3

The newNet.php runs and correctly creates the new entry. The netID variable is an auto increment so it is created automatically. My goal is to then retrieve it and use it in the showActivities() function to display the record just created. For example it should resolve like this; showActivities(55);

The problem is the SQL always returns the previous value of netID, 54 instead of 55; If I say echo $result + 1; Then, according to page source it shows the correct number is being resolved in the showActivities function but the function can't find and return the data. But looking at the DB it has successfully been inserted.

So step by step:

  1. newNet.php runs, it adds a record to a MySQL db
  2. get the netID value just created in #1
  3. pass it to showActivities() which displays it on the page.

How can I get what I want here? It would seem that the DB does not get updated fast enough to accommodate the request from showActivities(), is this possible?

 function newNet(str) {
   str = str;
     var xmlhttp = new XMLHttpRequest();
     xmlhttp.onreadystatechange = function() {
       if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
         document.getElementById("status").innerHTML = xmlhttp.responseText;
     }}

     xmlhttp.open("POST", "newNet.php", true);
     xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
     xmlhttp.send("q="+str);

     showActivities(<?php $stmt=$db_found->prepare("select max(netID) as netID from netLog limit 1");
       $stmt->execute();
       $result=$stmt->fetchColumn();
       echo $result;
     ?>);
 }
Mouser
  • 13,132
  • 3
  • 28
  • 54
Keith D Kaiser
  • 1,016
  • 2
  • 14
  • 31
  • 1
    Asynchronous problem. You ordered a pizza and want to eat it before it's baked. – Mouser Aug 10 '15 at 20:30
  • db speed has nothing to do with it. you're trying to eat the pizza before you even finish hanging up the phone after calling the pizza joint to order it. – Marc B Aug 10 '15 at 20:33
  • and you're mixing PHP and Javascript. the php executes **ONCE** on the server, and you'll have "hardcoded" that max(newid) value in your page's JS until the page gets reloaded. – Marc B Aug 10 '15 at 20:34
  • I understand the analogy, and now I'm hungry.. thank you very much. But I don't know how to fix it. What should I be doing? – Keith D Kaiser Aug 10 '15 at 20:42

1 Answers1

2

Two problems here:

  1. As I said in the comment your problem has to do with the asynchronous nature of AJAX. The request actually needs time to process. But your code will immediately start executing showActivities, so no results are back from the request, because that is still "baking".

  2. Your PHP code is rendered upon page load. So the old value will be loaded from the database. On page load it will be 54. You can fire that Ajax request ten times and netID will still be 54 since PHP is run server side and not client side.

How to fix this:

You have a xmlhttp.onreadystatechange function which listens to the request and fires everytime a step is done. This is called a callback function. At step 4 the pizza is done and 200 means it isn't burned and actually looks good. When the status is like this data is returned and can be accessed.

 var xmlhttp = new XMLHttpRequest();
 xmlhttp.onreadystatechange = function() {
   if (xmlhttp.readyState === 4 && xmlhttp.status === 200) {
     document.getElementById("status").innerHTML = xmlhttp.responseText;
     //execute all relevant code that needs data from server from here.
     showActivities(xmlhttp.responseText);
 }}

In newNet.php you should execute the PHP code that is now in the arguments bit of showActivities(). Execute this after the script has done its inserts to the database.

   $stmt=$db_found->prepare("select max(netID) as netID from netLog limit 1");
   $stmt->execute();
   $result=$stmt->fetchColumn();
   echo json_encode($result);

You can json_encode the result. This way it is printed as JSON to the page. We can load this variable into a JavaScript variable.

function showActivities(data)
{
   //remember data is a JSON string, time to convert it into JavaScript
   var netID = JSON.parse(data);
   alert(netID); //should show the highest netID
}

Learn more:

To sum up

  • PHP is always ran before the page is loaded and cannot be ran again without reloading the page. For that XMLHttpRequest was invented.
  • XMLHttpRequest takes time to complete, a callback must be used to process its results.
Community
  • 1
  • 1
Mouser
  • 13,132
  • 3
  • 28
  • 54
  • OK, I see what you're saying. However the newNet.php program actually is the code that inserts the new row into the DB in the first place. After it runs and the new row is in place I want to get the netID that was created for use in a stand alone program.... wait, wait... as I type stuff is coming to me. Are you saying both PHP codes should be passed at the same time to the server for processing? Hmmmm! – Keith D Kaiser Aug 10 '15 at 20:48
  • No code is passed to the server for processing by the `XMLHttpRequest` just some arguments via the `querystring`. The actual processing is done on the server in `newNet.php`. PHP also works with a single thread. First it runs the call to the DB and after that it could retrieve the new id and print it to the page which on its turn is send back to `XMLHttpRequest` object where you can retrieve the new id. – Mouser Aug 10 '15 at 20:52
  • I'm starting to get the idea. I'll work on it a bit and let you know how I do. Thank you very much for the help. Truly appreciate it. – Keith D Kaiser Aug 10 '15 at 20:58
  • I'm still struggling a little here Mouser not because you didn't explain it well enough but because I'm not quite catching on as well as I should. On top of that I realize now I lied to you a little. The netID is not an auto increment, I actually have to go find out what it is. So in my newNet.php the first SQL selects the max(netID) out of the table along with other information. That in turn gets used to do the insert to create the new row. YIKES! I'm guessing that after the insert I should do yet another SQL this time to pull the newly created row and its very important netID number?? – Keith D Kaiser Aug 11 '15 at 14:29
  • I moved showActivites(xmlhttp.responseText) as you suggested above and removed it from the bottom of the newNet() function. Then in newNet.php I used your code to create the jason encoding. But I guess I don't know what to do with it there. I don't understand the use of the function you created above. Your doing a bang up job but I'm not... I'm too new at this I guess. Thanks. – Keith D Kaiser Aug 11 '15 at 14:57
  • Please read into JSON. It's a way of transferring data on a uniform way between languages (just like XML, but with less overhead). The JSON simply transfers your `netID` from PHP to JavaScript. It gets encoded to JSON by PHP's `json_encode` server side and decoded by JavaScript's `JSON.parse` on the client side. The benefit of using JSON with just a simple integer isn't apparent. However you can also transfer complete SQL result sets with it. – Mouser Aug 12 '15 at 11:17