Dingo Bruce
Dingo Bruce

Reputation: 405

Ajax, JQuery & PHP - Passing PHP variable to JQuery

I have a page that allows users to upload multiple files and preview them without refreshing the page using jquery. In php I generate a unique file_id for each filename which I would then like to pass back in to JQuery and use it to load up the preview image etc.

I hope I have explained myself clearly.

Thanks for any pointers!

The PHP code:

   // php code to upload file and generate unique file id. then...

   if (move_uploaded_file($main_image, $file)) { 
      echo "success"; 
      echo $file_id; // <--- I WANT TO PASS THIS VARIABLE BACK IN TO JQUERY
    } else {
        echo "error";
    }

The J Query Code:

$(function(){
        var btnUpload=$('#upload_main');
        var mestatus=$('#mestatus');
        var button=$('#button');
        var files=$('#main_file');
        new AjaxUpload(btnUpload, {
            action: 'classified-ads/upload-classified-image.php?filenumber=1',
            name: 'file1',
            onSubmit: function(file, ext){
                 if (! (ext && /^(jpg|png|jpeg|gif|'')$/.test(ext))){ 
                    // extension is not allowed 
                    mestatus.text('Only JPG, PNG or GIF files are allowed');
                    return false;
                }
                mestatus.html('<img src="extras/ajaxuploader/progress_bar.gif" height="30" width="340">');
                button.html('Loading...');
                $('#upload_main').removeClass('hover').addClass('upload_button_loading');
            },
            onComplete: function(file, response){
                //On completion clear the status
                mestatus.text('Photo Uploaded Sucessfully!');
                button.html('Change Photo');
                $('#upload_main').removeClass('upload_button_loading').addClass('upload_button');
                //On completion clear the status
                files.html('');
                //Add uploaded file to list
                if(response==="success"){
                var file2 = file.replace(/\s/g, "_");
                            var file_id= file_id;

                        $('<div></div>').appendTo('#main_file').css('background-image', "url(/ht/classified-ads/temp_images/prev1_<?php echo $parsed_user;?>_"+file_id+")").addClass('main_success');
                        $("#image1_temp").val("main1_<?php echo $parsed_user;?>_"+file_id+"");
                        $("#thumbnail_temp").val("thumbnail_<?php echo $parsed_user;?>_"+file_id+""); 
                    } else{
                        $('<li></li>').appendTo('#main_file').text(file).addClass('error'); 
                    }
                }
            });

        });

Upvotes: 0

Views: 92

Answers (2)

Ben Chamberlin
Ben Chamberlin

Reputation: 731

In your PHP:

$response = array('result' => 'success', 'file_id' => $file_id);
echo json_encode($response);

In your jQuery:

var obj = $.parseJSON(response);

You would then check whether the response was a success with if (obj.result == 'success') and you'd get your file_id with obj.file_id

Upvotes: 1

Blizzardengle
Blizzardengle

Reputation: 1071

The simplest way is to do this allowing for MULTIPLE values to be returned:

// Make a variable to hold data to send back and keep track of your separator
$data = '';
$separator = 1;
// Put this in a loop, your loop will depend on how many file uploads you have
// I did not do the loop for you
if (move_uploaded_file($main_image, $file)) { 
  // echo "success"; Take this out
  if ($separater==1){
      $data .= $file_id;
  } else {
      $data .= ','.$file_id;
  }
  $separater++;
}
// Now outside the loop echo the results back
echo $data;

With this info echoed back you can manipulate it with Javascript (Jquery). Just use something like spli(','); which gives you an array of the file names you needed.


If you only want one value to come back, meaning you only have one file id to send back foregt everything about the loop and the PHP would be this:

if (move_uploaded_file($main_image, $file)) { 
// echo "success"; Take this out
$data = $file_id;
// Now echo the results back
// Its been a while since I've done this but there may be times its ok to use return
echo $data;
} else {
// Handel error here
echo "error";
}

Now based off your code this echoed information should be picked up and processed here:

onComplete: function(file, response){ ... }

Instead of looking for "Success" you need to change your code to look for a file id or something like error instead (which is easier) like so:

if(response!=="error"){
// Now you can use your variable "response" here since it contains the file id
} else { 
// Handle the error
}

The reason I gave you a long explanation about getting multiple values back is because that is more common as you start making more advanced forms and it wouldn't hurt to use now. This way you can allow multiple file uploads for example. What I do for example when using AJAX is echo back something like this:

1::value,value,value

Now I just split that into arrays first by :: and then by , this line for example says No Error Happened (1 which as we know is also TRUE) and here is your data: value,value,value which you can now use for things in your Jquery or just print to the document.

You should look at the Jquery AJAX page for in depth examples and explanations, it explains the trouble you ran into getting results back. Look at .done .success .complete especially.

Upvotes: 0

Related Questions