4

I am having trouble sending $_POST data via jQuery Ajax. I have read over everything I can find regarding the matter and still I am getting nowhere. I have even gone back to very basic data and still nothing, the JSON data has been validated using the JSON validate site. For the life of me I cannot echo/print_r/var_dump or get access to any data.

My JavaScript:

$('#updateJSON').click(function(){
    var content = [{
                        "id": 21,
                        "children": [{
                            "id": 196
                        }, {
                            "id": 195
                        }, {
                            "id": 49
                        }, {
                            "id": 194
                        }]
                }];
    var someText = "someText";
        $.ajax({
             type: 'POST',
             url: 'test.php',
             data: {data: content},
             cache: false,
             success: function(){  
                 alert("success");
                 console.log(content);
                 window.location = "test.php";
             },
             error:function(){
                 alert('ajax failed');    
             }   
        }); 
}); 

My PHP:

<?php
if(isset($_POST['data'])) {
    $json = stripslashes($_POST['data']);
    var_dump(json_decode($json, true));
} else {
    echo "No Data";
}
?>

So I do get the alert("success"), and then get redirected to test.php once at test.php I get the echo "No Data".

Thanks in advance for any help with this issue.

5
  • 3
    What does test.php have? The JSON is going to be gone on the redirect, you aren't storing it anywhere. Does your console log have the JSON? Commented Jul 31, 2016 at 13:17
  • 1
    are you sure you want to redirect to test.php? you would already get the result (=the var_dump) of test.php in success-callback if you would read it: success: function(response) { console.log(response); } Commented Jul 31, 2016 at 13:24
  • @chris85 - the PHP code above is what is in test.php - and for the "gone on redirect" from what I have read I was under the impression that using "POST" and assigning a keyvalue to the data "data:{data:content}" it would be store in the $_POST['data']? maybe I have misunderstood the documentation I have been reading. The variable "content" holds the valid JSON at the moment and its just test data as initially I had tried with other data and thought my format was incorrect, so i went back to a basic AJAX post with test data. Commented Aug 1, 2016 at 1:51
  • @jeff - I don't really need a redirect, all I want is to pass the JSON to a specific PHP file and then use that JSON in the PHP script on that page. Also I have tried the success callback function and the response reads NULL. code below (incase I misinterpreted what you ment): Commented Aug 1, 2016 at 1:57
  • $.ajax({ type: 'POST', url: 'test.php', data: {data: content}, cache: false, success: function(response){ alert("success"); console.log(response); // window.location = "test.php"; }, error:function(){ alert('ajax failed'); } }); Commented Aug 1, 2016 at 1:57

4 Answers 4

3

The reason is you are using window.location to redirect to the PHP file (without any post data) instead of posting the form on test.php.

You should either post the form without ajax on test.php.

Or use the response from test.php in your success function.

$('#updateJSON').click(function(){
    var content = [{
                        "id": 21,
                        "children": [{
                            "id": 196
                        }, {
                            "id": 195
                        }, {
                            "id": 49
                        }, {
                            "id": 194
                        }]
                }];
    var someText = "someText";


$.ajax({
         type: 'POST',
         url: 'test.php',
         data: {data: content},
         cache: false,
         success: function(response){  
             alert("success");
             console.log(response);
             //window.location = "test.php";
         },
         error:function(){
             alert('ajax failed');    
         }   
  }); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the reply, I have tried the above code and the console log shows a NULL value,also initially I was just using the 'url:"test.php"' without the redirect and then trying to read the $_POST['data'] value and still NULL.
2

You are passing data as a string to ajax file. Please use JSON.stringify(conten) to pass data as a json format in ajax file.

use

data: {data: JSON.stringify(content)}

in place of

data: {data: content}

6 Comments

Ok this has helped the callback response now show the JSON data - I had tried this but didn't validate by logging the callback response so now I know the data is being sent or at least seen through AJAX. However I still cannot output this data in the PHP file test.php the $_POST['data'] is empty.
Please check after giving argument to success function of Ajax. success : function(content)
on the console.log(content) in success function i now get the following:
array(1) { [0]=> array(2) { ["id"]=> int(21) ["children"]=> array(4) { [0]=> array(1) { ["id"]=> int(196) } [1]=> array(1) { ["id"]=> int(195) } [2]=> array(1) { ["id"]=> int(49) } [3]=> array(1) { ["id"]=> int(194) } } } }
now this doesnt look to be valid JSON data, however I still attempted to read this data in the test.php $_POST['data'] but this is still NULL, thank you again.
|
2

Use:

<?php
    $postdata = file_get_contents("php://input");
    $request = json_decode($postdata);

Then access each field as follows:

       $field1 = @$request->field1Name;
       $field2 = @$request->field2Name;
etc..

EDIT:

Well, the first part of the answer is still valid.

I've tried your code and slightly modified it on my machine, and i was able to access the whole data as you will see below:

Javascript: removed the square brackets from the outside of your JSON and removed the curly brackets from the 'data' part of the ajax since they are not necessary

as you can see, i've also added the "data" to the success function so i can debug the response from test.php better

$(document).ready(function(){
    $('#updateJSON').click(function(){
        var content = {
            "id": 21,
            "children": [{
                "id": 196
            }, {
                "id": 195
            }, {
                "id": 49
            }, {
                "id": 194
            }]
        };


        var someText = "someText";
        $.ajax({
            type: 'POST',
            url: 'test.php',
            data:  JSON.stringify(content),
            cache: false,
            success: function(data){
                alert(data);
                console.log(content);
            },
            error:function(){
                alert('ajax failed');
            }
        });
    });
});

PHP:

<?php

$postdata = file_get_contents("php://input");
$request = json_decode($postdata);
$field1 = @$request->id;
echo $field1;

and $field1 is echoed as "21", the correct answer

You can apply this to your code and check also.

2 Comments

Thank you for the reply, I have tried the above code inside test.php and the data is NULL, it seems my issue is between the js file and the php file as from everything I have read the php and js code is OK but i still cannot access the data sent from JS to PHP inside PHP... its hurting my brain :)
@KelRobertson Please view my edit. I've managed to make your code work on my machine
1

Thanks everyone for the help I have managed to figure it out with the help of each of you.

I needed to create in the test.php file a, $json = array(), and then populate the array, $json[] = json_decode($_POST['data']);

that then allowed me to place the contents in a JSON file.

here is the php code:

<?php
$json = array();
if($_POST['data']) {
$json[] = json_decode($_POST['data']);
file_put_contents("../JSON/test.json",json_encode($json)); 
} else {
echo "No Data";
}
?>

and as long as the file "JSON/test.json" exists then it will write the JSON passed from the JS.

I would like to note:

without the JSON.stringify(content); the data is NULL so thank you @ Rahul Patel for making sure this was being applied.

the JSON data is valide according to the JSON validate site.

also just for keeps sake the JS code:

$('#updateJSON').click(function(){
    var content = {
                        "id": 21,
                        "children": [{
                            "id": 196
                        }, {
                            "id": 195
                        }, {
                            "id": 49
                        }, {
                            "id": 194
                        }]
                };

        $.ajax({
             type: 'POST',
             url: 'test.php',
             data: {data: JSON.stringify(content)},
             cache: false,
             success: function(){  
             alert("JSON Updated");
             },
             error:function(){
                 alert('ajax failed');    
             }   
        }); 

}); 

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.