Need to pass an array to PHP and for the PHP script to take control

I am writing a bank reconciliation script. I have managed to mark and unmark items, keep track of the total and which items are marked, but now I need to pass the array of marked items back to a PHP script to update the database when the Continue button is pressed. And I’m stumped!

I was thinking I could do it as an Ajax call but I want to pass control to the PHP script and not return. I have been wondering whether I need to change my approach and make an Ajax call every time a checkbox is clicked and keep track in a Session variable(array).

This is my JS

let mtch = 0;
const frm = document.getElementById("stmt");
const ips = frm.getElementsByTagName("input");
const mxi = document.getElementById("mxitem");
const drs = frm.getElementsByClassName("dr");
const crs = frm.getElementsByClassName("cr");
const stb = Number(document.getElementById("stmtbal").innerHTML);
const done = document.getElementById("donebrec");
let a = [];
for (let c = 0; c < ips.length; c++) {
  ips[c].addEventListener("click", function() {
    if (ips[c].checked == true) {
      mtch = mtch + Number(crs[c].innerHTML) - Number(drs[c].innerHTML);
      a.push(ips[c].dataset.value);
    } else {
      mtch = mtch - Number(crs[c].innerHTML) + Number(drs[c].innerHTML);
      let i = a.indexOf(ips[c].dataset.value);
      if (i > -1)
        a.splice(i, 1);
    }
    mxi.innerHTML = mtch.toFixed(2);
    if (mtch.toFixed(2) == stb.toFixed(2)) {
      mxitem.style = "color:green";
      done.style = "display:block";
    } else {
      mxitem.style = "color:red";
      done.style = "display:none";
    }
  });
}

and there’s a working page here: gand alf4 58.c o.uk/v irgo/b ankr ec2.html

If you want to pass control to php, you need to send the information as an ajax request and give it the name of a function to carry on processing when it receives data from the server.

A Guide to Vanilla Ajax Without jQuery

Edit:

Well strictly speaking, you don’t need to give it a function. That’s only done if you want the JavaScript to carry on from somewhere afterwards.

1 Like

Thanks Paul. The method of using Ajax in that article is quite different from the one described in Javascript Novice to Ninja. I guess this might be more appropriate for a non-returning function…

As an aside, even though you’ve ‘passed control’ to the PHP script, the user end of the script is still in Javascript’s control, and you should at least verify that the PHP script received your request (check that the status came back 200).

If the PHP script is going to take a long time, then I would have the PHP system establish an effective queue - return immediately a notification to the user that the request was received, and simultaneously fork off a secondary process to handle execution.

(Updating a database shouldn’t qualify as ‘a long time’, usually.)

1 Like

I’ve realised I don’t actually need to pass control to the PHP script after all. It can do the db updates and return to the JS script, which seems cleaner.

1 Like

I should clear up a potential misunderstanding here.

Ajax doesn’t pass control. Instead, the JavaScript keeps on executing its own code at the same time that the Ajax data is being sent. When the JavaScript code has finished executing, any event handlers of yours waits for a trigger, such as a response from an Ajax process, and then executes more code that way.

Thanks, yes I understand. My original idea was to use a form and pressing the submit button would start an Ajax process and “go to” another PHP script. I see now that’s a crazy idea (even if it could work). I’m now going to use a button to start the Ajax process and continue in the same PHP script.

BTW what is the difference (apart from the obvious syntax) between the 2 ways of initiating an Ajax request described in A Guide to Vanilla Ajax Without jQuery and Javascript Novice to Ninja? I have managed to get the latter method to work but not the former.

for the sake of those that might come after, what syntaxes were tried?

I have got thus far putting the Ajax call in an event listener, and it works as far as it goes, but I cannot get the code to deal with the response to work. TBH I’m not sure where it belongs - clearly within the event listener (I think), but otherwise I’m flummoxed.

const stg3 = document.getElementById("stage3");
stg3.addEventListener("click", function() {
  const msg = document.getElementById("message");
  const xhr = new XMLHttpRequest();
  xhr.open('GET', 'bankrec3.php?c=1');
  xhr.send(null);
});

Update. The following works after a fashion:

const stg3 = document.getElementById("stage3");
stg3.addEventListener("click", function() {
  const msg = document.getElementById("message");
  const xhr = new XMLHttpRequest();
  xhr.onreadystatechange = function() {
    if (xhr.readyState == 4 && xhr.status == 200) {
      msg.innerHTML = xhr.responseText;
    }
  };
  xhr.open('GET', 'bankrec3.php?c=1');
  xhr.send(null);
  stg3.disabled = true;
});

Oh dear - it’s time to try and track down those resources to find out what they are.

A Guide to Vanilla Ajax Without jQuery

Uses node in an August 2015 article to explore ajax using xmlhttprequest, resulting in the following code that doesn’t require node.

var oReq = new XMLHttpRequest();
oReq.onload = function (e) {
    results.innerHTML = e.target.response.message;
};
oReq.open('GET', e.target.dataset.url + '?' + new Date().getTime(), true);
oReq.responseType = 'json';
oReq.send();

JavaScript From Novice to Ninja uses a more modern promise-based type of JavaScript code, involving fetch and then

A relevant example from Chapter 13 of the book is:

const task = {
  userId: 1,
  title: form.task.value,
  completed: false
};
const data = JSON.stringify(task);
const url = 'https://jsonplaceholder.typicode.com/todos';
const headers = new Headers({
  'Accept': 'application/json',
  'Content-Type': 'application/json'
});
const request = new Request(url, {
  method: 'POST',
  header: headers,
  body: data
});
fetch(request)
  .then( response => response.json() )
  .then( task => console.log(`Task saved with an id of ${task.id}`) )
  .catch( error => console.log('There was an error:', error))
2 Likes

Finally realised why I couldn’t get the response code in A Guide to Vanilla Ajax Without jQuery to work, there’s a missing curly bracket at the end of the line

if (xhr.status === 200)

:slight_smile:

1 Like

Oops. Sorry about that Gandalf. I’ve updated the article and fixed the mistake.

3 Likes

I’m a special kind of wombat for not spotting it sooner!

2 Likes

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.