0

I'm making a simple AJAX call to a server side PHP script but the success callback is never executed. Instead, under the error callback I get the error 'parsererror'. I've searched stackoverflow and have tried everything but nothing works.

If I try to load the URL to the PHP script with relevant fields, in this case http://....../matching.php?cmd=generate&N=2&M=3, I'll get a proper piece of data in JSON format which is returned. For e.g.

{"N":"2","M":"3","E":[[1,1,39],[0,3,100],[2,1,50]]}

AJAX CALL

$('form').on('submit', function(event) {
        event.preventDefault();
        $.ajax({
            url: 'matching.php',
            dataType: 'json',
            contentType: 'json',
            type: 'GET',
            data: {
                cmd: "generate",
                N: $('#n1').val(),
                M: $('#n2').val()
            },
            success: function(data) {
                alert(data);
                leftCount = data.N;
                rightCount = data.M;
                returnedArray = data.E;
                generateFirstPage();
            },
            error: function(request,error) { 
                alert(request.responseText);
                alert(error);
            }
        });

    })

PHP

<?php

if (isset($_GET['cmd'])) {
    $n = $_GET["N"];
    $m = $_GET["M"];
    echo json_encode(generateEdges($n, $m));
    exit;
}

function generateEdges($n, $m) {
    $edgeNumber = rand($n,$n*2);
    $e = array();
    for($i=0; $i<$edgeNumber; $i++) {
        array_push($e, array(rand(0,$n), rand(0,$m), rand(1,100)));
    }
    return $finalArray = array('N' => $n, 'M' => $m, 'E' => $e);
}

?>

Doing a console.log(request.reponseText) will give

{"N":"2","M":"3","E":[[1,0,42],[1,3,48],[0,3,44],[0,0,8]]}
CHEWWWWWWWWWW
  • 169
  • 3
  • 20

1 Answers1

0

I believe the error is that your AJAX call isn't actually hitting your matching.php file. I copied your code into 2 files of my own, 1 with the HTML and the javascript included (though I did wrap the javascript with a $(document).ready(function() { ... }), but that doesn't seem to be your problem).

When I hit submit, calling my own "matching.php" but leaving that file empty, I get the same parsererror you mention. If I then have matching.php execute the code you provided, it hits the success condition and everything is fine. I don't think the issue is the PHP or even your javascript, necessarily, just where it's looking for matching.php.

Use Firebug or Chrome's developer javascript console to view the ajax network call to see if it actually hits it. This may just be a symptom of a different problem, but it's worth double checking, imo.

Davis
  • 856
  • 4
  • 11