0

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.

10
  • 2
    You forgot to mention what the problem is. Commented Sep 18, 2017 at 12:07
  • @jeroen it is not working, it's running the error function in the ajax call Commented Sep 18, 2017 at 12:09
  • 1
    If the error function is called, can you check in the browser console to see the request status ? Commented Sep 18, 2017 at 12:11
  • 2
    You don't need to stringify while sending request. Commented Sep 18, 2017 at 12:24
  • 1
    @Harish removing the stringify and the «dataType: json» does solve my issue. How can I mark it as correct? :) Thanks a lot Commented Sep 18, 2017 at 12:30

2 Answers 2

1

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

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

1 Comment

I actually had tried this before, but the browser cache might have interfered with the javascript code and I wasn't successful. This works though, in fact, not only I do not need to stringify, but if I try to stringify it will cause an error. Thank you!
1
 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

1 Comment

Thank you, I didn't know that. It's not working yet though

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.