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.
-
2You forgot to mention what the problem is.jeroen– jeroen2017年09月18日 12:07:53 +00:00Commented Sep 18, 2017 at 12:07
-
@jeroen it is not working, it's running the error function in the ajax callxickoh– xickoh2017年09月18日 12:09:55 +00:00Commented Sep 18, 2017 at 12:09
-
1If the error function is called, can you check in the browser console to see the request status ?Romi Halasz– Romi Halasz2017年09月18日 12:11:25 +00:00Commented Sep 18, 2017 at 12:11
-
2You don't need to stringify while sending request.Harish Kommuri– Harish Kommuri2017年09月18日 12:24:59 +00:00Commented 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 lotxickoh– xickoh2017年09月18日 12:30:52 +00:00Commented Sep 18, 2017 at 12:30
2 Answers 2
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
1 Comment
json_decode($_POST['category_info'], true);
to decode it as array, otherwise it will be object