0

Hello friend its my first question on stackoverflow i am facing problem in Json is not working with ajax. I am not able to understand and i didnt understood where problem. Myb code is following... I have action.php file If i am trying without json its working but i am using json is not get any response

<?php 
 $con = new mysqli("localhost", "root", "", "psycho"); /* REPLACE NECESSARY DATA INSIDE */

/* CHECK CONNECTION */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
 exit();
} 
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM question ORDER BY qid LIMIT 1")){
$stmt->execute(); /* EXECUTE THE QUERY */
$stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4); /* BIND THE RESULT TO THESE VARIABLES */
$stmt->fetch(); /* FETCH THE RESULT */
$stmt->close();
} /* END OF PREPARED STATEMENT */
?>
<h1 id="question"><?php echo $question; ?></h1>
<input type="hidden" id="qid" value="<?php echo $qid; ?>">
<input type="radio" name="a1" id="op1" value="<?php echo $opt1; ?>"><span id="op1text"><?php echo $opt1; ?></span><br/>
<input type="radio" name="a1" id="op2" value="<?php echo $opt2; ?>"><span id="op2text"><?php echo $opt2; ?></span><br/>
<input type="radio" name="a1" id="op3" value="<?php echo $opt3; ?>"><span id="op3text"><?php echo $opt3; ?></span><br/>
<input type="radio" name="a1" id="op4" value="<?php echo $opt4; ?>"><span id="op4text"><?php echo $opt4; ?></span><br/>
<input type="submit" name="submit" id="submit" value="Next"> <!-- THIS SERVES AS THE SUBMIT AND NEXT BUTTON -->
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
 $(document).ready(function(){
  $("#submit").click(function(){ /* WHEN SUBMIT IS CLICKED */
  var qid = $("#qid").val(); /* GET THE question id */
  var selected = $("input[type='radio'][name='a1']:checked");
  if (selected.length > 0) { /* CHECK THE SELECTED RADIO BUTTON */
    answer = selected.val();
  }
  $.ajax({
    type: "POST", /* THE METHOD WE WILL BE USING TO PASS THE DATA */
    url: "action.php", /* THIS IS WHERE THE DATA WILL GO */
    data: {"questionid" : qid, "answer" : answer}, /* THE DATA WE WILL BE PASSING */
    dataType : 'json',
    success: function(result){ /* WHEN IT IS SUCCESSFUL */
      /* THIS WILL REPLACE THE DATA IN OUR QUESTION PAGE */
      $("#qid").val(result.questionid);
      $("#question").html(result.question);
      $("#op1").val(result.op1);
      $("#op2").val(result.op2);
      $("#op3").val(result.op3);
      $("#op4").val(result.op4);
      $("#op1text").html(result.op1);
      $("#op2text").html(result.op2);
      $("#op3text").html(result.op3);
      $("#op4text").html(result.op4);
    }
  }); /* END OF AJAX */
});
});
 </script>

My second file code is here action.php

<?php
 if(isset($_POST["questionid"])){
/* INCLUDE OUR NEW ESTABLISHED CONNECTION HERE */
/* PUT HERE YOUR INSERT QUERY WHICH STORES THE USER'S ANSWERS */

/* THEN FETCH THE NEXT QUESTION */
if($stmt = $con->prepare("SELECT qid, question, opt1, opt2, opt3, opt4 FROM question WHERE qid > ? ORDER BY qid LIMIT 1")){
  $stmt->bind_param("i", $_POST["questionid"]);
  $stmt->execute();
  $stmt->bind_result($qid, $question, $opt1, $opt2, $opt3, $opt4);
  $stmt->fetch();
  $stmt->close();
} /* END OF PREPARED STATEMENT */

/* THIS SET OF DATA WILL REPLACE THE DATA IN OUR CURRENT QUESTION PAGE */
echo json_encode(array("questionid" => $qid, "question" => $question, "op1" => $opt1, "op2" => $opt2, "op3" => $opt3, "op4", => op4));
   } /* END OF ISSET */
?>
  • Are your `` elements within a `
    ` tag at all?
    – Phil Oct 09 '18 at 03:04
  • Check your browser's _Network_ console; what response is coming back for the AJAX POST request? – Phil Oct 09 '18 at 03:06
  • I suggest you also check out these posts... [How to get useful error messages in PHP?](https://stackoverflow.com/questions/845021/how-to-get-useful-error-messages-in-php) and [How to get MySQLi error information in different environments](https://stackoverflow.com/questions/22662488/how-to-get-mysqli-error-information-in-different-environments) – Phil Oct 09 '18 at 03:09

2 Answers2

2

You should include the following code to change the type of data in the header.

header('Content-Type: application/json');

Once you add this to your PHP code JQuery will be able to read the JSON Respons, this is because without specifying this content type, PHP naturally responds with a content type of HTML unless specified elsewhere.

FluxCoder
  • 1,266
  • 11
  • 22
  • 2
    It’s worth pointing out that without this header set, php is probably saying that the content type is HTML, so jquery thinks it’s html and not json, and so it’s not going to try to parse the json. (Just for a little further explanation of your answer.) A content type tells a browser (or any other client) what format the content is, because realistically it’s all just a big string of text, until you know how to parse it (is it json? is it html? is it javascript? is it xml? is it a picture? etc etc) – Nate Oct 09 '18 at 02:44
  • OP has `dataType: 'json'` so while this is generally good advice, it won't make a difference – Phil Oct 09 '18 at 03:04
-1

use this code:

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script>
     $(document).ready(function(){
      $("#submit").click(function(){ /* WHEN SUBMIT IS CLICKED */
      var qid = $("#qid").val(); /* GET THE question id */
      var selected = $("input[type='radio'][name='a1']:checked");
      if (selected.length > 0) { /* CHECK THE SELECTED RADIO BUTTON */
        answer = selected.val();
      }
      $.ajax({
        type: "POST", /* THE METHOD WE WILL BE USING TO PASS THE DATA */
        url: "action.php", /* THIS IS WHERE THE DATA WILL GO */
        data: {"questionid" : qid, "answer" : answer}, /* THE DATA WE WILL BE PASSING */
        dataType : 'json',
        success: function(data){ /* WHEN IT IS SUCCESSFUL */
          /* THIS WILL REPLACE THE DATA IN OUR QUESTION PAGE */

           var result = JSON.parse(data);              

          $("#qid").val(result.questionid);
          $("#question").html(result.question);
          $("#op1").val(result.op1);
          $("#op2").val(result.op2);
          $("#op3").val(result.op3);
          $("#op4").val(result.op4);
          $("#op1text").html(result.op1);
          $("#op2text").html(result.op2);
          $("#op3text").html(result.op3);
          $("#op4text").html(result.op4);
        }
      }); /* END OF AJAX */
    });
    });
     </script>