javascriptphpajaxcircular-queue

AJAX does not return anticipated response


I'm trying to start to use AJAX to

  1. send a Javascript variable from one PHP file to another
  2. that will enqueue it to a queue function I have created
  3. and then peek that ID in the queue by changing the < p > tag in my main file

EDIT:

I get an error now that I have added an error parameter; either [Object Object] or Undefined and console.log(data) the error is a POST 500 jquery.js

I have tried solutions to add .d after data, altering the dataType to match the response from the Networks panel in Dev Tools, json_encode in the PHP file, but no luck.

Javascript:

var log = document.getElementById("log"); //ID of the  <p> tag to change to ID number

document.getElementById("scanButton".addEventListener("click", async () => {

try{

/*functions to obtain ID number*/

var IDnumber = 0000; //functions will change this value after every click



$.ajax({
    type: "POST",
    url: "savetodb.php", 
    data: { idNumber : IDnumber },
    success: function(data){
        log.innerHTML = data;
    },
    error: function(error) {
        log.innerHTML = error;
    }
  });
  
  
  
} catch (error){
      log.innerHTML = error;
});

PHP:

$idNumber = $_POST['idNumber'];

/*queue methods and functions*/

public function peek() { 
  return $this->queue[$this->front]; 
}

$queue = new CircularQueue(15);
$queue->enqueue($idNumber);
echo $queue->peek();

Networking Page in DevTools for savetodb.php


Solution

  • Try to catch error through parameter "error" instead of using try catch.

    $.ajax({
        type: "POST",
        url: "savetodb.php", 
        data: { idNumber : IDnumber}, 
        success: function(){
            log.innerHTML = ("ID : " + IDnumber + " logged successfully!");}
        },
        error: function(error) {
            log.innerHTML = error.responseText;
        }
    );
    

    https://api.jquery.com/jquery.ajax/