0

This is the jquery ajax part in which i have sent json data to the php file.

$(function () {
 $('form').submit(function () {
   var fields = $(this).serializeArray();
   var ans_json = JSON.stringify(fields);
   console.log(ans_json);

   $.ajax({
     url: "results.php",
     type: "POST",
     data: ans_json,
     dataType: "json",
     success: function (result) {
       console.log(result);
     }
   });
   return false;
 });
});

Now i want to use this json data sent to the php page.How can i do it? I have done it this way but it returns null.

<?php
   echo json_decode('ans_json');
?>

I have a set of 10 questions which need to be answered. 3 questions were answered so got the below result.This is what i got in my console.

 [{"name":"answer_9","value":"a"},{"name":"answer_10","value":"a"}] quizzes.php:14

null

2 Answers 2

2

You don't need to decode any JSON string at server-side if you encode properly your parameters.

You can use .serialize() to do the form serialization for you, and it's ready to send.

$(function () {
  $('form').submit(function () {
    var serialized = $(this).serialize();

    $.ajax({
      url: "results.php",
      type: "POST",
      data: serialized,
      ...
    });

    return false;
  });
});

Your parameters will be available in your $_POST as in any normal POST request. For example,

$ninth_answer = $_POST["answer_9"];
Sign up to request clarification or add additional context in comments.

2 Comments

Thanx it worked now, but what should be the dataType now?Is it json or somrthing else?
dataType is for the server's response, not for the request. It depends of what you are returning
1

You need to decode the POST variable. Currently you're decoding just a string which even isn't valid JSON.

<?php
$json_arr = json_decode($_POST['my_json'], true);
var_dump($json_arr);
echo "First name in json is:". $json_arr[0]['name'];
?>

and edit your javascript to reflect following: This posts my_json parameter with your json as an value. This makes it easy for PHP to recieve it using $_POST.

$.ajax({
 url: "results.php",
 type: "POST",
 data: {"my_json": ans_json},
 dataType: "json",
 success: function (result) {
   console.log(result);
 }
});

I suggest to read a little about those things:

http://api.jquery.com/jQuery.ajax/

https://www.php.net/manual/en/function.json-decode.php

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.