Ajax non functioning

OK. In my wonderful world of not knowing what I am actually doing in programming, I have run across the following problem:

I am attempting to add a section to a Work Order page of my website. The purpose is for the user to select a part from a drop down list, the webpage does an AJAX call, returns the data needed to the same page without a refresh. (Basically adding parts used on a job to the page) I have tried every AJAX example that I could find across the web, with no avail. Most of them allow me to click the submit button and the page just sits there and stares at my blankly.

         <tr><td><form id='Parts' action=''>Parts</td><td>"; 
   echo "<select name='Part'>";
      $mysqli = $conn;
      $query= $mysqli->query("SELECT DISTINCT * FROM Parts");

      while ($row = mysqli_fetch_array($query)) {
      echo "<option value='" . $row['PartName'] . "'>" .$row['PartColor'] . "&nbsp" .$row['PartName'] . "</option>";
    } ;  
   echo "</td><td><input type='submit' name='AddPart' value='Add Part'></form></td></tr><tr><td>";

This is the base code that I am using on the page.

The php file that I have is:

<?php

if (isset($_POST['AddPart'])) {
   $Part = $_POST['PartName'];
}

$sql = "SELECT * FROM Parts WHERE PartName = '$Part'";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
   echo "<table style='border-radius: 5px; color: white; position: absolute; left: 5%; top: 20%;'>";
   while($row = $result->fetch_assoc()) {
        echo "<tr><td><font color= '#EE9A00'>Qty</font></td><td width='10'></td><td><font color= '#EE9A00'>Part Name</font></td><td width='10'></td><td><font color= '#EE9A00'>Part Color</font></td><td width='10'></td><td><font color= '#EE9A00'>Part Description</font></td><td width='10'></td><td><font color= '#EE9A00'>Cost</font></td><td size='5'></td><td width='10'></td><td><font color= '#EE9A00'>Extended Cost</font></td></tr>
      <tr><td><input type='number' style='width:50'></input></td><td></td><td>" . $row["PartName"]. "</td><td width='10'></td><td>" . $row["PartColor"]. "</td><td width='10'></td><td>" . $row["PartDescription"]. "</td><td width='10'></td><td>" . $row["BillPrice"]. "</td><td></td><td></td></tr>
      </table>";
}
};
?>

What is the proper AJAX call to accomplish this? If it helps, I am using mySQL through Yahoo websites.

If there is a problem on the frontend, open the dev tools and see what the error that prevents it from happening is.

(F12)

I deleted all of the AJAX that I had, that I was using. I am looking for a direction to go to find the correct AJAX syntax to input into my page.

Before you can ‘ajax’ you need to be able to html/css/php/sql. You need to produce a complete working application without the ajax, then add it, because you will need all of the application’s html, css, php, and sql, organized and called in a slightly different order, when you add ajax.

So, what exactly is the overall goal of this application - to display items (parts), select an item and a quantity to add to a ‘shopping cart’, display the cart with a way of deleting items and modifying quantities, then submit the finalized cart to be stored as the items that are for an order/job?

Btw - you can put a whole html table inside of a form, you can put a whole form inside of one html table cell, but you cannot put a form inside of a table with different parts of the form spread between different html table cells.

Your <option value=’…’ should be the item id, not the item name and in most cases you should use css classes rather than to put css in-line in the html elements.

Also, in html5, to cause a form to submit to the same page, leave the action=’’ attribute out of the form tag (an empty action=’’ attribute is actually invalid.) The parts table should not have duplicates, so the DISTINCT is unnecessary. You should validate all input data before using it. You should use a prepared query when supplying external data to an sql query statement.

My suggestion would to use fetch (or $_Get in jQuery) as it simplifies coding, but you still need to understand XHR requests. I’m developing a quiz game the last 2 weeks and here’s my fetch request in vanilla javascript.

const quizUISuccess = function (parsedData) {
    console.log(parsedData);



    const records = parsedData.length;
    categoriesForm.style.display = "none";
    movieData = parsedData; // Store parsed data in global variable:

    container.setAttribute('data-records', records);

    dispQuiz();
    gameOverCheck();


};

/*
 * If Database Table doesn't load for some reason this is a fallback where
 * there's only 3 questions. 
 */

const quizUIError = function (error) {
    console.log("Database Table did not load", error);
    errFlag = true;
    movieData = [
        {
            id: 1,
            question: "What actor from the movie \"Dead Poets Society\" plays Dr. James Wilson on the TV show ",
            answer1: "Ethan Hawke",
            answer2: "Dylan Kussman",
            answer3: "Robert Sean Leonard",
            answer4: "James Waterston",
            correct: 3
        },
        {
            id: 7,
            question: "Who portrayed the Joker in \"The Dark Knight (2008)\"?",
            answer1: "Christan Bale",
            answer2: "Aaron Eckhart",
            answer3: "Michael Caine",
            answer4: "Heath Ledger",
            correct: 4
        },
        {
            id: 30,
            question: "Follow the Sun was about what real life golf pro?",
            answer1: "Bobby Jones",
            answer2: "Ben Hogan",
            answer3: "Arnold Palmer",
            answer4: "Jack Nicklaus",
            correct: 2
        }
    ];
    categoriesForm.style.display = "none";
    console.log('mData', movieData);
    container.setAttribute('data-records', movieData.length);
    dispQuiz();
    gameOverCheck();

};


/*
 * 
 * @param {type} response
 * Throw error response if something is wrong:
 * 
 */
const handleErrors = function (response) {
    if (!response.ok) {
        throw (response.status + ' : ' + response.statusText);
    }
    return response.json();
};

/*
 * 
 * @param {type} url
 * @param {type} succeed
 * @param {type} fail
 */

const createRequest = function (url, succeed, fail) {
    fetch(url)
            .then((response) => handleErrors(response))
            .then((data) => succeed(data))
            .catch((error) => fail(error));
};

You still need to know backend coding and in my case it’s PHP. In my case the PHP is pretty simple:

<?php

require_once '../private/initialize.php';

use Library\Trivia\Trivia;

/* Makes it so we don't have to decode the json coming from JQuery */
header('Content-type: application/json');

$trivia = new Trivia();


$category = htmlspecialchars($_GET['category']);
$api_key = htmlspecialchars($_GET['api_key']);

if ($api_key === $_SESSION['api_key']) {
    if (isset($category)) {
        $data = $trivia->read($category);
        output($data);
    }
}

function errorOutput($output, $code = 500) {
    http_response_code($code);
    echo json_encode($output);
}

/*
 * If everything validates OK then send success message to Ajax / JavaScript
 */

function output($output) {
    http_response_code(200);
    echo json_encode($output);
}

One benefits of using fetch (or $_get) is you don’t have to worry about nasty callbacks.

HTH John

Sponsor our Newsletter | Privacy Policy | Terms of Service