ngplayground
ngplayground

Reputation: 21627

jQuery Ajax sending Object to PHP

before JSON.stringify

[Object { key="name", val="John Doe"}, Object { key="email", val="[email protected]"}, Object { key="company", val="JOHN INC"}, Object { key="tel", val="01234"}, Object { key="subject", val="Sales Enquiry"}, Object { key="comments", val="HELLOOO"}]

JSON.stringify

[{"key":"name","val":"John Doe"},{"key":"email","val":"[email protected]"},{"key":"company","val":"JOHN DOE INC"},{"key":"tel","val":"01345"},{"key":"subject","val":"Sales Enquiry"},{"key":"comments","val":"HELLOOO"}]

The above is what is output using the console.log(strung) in the code below. What I'm trying to get is the data to send via ajax to PHP so that I can then use for example $_POST['name'] in the PHP to send an email.

var strung = JSON.stringify(arr);
    console.log(arr);
console.log(strung);
$.ajax({
    type: "POST",
    url: "/contact.php",
    data: strung,
    success: function(data) {
        console.log(data);
    }
});

Help is appreciated

Upvotes: 0

Views: 1808

Answers (1)

Ramesh
Ramesh

Reputation: 4293

Try:

var param = {};

$.each(arr, function() {
    param[this.key] = this.val;
});

And send

data: param,

in the $.ajax parameter.

You can access in PHP,

echo $_POST['name'], $_POST['email']

...

Upvotes: 4

Related Questions