Ajax to PHP to Ajax

I am trying to send some data to Php with Ajax and then sending back a result to Ajax. Thing is that Ajax gives me an empty error and I cant find what the problem is. Is there something wrong in the PHP script?

Ajax code

$.ajax({
        type: POST,
        url: PHPfileLink,
        data: {'data1': test, 'data2': asd},
        success:function(data){
             document.getElementById('testDiv').innerHTML = data;
        },
        error:function(request,textStatus,error){
            alert(error);
        }
    });
 }

PHP code

<?PHP

//$a = $_POST['data1'];
//$b = $_POST['data2']

$name = "qwerty";
$age = 100;

$arr = array('name' => $name, 'age' => $age);

echo json_encode($arr);

What I do is try to get it to work it straight PHP then insert Ajax into the mix, plus also using the browser web development tools (console) to debug the Ajax portion will help you out tremendously.

Instead of

document.getElementById('testDiv').innerHTML = data;

using console you would do this
console.log("My data is ", data);

1 Like

Thanks for the answer. Thing is that i cant get the data, it only gives me an empty error.
I did however update my php code:

This does not work

<?PHP
...
...
...

$name = $row['name'];

$arr = array('name' => $name, 'age' => 100);

echo json_encode($arr);

This works, when only sending hardcorded strings back to Ajax. So there probably is a problem with DB connection or something but i dont get any errors from it? I probably have to post whole code but i am on my mobile device atm so i dont have the code in front of me so ill post it later.

<?PHP
...
...
...

$name = $row['name'];

$arr = array('name' => 'Name', 'age' => 100);

echo json_encode($arr);

I find it easier to use a tool designed for testing API’s before connecting the frontend to it. Fiddler by Telerik or Postman are both great tools.

To simplify your debugging, got to the page you are trying to access, and make sure that error reporting is turned on. Whatever the page displays, is what you are getting when you do the ajax request. It gets more complicated, but based on the code you are showing, I don’t see any hurdles that this would exclude at this point. It is highly likely that their is an issue with either the database connection, or the query itself, but error reporting being turned on should show if it is that.

1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service