0

I am passing a file to a php file via ajax and i am returning only 1 $ variable using die($var) in the php file after a sucsessfull run...

the problem i am now facing is passing more than 1 variable back to the ajax sucess function . i have tried using json encode but it has failed to work. im thinking maybe to do with the ajax being form data.

im hoping there is a simple way top pass multiple varibles back to the sucess function.

Any help is greatly appreciated

var form_data = new FormData(); // Creating object of FormData class
form_data.append("image", file , newimagesrc) // Appending parameter named file with properties of file_field to form_data
form_data.append("oldimagesrc", oldimagesrc) // to re-write over with new image 
form_data.append("email", email)
form_data.append("imagext", fileNameSub)


$.ajax({
url: "UploadProfileImage.php",
type: "POST",
data: form_data,
processData: false,
contentType: false,
success: function(newimagesrc){ 


   //how do i pass back from php these variables
var out1=out1;
var out2=out2;
alert(out1 , out2);
  //help appreciated


var newimagesrc = newimagesrc;
//alert(newimagesrc); alert recieved message

imagename=input.files[0].name;
$('#imageupdate').css('color','green');
$('#imageupdate').text(newimagesrc);


var refreshimage = "Profileimagerefresh.php?avatar="+newimagesrc+"&email="+email;
$('#imagerefresh').load(refreshimage);


}//success 1 messagereturn1

});//ajax1

PHP FILE ('UploadProfileImage.php')

if(file_exists($oldimagelocation) && is_readable($oldimagelocation)){


$new=$rnd.$accountname.".".$extension;
if ($stat->execute(array("$new","$email"))){

unlink($oldimagelocation);
die($oldimagesrc);      //HERE I PASS 1 $ BACK  - I NEED TO RETURN MORE
exit();
}
else{
die("Failed replace image with image and rename");
exit();
}
 }
6
  • die() is a synonym/alias for exit(). Don't call them both. Commented Jan 14, 2019 at 19:11
  • If you want to pass data via AJAX back to the browser then JSON is the best choice. die() is only used to prematurely kill the execution of the script, it doesn't return any value or have hidden behaviour except for displaying the error message you passed as an argument. Commented Jan 14, 2019 at 19:14
  • Ok thanks for the heads up. i just thought with it being an ajax responce that die would just end the php script and that i needed to exit to get back to the jscript . Commented Jan 14, 2019 at 19:14
  • Dharman Quite, But how do i do this from the php page and return the $ to the success function in my ajax Commented Jan 14, 2019 at 19:15
  • <?php echo json_encode(array("a" => "valueA", "b" => "valueB")); ?> In Javascript: $.getJSON("myscript.php", function(data) { alert("Value for 'a': " + data.a + "\nValue for 'b': " + data.b); }); Commented Jan 14, 2019 at 19:17

2 Answers 2

1

Using JSON encode is the best choice. I would recommend something like this:

if (file_exists($oldimagelocation) && is_readable($oldimagelocation)) {
    $new = $rnd.$accountname.".".$extension;
    if ($stat->execute([$new, $email])) {
        unlink($oldimagelocation);

        echo json_encode([
            'out1' => $oldimagelocation, 
            'out2' => $oldimagesrc, 
        ], JSON_FORCE_OBJECT);

    } else {
        die("Failed replace image with image and rename");
    }
}

Then in JS just parse the response as JSON

$.ajax({
    url: "UploadProfileImage.php",
    type: "POST",
    data: form_data,
    processData: false,
    contentType: false,
    success: function(newimagesrc){ 
        let jsonObj = JSON.parse(newimagesrc);
        console.log(jsonObj.out1);
    }
});
Sign up to request clarification or add additional context in comments.

4 Comments

thsnk you i will try this... and how do i retrieve this in my ajax succsess function...
I updated the answer. You also need to properly handle the script flow and don't die(). instead send errors as JSON and display them properly to the user.
JSON.parse: unexpected character at line 1 column 1 of the JSON data - same error as i got with luke clynes suggestion, it must have sumthing to do with whatt im passing back or sumthing
@lezz Yes, check in your browser console. My guess is that the JSON is not the only thing that your script outputs. Check before if you have any other die or echo.
0

I have encountered a similar issue recently and solved this using JSON.

With PHP you can put the variables into an array and then use json_encode: and then return that onto the webpage.

Now, using your jQuery, you can use $.parseJSON which then makes it an array in jQuery.

Here's an example:

PHP:

die(json_encode(array('Hello', 'world!')));

jQuery:

$.ajax({
type: 'POST',
url: 'test.php',
}).done(function(result){
var array = $.parseJSON(result);
alert(array[0]);
});

3 Comments

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data -- probly down to my own code though, im still trying to fix it.
Are you using jQuery? Just noticed I have a comma at the end of url that shouldn't be there... I haven't tested this code, it's there for a reference. I have also provided a link to parseJSON. Hopefully they help.
error has changed ,unknown reason--> JSON.parse: unexpected end of data at line 1 column 1 of the JSON data

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.