2

I am constructing an array of objects from form data in order to send to a processing script that will then send the data on to an API. The API does not allow CORS ajax requests, hence the need to send to an external script first.

I can return simple strings, but when I stringify the data I have, the response from the server is always that the POST or GET (have tried both) data is just an empty array.

JS

$('#enrol').submit(function(e) {
    e.preventDefault();

    var collection = [];

    $('#enrol .form-row').each(function() {
        var email = $(this).find('input[type="email"]').val();
        var c1Val = $(this).find('.c1').is(':checked') ? 'true' : 'false';
        var c2Val = $(this).find('.c2').is(':checked') ? 'true' : 'false';
        var c3Val = $(this).find('.c3').is(':checked') ? 'true' : 'false';
        var c4Val = $(this).find('.c4').is(':checked') ? 'true' : 'false';
        var c5Val = $(this).find('.c5').is(':checked') ? 'true' : 'false';
        var c6Val = $(this).find('.c6').is(':checked') ? 'true' : 'false';
        var c7Val = $(this).find('.c7').is(':checked') ? 'true' : 'false';

        var person = {
            'email'   : email,
            'course1' : c1Val,
            'course2' : c2Val,
            'course3' : c3Val,
            'course4' : c4Val,
            'course5' : c5Val,
            'course6' : c6Val,
            'course7' : c7Val,
        }
        collection.push(person);

    });

    var dataString = JSON.stringify(collection);

    $.ajax({
        url: 'http://www.example.com/script.php',
        data: dataString,
        crossDomain: true,
        success: function(response) {
            console.log(response);
        },
        error: function(response) {
            console.log(response);
            alert(response.responseText);
        }
    });
})

PHP

header("Access-Control-Allow-Origin: URLHERE");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept");

var_dump($_GET);

What I don't get is if I just JSON.stringify a simple string, I get the data returned, yet the array of objects seems to arrive at the php script as an empty array - or at least that's what the console.log is suggesting. I've outputted the dataString variable to ensure it has data - it does.

4
  • 1
    What I don't get is what is the problem? Commented Aug 23, 2017 at 12:10
  • This bit - "I can return simple strings, but when I stringify the data I have, the response from the server is always that the POST or GET (have tried both) data is just an empty array." Commented Aug 23, 2017 at 12:11
  • 2
    Did you try data: {mydata: collection}, without the stringify Commented Aug 23, 2017 at 12:13
  • @RiggsFolly this worked (with the stringify) - stupid as that's how I have always structured it before! If you chuck that in an answer with an explanation I'll mark as correct Commented Aug 23, 2017 at 12:42

3 Answers 3

1

i have something similar in my own project. This works for me:

jsonObj = new Object();
jsonObj['email'] = email;
jsonObj['course1'] = c1Val;
.
.
.

 $.ajax({
            type: 'POST',
            url: 'http://www.example.com/script.php',
            data: {"data": JSON.stringify(jsonObj)},
            dataType:'JSON',
            cache: false,
.
.
.
});

PHP:

var_dump($_REQUEST['data']);
Sign up to request clarification or add additional context in comments.

2 Comments

dataType argument doesn't do anything in this context. It's to tell jQuery what type of data the server will return; it doesn't change anything to how the data is sent by jQuery or received by PHP. This works for you because by using {"data": JSON.stringify(jsonObj)}, you are no longer sending JSON, but a query string. If you Open the browser console to see what is sent to the server you will see something like data="<json-string>" which is not JSON structure
@BeetleJuice .. Yeah you are right about the dataType argument - useless in this context. But the problem should still be fixed like this...inside it's still JSON --> $_REQUEST['data'] is valid json and can be decoded and further processed.
0

PHP will not automatically fill the superglobals $_GET and $_POST when the data arrives in JSON format. You'll need to do two things on the PHP side:

  1. Manually capture the input
  2. JSON-decode it into a PHP data structure

    // capture your raw JSON
    $datastring = file_get_contents("php://input");
    // decode it into a PHP array
    $collectionArray = json_decode($datastring, true);
    

On the jQuery side, the following may not be needed, but I would be explicit about the type of content sent to the server:

$.ajax({
    url: 'http://www.example.com/script.php',
    data: dataString,
    contentType : "application/json",
    ...

Comments

0

The solution was a simple one, I wasn't providing a key for the post array -

data: dataString

should have been

data: { data: dataString }

Then the output of var_dump($_GET['data')) contained the data I was sending.

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.