-1

I am passing json object to my php file through ajax call.

jQuery Syntax

$.getJSON('http:..Sample/JsonCreation.php', function(data)
{
   //data has the json - I am trying to edit this json and then pass it to another php file through ajax and save in DB. I have successfully edited but unable to access the passed json in my php file.
   questionsArray = data;
}
$('form').on('submit', function(event)
{
//AJAX CALL
                $.ajax
                ({
                    url: "updateTestReport.php",
                    type: "post",
                    //JSON.stringify
                    data: {json:(questionsArray)},
                    contenttype: "application/json; charset=utf-8",
                    datatype: "text",

                    success: function(data)
                    {
                        //alert("success");
                        alert(data);
                    },
                    error:function()
                    {
                        alert("failure");
                    }
                });
});

PHP FILE

<?php

//$contentjson = file_get_contents("php://input");
//echo $_POST['json'];
$questionsArray = json_encode($_POST['json']);
echo $questionsArray;


?>

OUTPUT:

[{"questionNumber":"1","quesDesc":"The price of petrol has increased by 25%.By what percentage should it now be reduced to return to the original price?","optionA":"25%","optionB":"20%","optionC":"15%","optionD":null,"correctOption":"A","selectedAnswer":null,"isQuestionViewed":null},{"questionNumber":"2","quesDesc":"Price of cooking gas has increased by 10%. By what percentage should consumption be reduced to keep expenditure unchanged?","optionA":"9.09%","optionB":"10%","optionC":"11.11%","optionD":null,"correctOption":"A","selectedAnswer":null,"isQuestionViewed":null},{"questionNumber":"3","quesDesc":"A buys a shirt for Rs 100 and sells it to B for Rs 120. B now sells it to C for Rs 144. Had A sold it directly to C at the price C paid for it, then his profit % would have been","optionA":"10%","optionB":"20%","optionC":"44%","optionD":null,"correctOption":"C","selectedAnswer":null,"isQuestionViewed":null}]

1) How is that json_encode in the php file gives the output. Shouldn't i use json_decode? 2) And even through the encoded json, i am not able to retrieve the values. Please let me know how to access the values from this json... 3) what is the difference between file_get_contents & $_POST['json']?

EDIT: //BEGIN

I need to access my json inside the php file, retrieve some values, make some calculations, save in DB. Then return to the main html file.

//END Kindly give clear explanation...

3 Answers 3

2

Like I am giving you an example for the ajax for submission. form#data -> #data is the id of the form

<script>
    $("form#data").submit(function() {
        if($("form#data").validationEngine('validate') != true){
         return false;
         }
        var formData = new FormData($(this)[0]);

        $.ajax({
            url: '/test/test.php',
            type: 'POST',
            data: formData,
            async: false,
            success: function(data) {
                data = jQuery.parseJSON(data);
                if (data.result == true) {
                    alert('Your details updated successfully.');
                }
                else if (data.result == false) {
                    alert("Your details not updated!");
                }
            },
            cache: false,
            contentType: false,
            processData: false
        });

        return false;
    });
</script>

Now I am showing you the test.php which was requested on ajax call.

<?php
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && ( $_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' )) {
    $mt = $_POST['tmt'];
    if($mt!=NULL){
            $res11['result']=TRUE;
        }else{
            $res11['result']=FALSE;
        }
        echo json_encode($res11);
}
?>

This is the php file which get the data through the ajax post. If you have any queries or other queries, you can ask.

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

Comments

0

You want to convert or fetch the array which you have encoded in php. I have given you the solution for the ajax

<script>
            $.ajax
                    ({
                        url: "updateTestReport.php",
                        type: "post",
                        //JSON.stringify
                        data: {json: (questionsArray)},
                        contenttype: "application/json; charset=utf-8",
                        datatype: "text",
                        success: function(data)
                        {
                            /*
                             * Below this comment you can also use 
                             * data = jQuery.parseJSON(data);
                             * It will decode json encoded
                             */
                            data = jQuery.parseJSON(data);
                            alert(data.questionNumber);
                            alert(data.quesDesc);
                            /*
                             * put the array keys using the period in between with data variable
                             * 
                             */
                            alert(data);
                        },
                        error: function()
                        {
                            alert("failure");
                        }
                    });
        </script>

Please let me know if you have any queries.

9 Comments

Sorry if i haven't placed my query clearly.I need to access json inside the php file.... I am echo'ing in my php just to check the output...
@vivin You can use json_decode($_POST['json']) for your php and can use the array
I did try @Avi. But in my alert it gives a huge message having html content - <br /> <font size = '1'> <table.....
@vivin This is kind of error. Will you please tell me exact message which is coming as alert.
I found the warning message... json_decode()expects parameter 1 to be string, array given in... I am trying to use JSON.stringify. But even the preventDefault() action of the submit button is not executed. Why is it so?
|
0

If you are directly printing the values by alert, it will display [Object] because the response is in JSON format. Try alert(res[0].questionNumber), this will display first questionNumber

Try something like this to access the values

success: function(res)
{
 for(var i=0;i<res.length;i++)
 {
    qno = res[i].questionNumber;
    desc = res[i].quesDesc;
    // and so on
    // do whatever you want this data
 }
},

1 Comment

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.