Reputation: 1693
Im creating a simple upload script. I use a simple form to let people upload a picture and then a external php script will upload the picture and return some vars to the upload page.
But I cant get the part to return some vars to work. currently im using this:
The page that also contains the form:
form_data.append('file', file_data);
$.ajax({
url: 'upload.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script, if anything
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(response){
document.getElementById("titel" + amount).innerHTML = response['naam'];
});
The upload page that should return some data:
echo json_encode(array('naam'=>$naam));
This scripts returns undefined..
If I remove the ['naam'] after response on the form page it will print out: {"naam":"test.png"}
Hope someone know what im doing wrong. Thanx in advance!
Upvotes: 0
Views: 774
Reputation: 87203
The response you get from the server is the string
. To use it as object, you need to parse it to JSON format using JSON.parse()
.
var obj = JSON.parse(response);
Then you can use:
obj.naam;
to get the value of naam
from the object.
Upvotes: 1
Reputation: 694
Please change datatype from "text" to "json" then parse that JSON using JSON.parse(//return value ").
Var jsonObject = JSON.parse("Ajax Response object"); then use it jsonObject.keyName and it will return the value.
Upvotes: -1
Reputation: 943912
You said:
dataType: 'text', // what to expect back from the PHP script, if anything
… so jQuery will ignore what the server claims the data is (which seems to be HTML as you haven't changed the Content-Type header in your PHP) and process the response as if it was plain text.
response
will therefore be a plain text string and not the results of parsing JSON.
Change dataType
to "json"
.
Upvotes: 2