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();
}
}
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);
}
});
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]);
});
Related
I am trying to build off a question I asked yesterday.
I am able to pass the file over to PHP using the ajax method. But I need to be able to change the file name to the booking number. For some reason, the booking was not being passed over to the PHP script. So I attempted the following:
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
$.post('process/fileUpload.php', {booking:booking, partner:partner}, function(data)
{
// Wasn't sure if I needed anything here
console.log(data);
});
$.ajax({
url: 'process/fileUpload.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data){console.log(data);},
error: function(jqHHR, textStatus, errorThrown){console.log('fail: ' + errorThrown);}
});
});
As you will notice above, I had to use the $.post method to send the booking and partner over to the php script.
I then used $.ajax to send the form_data over to the same script.
(I could not achieve this in one motion from yesterday's question I asked. So this is my second attempt to complete this. If there is a way to send all of the info in one motion, please refer to the question I linked above.)
So over in the PHP script, I am able to get all of the items I needed with a couple of functions:
<?php
// from the $.post method
if(isset($_POST['booking']))
{
$booking = $_POST['booking'];
$partner = $_POST['partner'];
getInfo($booking);
}
// from the $.ajax method
if($_FILES['file'])
{
$file = var_dump($_FILES['file']);
getFile($file);
}
function getInfo($booking)
{
return $booking;
}
function getFile($file)
{
return $file;
}
?>
I know it's not pretty, but I am able to get the booking (I don't need the partner right now), and I am also able to get the file information.
What I need to do is rename the file to the booking, and then finally upload it to the necessary directory.
I wasn't sure if I had to combine the functions, but I did try to no avail.
With that said, I am able to get the booking and file info within the PHP script. Now how would I go about renaming the file to the booking?
As you used form_data.append() to add the file data to the formdata. did it not occur to you to also use that to add the booking and partner values to it as well?
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
form_data.append('booking', $('#bookingNum').val());
form_data.append('partner', $('#partnerCode').val());
$.post('process/fileUpload.php', form_data, function(data)
{
console.log(data);
});
});
To fix your ajax request (especially the illegal invocation), use the following javascript code
$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('pdfFile').files[0]);
form_data.append('booking', $('#bookingNum').val());
form_data.append('partner', $('#partnerCode').val());
$.ajax({
type: "POST",
url: 'process/fileUpload.php',
data: form_data,
processData: false,
contentType: false,
success: function(data) { console.log(data); }
});
});
Notice the use of processData: false and contentType: false
I have read a lot of Q&As on here and can't seem to figure out what I am doing wrong...
Here is AJAX
var color = $('#fontcolor').val();
var size = $('#fontsize').val();
var text = $('#imagetext').val();
var fileToUpload = $('#fileToUpload').val();
var placement = $('#placement').val();
$.ajax({
type: "POST",
url: 'upload.php',
data: {color:color, size:size, text:text, fileToUpload:fileToUpload},
success: function(data)
{
window.alert(data);
},
cache: false,
contentType: false,
processData: false,
error: function()
{
window.alert('error');
}
});
And then php, I am just trying to simply see my data from now, but it shows empty...
<?php
$fontSize = $_POST['size'];
echo $fontSize;
echo "Test";
?>
I know that data is coming from form, I have tested variables after data is received, but just can't get it to post... I was using FormData object originally, but decided to simplify for troubleshooting purposes... Still nothing, seems very straightforward, but have been on this for a few days now...
So it seems I might not be able to pass the image alongside the other parameters, though perhaps there is a way I cannot find. Instead, I will pass image to upload.php, then in response return the image path. Then I will have it trigger success function that passes other parameters to another function that modifies the image accordingly. Works for me.
I get this from ajax call
{"id":"381120774951940096","time":"Posted 0 minutes and 51 seconds ago.",....
How can I add each of these into variable, id, time etc? data.id won't work, it says undef.
<script>
$(function() {
$.ajax({
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
});
</script>
This is what I return from start.php
$return = array('id' => $info['id_str'] ,'time' => timeDiff(new DateTime($info['created_at'])), 'name' => $info['user']['name'], 'text' => $info['text'], 'image' => $picture, 'url' => "http://twitter.com/{$info['user']['screen_name']}");
print_r(json_encode($return));
EDIT
I had that print_r inside foreach loop and that was the issue. So I added another array and used echo json_decode($array,true) at the end of file.Writing this just in case, might help someone.
Cheers
First, in your PHP, change your line to:
echo json_encode($return, true);
That second parameter ensures that the JSON is interpretable as an associative array. Also, you should use echo instead of print_r when returning JSON; print_r can alter the formatting.
Next, use the following AJAX call:
$.ajax({
type: "POST",
url: "start.php",
dataType: "json", // Add this option.
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
})
The dataType: "json" option ensures that data will be parsed as a JSON object as soon as it's retrieved. So, data.id should be immediately available in your success callback function.
Hope this helps!
Firstly, you should use echo in the server script. print_r is mainly for debugging arrays.
Secondly, you should declare a dataType option for the ajax call:
$.ajax({
dataType: "json", // <-- here
type: "POST",
url: "start.php",
cache: false,
success: function(data) {
console.log(data.name);
console.log(data);
}
});
The way you have it now, I think you are getting a string response as data.
You can verify that with console.log(JSON.stringify(data));
You have to set dataType: 'json' in your ajax. This means that jQuery will parse the result as JSON for you.
Then parse the data,
data = $.parseJSON(data);
Then read var id = data.id;
Also, in your PHP, No need to use print_r(). Just use echo instead print_r().like:
echo json_encode($return);
You'll need to parse the JSON string into an object. You can use JSON.parse to do this.
// Your JSON string
var json_str = "{'id': 'foo', 'time': 'bar'}";
// We need to parse it, converting it into a JS object
var json_obj = JSON.parse(json_str);
// We can now interact with it
console.log(json_obj.id);
console.log(json_obj.time);
Alternatively, you can parse JSON using a built in jQuery function parseJSON().
jQuery also has a built in function for fetching JSON called getJSON(). If memory serves, this is just a shorthand for doing an .ajax() call and specifying a datatype of json. This will handle the above (parsing JSON) for you, and is the recommended solution.
I have this ajax code
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(html)
{
LastDiv.after(html);
}
});
I am new with this Ajax thing.
This code is to load getData.php file and send variables through type POST.
The variables are in this var ValueToPass = "lastid="+LastId+"&br="+br;.
Other thing this code does is return the getData.php's HTML after loading.
Probably with this. success: function(html)
How can I return this $br variable from getData.php after loading, so I can use it again through the next cycle. Cuz what happens here is that I can put the variable in the getData.php with the Ajax and working with it, but when the file getData.php is loaded, outside this file, the variable is not known(not declared). And I'm losing the counting :S
I want to return the HTML and the variable.
You can return json data in your php file like
$response = array ('br'=> $br, 'html'=> $html);
echo json_encode($response);
Here both html and data are returned.
And this to use it in your ajax callback :
success: function(data)
{
br = data.br;
LastDiv.after(data.html);
}
I'd consider setting a Session variable with the value from the $br variable passed via AJAX. Then when you call getData.php from another file or location, you can use the Session variable since session variables retain their value anywhere in the session.
You can try this to get the data from your `getData.php' :
$.ajax(
{
type: "POST",
url: "getData.php",
data: { ValueToPass: ValueToPass},
cache: false,
success: function(data)
{
LastDiv.html(data);
}
});
and in your getData.php you have to pass ValueToPass
maybe like this:
$ValueToPass = mysqli_real_escape_string($db, $_POST['ValueToPass']);
If I understand your question correctly, and if you want to return the $br variable then include it in a JSON object in the successs callback function. So, something like this (I'm not familiar enough with PHP so my PHP syntax might be incorrect):
// create JSON object
<?php
$result = array('br' => $br, 'html' => 'htmlContent);
echo json_encode($result);
?>
// return JSON object
$.ajax(
{
type: "POST",
url: "getData.php",
data: ValueToPass,
cache: false,
success: function(result)
{
var $br = result.br;
LastDiv.after(result.html);
}
});
Sorry if this is basic, but I have been dealing with figuring this out all day and have gotten to where I can do everything I need with Jquery and cakephp (not sure if cakephp matters in this or if its same as any PHP), I want to return a variable from a cakephp function to jquery, I had read about how to do it, like here:
the cakephp:
$test[ 'mytest'] = $test;
echo json_encode($test);
and the jquery:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
}
});
I just can't figure out how to get one or more variables back into usable form within jquery, I just want the variable so I can do whatever else with it, I've been looking at what I can find through searching but its not making it fully clear to me.. thanks for any advice.
The JSON variables are in the data variable. In your case, it'll look like this:
var data = {
myTest: "Whatever you wrote here"
};
... so you can read it from data.myTest.
(Not sure whether it's relevant but you can remove the http://localhost/ part from the URL;
AJAX does not allow cross-domain requests anyway.)
Your variables are in data.
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
// how do i get back the JSON variables?
var values = eval( data ); //if you 100 % trust to your sources.
}
});
Basically data variable contain the json string. To parse it and convert it again to JSON, you have to do following:
$.ajax({
type: 'POST',
url: 'http://localhost/site1/utilities/ajax_component_call_handler',
data: {
component_function: component_function,
param_array: param_array
},
dataType: "json",
success: function(data) {
json = $.parseJSON(data);
alert(json.mytest);
}
I haven't test it but it should work this way.
Note that when you specify dataType "json" or use $.getJSON (instead of $.ajax) jQuery will apply $.parseJSON automatically.
So in the "success" callback you do not need to parse the response using parseJSON again:
success: function(data) {
alert(data.mytest);
}
In case of returning a JSON variable back to view files you can use javascript helper:
in your utilities controller:
function ajax_component_call_handler() {
$this->layout = 'ajax';
if( $this->RequestHandler->isAjax()) {
$foobar = array('Foo' => array('Bar'));
$this->set('data', $foobar);
}
}
and in your view/utilities/ajax_component_call_handler.ctp you can use:
if( isset($data) ) {
$javascript->object($data); //converts PHP var to JSON
}
So, when you reach the stage in your function:
success: function(data) {
console.log(data); //it will be a JSON object.
}
In this case you will variable type handling separated from controllers and view logic (what if you'll need something else then JSON)...