xickoh
xickoh

Reputation: 314

Send jQuery object to PHP through Ajax

I'm very aware this is a possible duplicate, but none of the other questions/answers here on Stackoverflow solve my issue, and I've seen dozens!

Here's what I'm trying to do: Send the object in jQuery to PHP through Ajax, if possible as an array (not mandatory, but preferable).

My jQuery code:

  var category = {
        id: $(this).data('id'),
        name: $(this).data('name'),
        brief_description: $(this).data('briefdesc'),
        description: $(this).data('desc')
    };

    $.ajax({url: '/ajax.php',
        data: {action: 'removeCategory', category_info: JSON.stringify(category)},
        type: 'post',
        success: function (result) {
            console.log(result);
        },
    error: function () {
       console.log("Error");  
    }, dataType: "json"
});

The variable category is working fine, every index has its value

Now my ajax.php code

$category = json_decode($_POST['category_info']);
//category['name'] should exist and have the value sent from ajax
echo "We did it?";

The problem is that the error function is called.

Upvotes: 0

Views: 71

Answers (2)

Hardeep Singh
Hardeep Singh

Reputation: 780

You no need to stringify.

$.ajax({
        url: '/ajax.php',
        data: {
              action: 'removeCategory', 
              category_info:category
        },
        type: 'post',

On PHP side you will get it in $_POST['category_info']. No any need to decode

Upvotes: 1

X A
X A

Reputation: 837

 json_decode($_POST['category_info'], true);

to decode it as array, otherwise it will be object

http://php.net/manual/en/function.json-decode.php

Upvotes: 1

Related Questions