0

Here is my code. I keep getting a json parser error. The ajax never goes into done. Help!

<input type="submit" class="button" name="insert" value="load"/>
<div id="wines">
    <!-- Javascript will print data in here when we have finished the page -->    
</div>
jQuery(document).ready(function() {
    var $ = jQuery;
    var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');

    $('.button').click(function(){ // This event fires when a button is clicked
        var button = $(this).val();
        $.ajax({ // ajax call starts
            url: baseUrl, // JQuery loads serverside.php
            data: 'action=' + $(this).val(), // Send value of the clicked button
            dataType: 'json', // Choosing a JSON datatype
        }).done(function(data) { // Variable data contains the data we get from serverside
            console.log("j");      
        }).fail(function(data,error) { 
            console.log(error);  
       })
    });
});
<?php
    $action = req('action');
    // Red wine table
    $red = array('Chianti', 'Barolo', 'Pinot Noir');
    $white = array('Chardonnay', 'Cava', 'Chablis');

    // Combine red and white tables into one multidimensional table

    $winetable = array(
      "red" => $red,
      "white" => $white,
    );

    // Finally depending on the button value, JSON encode our winetable and print it
    if ($action == "load") {
          print json_encode($red);
          header('Content-Type: application/json');
    }
?>

UPDATE: Error message shows this in the console:

"Initializing System Events for WUH..." common_admin.js:22
"["Chianti","Barolo","Pinot Noir"]
<input type="submit" class="button" name="insert" value="load"/>
<div id="wines">
  <!-- Javascript will print data in here when we have finished the page -->
</div>


<script type="text/javascript">
jQuery(document).ready(function() {

    var $ = jQuery;
    var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');

  $('.button').click(function(){ // This event fires when a button is clicked
    var button = $(this).val();
    $.ajax({ // ajax call starts
      url: baseUrl, // JQuery loads serverside.php
      data: 'action=' + $(this).val(), // Send value of the clicked button
      dataType: 'json', // Choosing a JSON datatype
    })
    .done(function(data) { // Variable data contains the data we get from serverside
      console.log("j");      
    })
    .fail(function(data,error) { 
      console.log(data.responseText+error);  
     })
  });
});
</script>parsererror"
9
  • 1
    What is the exact response of the request? You can check it in the network tab of the console. Also note that your PHP code never sets the $action variable, so it will never enter your if statement Commented Apr 8, 2016 at 7:12
  • 1
    I dont think you need that header at the end Commented Apr 8, 2016 at 7:14
  • In the response, there is SyntaxError:JSON.parse:unexpected non-whitespace character after JSON data at line 2 column 5 of the JSON data. Commented Apr 8, 2016 at 7:16
  • 1
    You cannot send headers after output Commented Apr 8, 2016 at 7:16
  • I removed the headers. While there is no SyntaxError in the response, it still goes to the ajax fail. Commented Apr 8, 2016 at 7:18

2 Answers 2

3

First, you should print your headers BEFORE sending any body, else you may encounter classical headers errors:

Warning: Cannot modify header information - headers already sent by (...)

For this you should move your headers() call BEFORE print json_encode(...), like this:

// Finally depending on the button value, JSON encode our winetable and print it
if ($action == "load") {
      header('Content-Type: application/json');
      print json_encode($red);
}

Next, as you might have other instructions runned after printing your JSON, you should, as @PranavBhaat said, add a die or exit statement at the end of your script so you're sure nothing else is outputted and the JSON is correctly parsed by your AJAX call.

Sign up to request clarification or add additional context in comments.

Comments

0

You need to end-up your ajax response call with exit();

if ($action == "load") {
          echo json_encode($red);
          exit(); 
}

and print will let you formatted output which not required, I think.

so just echo also been working.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.