Reputation: 532
From my PHP processing file I receive back an object
([object Object]
) and I'd like to access it's content's with calls like data[0].errors
etc, but all tries seem to fail for me.
How may I achieve that?
Here's what the object looks like:
" Array
(
[success] =>
[errors] => Array
(
[companyname] => Company name is required and must have 50 characters at most.
[logo1] => Logo is required.
[investment] => First investment amount is required.
[investment1] => Investment value must be an integer.
[payment] => Basic wage is required.
[payment1] => Payment value must be an integer.
[companytype] => Company type is required.
[companytype2] => Something is wrong with your company type.
)
)
"
I have to display those errors
in console div to show the user what has he done wrong.
EDIT:
Here's exactly what I get when I console.log(data)
:
Also here's my AJAX request to make everything clear.
$.ajax({
type : 'POST',
url : 'processcreatecompany.php',
data : formData,
dataType : 'json',
contentType: false,
processData: false,
encode : true
}).done(function(data) {
console.log(data);
}).fail(function(data) {
console.log(data);
})
Upvotes: 0
Views: 137
Reputation: 1761
as expected the problem is in the php part ... you are doing a print_r
of the objects which gives that output that it's not json
you should use json_encode
to return the $data
object/array, so instead of
print_r($data['success']);
print_r($data['errors']);
you should have (also you should add the content type header )
header('Content-Type: application/json');
echo json_encode($data);
Later edit: without the header you usually get the response as text/plain
in data.responseText
, as in your screenshot, and and you will have to do the JSON parsing "by hand". Adding the header makes jQuery do the parsing automatically and you'll have the response as an object in data.response<something I dont recall now>
Upvotes: 3