SJSSoft SJSSoft - 5 days ago 5
Javascript Question

JSON response at ajax request to JS variables

I am trying to upload files with dynamic names and get those dynamic names back.

In detail, I have 2 page

form.php
and
upload.php
. When upload button is pressed on
form.php
then request sent to
upload.php
, where 2 files (DLpath and PhotoIDPath) are uploaded to server with dynamically names e.g :

DLpath=documents/20161130232311i8hGn0HzJT276415832.png

And

PhotoIDPath=documents/20161130232311SSRqCyIbKKalock.png.

It is working fine. Then on
upload.php
, I am encoding those file names as JSON array i.e.

$response = array ('DLpath'=>$Dlpath ,'PhotoIDPath'=>$PhotoIDPath);
echo json_encode($response);


And firebug snapshot is :

enter image description here

I want to get DLpath in
var jsDlpath
and PhotoIDPath in
var jsPhotoIDPath


And my code ( Not working) to get response is :

complete: function(response)
{
var jsDlpath=response.DLpath;
var jsPhotoIDPath=response.PhotoIDPath;
alert(jsDlpath+" - "+jsPhotoIDPath)
}


And alert show :


undefined - undefine


If you can help me to gwt those values in js variables, I will be very thankful to you.

Answer

Since you're encoding you response in server side you should parse it in the js side, you could use $.parsejson() :

success: function(response) 
{
    var response = $.parseJson(response);

    var jsDlpath=response.Dlpath;
    var jsPhotoIDPath=response.PhotoIDPath;

    alert(jsDlpath+" - "+jsPhotoIDPath)
}

NOTE : Use success/done callback instead of complete.

Hope this helps.

Comments