0

I need to pass a Javascript array of objects to PHP. Found about 3 solutions on the internet, but none of them worked for me. The array looks like this (in Chrome dev console):

enter image description here

And my current AJAX call looks like this:

function consolidate() {
        var studentsstring = JSON.stringify(students);
        $.ajax({
             type: "POST",  
             url: "writefile.php",
             dataType: "json", 
             data: {students: students},
             success: function(data) {
                  alert(data);
             }
        });
    }

And the PHP file looks like this:

<?php
print($_POST['students']);
?>

Currently, when I hit the "consolidate" button, nothing happens. No alert is shown. Chrome dev reports no errors in the code.

10
  • 1
    var studentsstring = JSON.stringify(students); also appears to be redundant. Commented Jun 15, 2017 at 12:26
  • 2
    "nothing happens" — Are you sure? What do the developer tools in your browser say? Are any errors reported on the Console? Do you see the request in the Network tab? Does it get a response? Are the HTTP status codes what you expect? Commented Jun 15, 2017 at 12:29
  • 1
    Check network tab as @Quentin said and do echo json_encode($_POST['students']); because your ajax waits for json response Commented Jun 15, 2017 at 12:30
  • 1
    from where you get the variable " students " in the line var studentsstring = JSON.stringify(students); Commented Jun 15, 2017 at 12:31
  • 1
    We need to see the bigger picture, as there could be any number of issues, of the top of my head, the function is never called, students is out of scope, server sends a non 200 header. Commented Jun 15, 2017 at 12:33

1 Answer 1

1

Oh, I'm dumb. Too many hours of coding. The line should have been:

data: {students: studentsstring},

and now it works. Thanks all.

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

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.