[javascript] How do I debug jquery AJAX calls?

I have been working on trying to get AJAX to work with Jquery. My big issue so far has been that I don't really know how to figure out where I'm making a mistake. I don't really have a good way to debug AJAX calls.

I'm trying to set up an admin page where one of the functions I want to make is to change the permission set in my SQL database. I know that the .click function is being triggered, so I've narrowed that down, but I'm not sure where in the chain from AJAX call to SQL query its going wrong.

My .js code:

$('#ChangePermission').click(function(){
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
        'user': document.GetElementById("user").value,
        'perm': document.GetElementById("perm").value
        }
    })
})

my .php handler:

<?php  
require_once(functions.php);

echo $_POST["user"];

try{
    $DBH = mysql_start();

    $STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");

    $STH->bindParam(1, $_POST["user"]);
    $STH->bindParam(2, $_POST["perm"]);

    $STH->execute();
}
catch(PDOException $e){
    echo $e->getMessage;
}?>

Where the mysql_start is setup for the PDO function that I use successfully in my other SQL calls.

I have been researching and looking up tutorials for a few days now and I can't for the life of me figure out what's going wrong. Are there tools I can use to figure out where the error is occuring? I'm obviously interested in the answer to this specific issue, but I think my bigger issue here is that I have no idea where to start with debugging. Thanks for your help!

This question is related to javascript php jquery ajax

The answer is


2020 answer with Chrome dev tools

To debug any XHR request:

  1. Open Chrome DEV tools (F12)
  2. Right-click your Ajax url in the console

Chrome console Ajax request

for a GET request:

  • click Open in new tab

for a POST request:

  1. click Reveal in Network panel

  2. In the Network panel:

    1. click on your request

    2. click on the response tab to see the details Chrome Network panel's response tab


Just add this after jQuery loads and before your code.

$(window).ajaxComplete(function () {console.log('Ajax Complete'); });
$(window).ajaxError(function (data, textStatus, jqXHR) {console.log('Ajax Error');
    console.log('data: ' + data);
    console.log('textStatus: ' + textStatus);
        console.log('jqXHR: ' + jqXHR); });
$(window).ajaxSend(function () {console.log('Ajax Send'); });
$(window).ajaxStart(function () {console.log('Ajax Start'); });
$(window).ajaxStop(function () {console.log('Ajax Stop'); });
$(window).ajaxSuccess(function () {console.log('Ajax Success'); });

here is what I would do in order to debug and get the php errors into javascript console.log after an ajax call:

    $('#ChangePermission').click(function () {
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
            'user': document.GetElementById("user").value,
            'perm': document.GetElementById("perm").value
        },
        success: function (data) {
            console.log(data);  
        },
        error: function (data) {
            console.log(data);
        }
    });
});

on the php side I would start by asking for all error returned to string concat and echo as a json encoded response that will includes php error messages as well if any.

<?php

error_reporting(E_ALL);
require_once(functions . php);
$result = "true";
$DBH = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass);  
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$STH = $DBH->prepare("INSERT INTO people ( username, permissions ) values (?, ?)");

if (isset($_POST["user"]) && isset($_POST["perm"])) {
    $STH->bindParam(1, $_POST["user"], PDO::PARAM_STR);
    $STH->bindParam(2, $_POST["perm"], PDO::PARAM_STR);
}
try {
    $STH->execute();
} catch (PDOException $e) {
    $result .= $e->getMessage;
}
echo json_encode($result);
?>

You can use the "Network" tab in the browser (shift+ctrl+i) or Firebug.
But an even better solution - in my opinion - is in addition to use an external program such as Fiddler to monitor/catch the traffic between browser and server.


Using pretty much any modern browser you need to learn the Network tab. See this SO post about How to debug AJAX calls.


you can use success function, once see this jquery.ajax settings

 $('#ChangePermission').click(function(){
    $.ajax({
        url: 'change_permission.php',
        type: 'POST',
        data: {
        'user': document.GetElementById("user").value,
        'perm': document.GetElementById("perm").value
        }
       success:function(result)//we got the response
       {
        //you can try to write alert(result) to see what is the response,this result variable will contains what you prints in the php page
       }
    })
})

we can also have error() function

hope this helps you


if you are using mozilla firefox than just install an add-on called firebug.

In your page press f12 in mozilla and firebug will open.

go for the net tab in firebug and in this tab go in the xhr tab. and reload your page. you will get 5 options in xhr Params Headers Response HTML and Cookies

so by going in response and html you can see which response you are getting after your ajax call.

Please let me know if you have any issue.


Install Firebig to see where your error is happening. You could also set up a callback in your ajax call to return your error messages from your PHP. Eg.

error: function(e){
     alert(e);
     }

Firebug as Firefox (FF) extension is currently (as per 01/2017) the only way to debug direct javascript responses from AJAX calls. Unfortunately, it's development is discontinued. And since Firefox 50, the Firebug also cannot be installed anymore due to compatability issues :-( They kind of emulated FF developer tools UI to recall Firebug UI in some way.

Unfortunatelly, FF native developer tools are not able to debug javascript returned directly by AJAX calls. Same applies to Chrome devel. tools.

I must have disabled upgrades of FF due to this issue, since I badly need to debug JS from XHR calls on current project. So not good news here - let's hope the feature to debug direct JS responses will be incorporated into FF/Chrome developer tools soon.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios