I got a jQuery script which sends info about a picture to a php file through a "formData" variable, like this:
url: 'ajax.php',
type: "POST",
contentType:false,
processData: false,
cache: false,
data: formData,
success: function(data){}
As far as I know, here is the part of the script that generates the content of that formData before it is sent:
function handleFileUpload(files,obj)
{
for (var i = 0; i < files.length; i++)
{
var fd = new FormData();
fd.append('file', files[i]);
var status = new createStatusbar(obj);
status.setFileNameSize(files[i].name,files[i].size);
sendFileToServer(fd,status);
}
}
To catch that data in the php file, I just use
$_FILES['file'][...];
What I would like to do is to simultaneously send an additional javascript variable to the php file, along with the formData, that I would be able to catch as
$_POST['picID'];
How would I do that?
Thank you.
PS the additional javascript variable "picID" is defined at the beginning of the root of the js file so, it should normally be accessible from within any function in that file.
You can append as many key => value to the form data.
fd.append('key', value);
Applying to your scenario,
fd.append('picID', value); //where value is the value of picID
I would recommend that you declare the form data variable fd before the for loop begins. This is because only the file data requires the loop. For additional form data, append them outside the loop
Example
function handleUpload(){
var fd = new FormData();
//commence for loop {
// }end for loop
//append extra key => value
fd.append('key', value);
}
Related
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]);
});
so I'm trying to upload files via a form sent using AJAX, except $_POST returns an empty array (so does $_FILES) - though I'm not sure why. Here is the top of my form:
HTML - generated from PHP (inside WP function)
$html .= '<form method="post" class="form-horizontal" id="product-slides-form" enctype="multipart/form-data">';
AJAX
//edit product gallery
$('#update-product-gallery').on('click', function()
{
var product_id = $(this).data('id'),
slides_form = $('#product-slides-form'),
slides_form_data = new FormData(slides_form[0]);
//create array of slides
var slides = {},
counter = 0;
$.each(slides_form.find('input'), function(j, v)
{
if ($(this)[0].files) {
$.each($(this)[0].files, function(i, files)
{
slides_form_data.append('slides-'+ counter, files);
counter++;
})
}
});
//add slideshow data
slides_form_data.append('slides', JSON.stringify(slides));
slides_form_data.append('product-id', product_id);
var slides_data = {};
slides_data['product_id'] = product_id;
slides_form_data.forEach(function(val, key)
{
slides_data[key] = val
});
//if I change data: to below test FormData than it works
var test = new FormData();
test.append('me', 1);
$.ajax({
data: slides_data,
dataType: 'text',
type: 'post',
url: PLUGIN_ROOT+ 'admin/inc/scripts/add-product-slides.php',
cache: false,
contentType: false,
processData: false,
success: function(res) {console.log(res)},
error: function(res) {$.fn.showPopup(2, 'Something went wrong. Please try again.', res)}
})
});
and my script just var_dumps $_POST + $_FILES for now
I console.log'd the FormData using this:
// Display the key/value pairs
for (var pair of slides_data.entries()) {
console.log(pair[0]+ ', ' + pair[1]);
}
and it returns the correct data, so I'm really not sure why my script doesn't get the $_POST data? Am I missing something really obvious?
(if more code is needed - comment and I'll add more)
var slides_data = {};
That is not a FormData object. You need to send a FormData object.
You create one here:
slides_form_data = new FormData(slides_form[0]);
Keep using slides_form_data for all your data. Don't create a second variable and ignore all the work you did to populate the first one.
Im using single file input field with multiple upload property. I've already tested single file pass like that and it worked. Now I'm trying to
pass files using an array but there is a mistake.
There is no form.
HTML:
<input id="fileInfo" name="userfile[]" type="file" multiple>
JS:
var formData = new FormData();
var files = [];
for(var i = 0; i < length; i++) {
files[i] = $('input', '#fileInfo')[0].files[i];
}
formData.append('userfile', files);
$.ajax({
url: "example.php",
data: formData,
type: 'POST',
dataType: 'json',
processData: false,
contentType: false,
success: function(res)
{
console.log("done");
}
});
PHP:
<?php
$length = sizeof($_FILES['userfile']['name']);
json_encode(array($length));
error.log:
PHP Notice: Undefined index: userfile in /path/to/php on line 2, referer: http://localhost/test
Instead of building an array with the files (which is kind of strange to do since the source already is an array), append the files directly to your FormData object:
var formData = new FormData();
// Get all the files so we easily can get the length etc.
// Not necessary, but it will make the code easier to read.
var files = $('input', '#fileInfo')[0].files;
for(var i = 0; i < files.length; i++) {
formData.append('userfile[]', files[i]);
}
$.ajax({
// your ajax call
});
We've also changed 'userfile' to 'userfile[]' which will make it an array that you can loop through in your PHP.
I'm struggling to pass a GET variable into a jquery file.
My code is
function upload(files){ // upload function
var fd = new FormData(); // Create a FormData object
for (var i = 0; i < files.length; i++) { // Loop all files
fd.append('file_' + i, files[i]); // Create an append() method, one for each file dropped
}
fd.append('nbr_files', i); // The last append is the number of files
$.ajax({ // JQuery Ajax
type: 'POST',
url: 'ajax/tuto-dd-upload-image.php?order=5', // URL to the PHP file which will insert new value in the database
data: fd, // We send the data string
processData: false,
contentType: false,
success: function(data) {
$('#result').html(data); // Display images thumbnail as result
$('#dock').attr('class', 'dock'); // #dock div with the "dock" class
$('.progress-bar').attr('style', 'width: 100%').attr('aria-valuenow', '100').text('100%'); // Progress bar at 100% when finish
},
xhrFields: { //
onprogress: function (e) {
if (e.lengthComputable) {
var pourc = e.loaded / e.total * 100;
$('.progress-bar').attr('style', 'width: ' + pourc + '%').attr('aria-valuenow', pourc).text(pourc + '%');
}
}
},
});
I need the 5 in url: 'ajax/tuto-dd-upload-image.php?order=5' to be the vatriable order passed through a url like domain.com/?order=XX
You can use PHP and export the variable:
var orderId = <?php echo json_encode($_GET['order']); ?>;
function upload(files) {
...
url: 'ajax/tuto-dd-upload-image.php?order=' + orderId,
Or you could parse it directly in javascript:
var orderId = self.location.search.match(/order=(\d+)/)[1];
// Then continue like the previous example
Of course you'll probably need some error checking around this, if there's a chance the GET param might ever be missing.
Try with javascript :
function $_GET(key){
var result = new RegExp(key + "=([^&]*)", "i").exec(window.location.search);
return result && result[1] || "";
}
and call $_GET(key) function in your $.ajax request.
var order = $_GET('order');
url: 'ajax/tuto-dd-upload-image.php?order='+order,
I have a voting system which sends an id of the clicked item to a PHP script, the PHP updates the database and echos back the new vote counts via an JSON encoded array.
This is the jQuery:
$(".vote_up").click(function(){
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
$(".votes_up").find(id).html(data[x].vote_up);
$(".votes_down").find(id).html(data[x].vote_down);
}
}
});
});
So when i construct the item in the first place, i take the record ID in the database and set it as the items ID. So what i'm trying to do is reference the exact item that was clicked and set it's HTML to the data thats coming back from the PHP. I've checked in Firebug and I'm getting correct data back but the count of votes isnt changing. Any ideas?
This is the PHP for reference:
$query = "SELECT vote_up, vote_down FROM posts WHERE id = '".$id."'";
$result1 = mysql_query($query);
$output = Array();
while ($row = mysql_fetch_array($result1)){
$output[] = Array(
"vote_up" => $row['vote_up'],
"vote_down" => $row['vote_down'],
);
}
echo json_encode($output);
If you just want this in the success: callback to refer to the element that was clicked, just set the context: property for the AJAX request.
$.ajax({
context: this, // set the context of the callbacks
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data) {
// now "this" refers to the element that was clicked
}
You can test it by doing something a little more generic, like:
$(this).html("yep, it works");
... then if that works, consider that it doesn't really make sense to do .html() on the same element in a loop, because each time .html() overwrites the entire content.
Use .append() instead if you're appending data from the loop:
for(var x in data) {
$(this).append(data[x].vote_up);
$(this).append(data[x].vote_down);
}
Wouldn't:
$(".votes_up").find(id).html(...);
Really just need to be:
$('#' + id).html(..);
If you define a variable within the click() method callback, you'll be able to reference it within your ajax success callback. Something similar to this should do you:
$(".vote_up").click(function(){
// Assign the clicked element to a scoped variable...
var target = $(this);
var id = this.id;
var vote = $(this).attr("class");
var data = "id=" + id + "&vote=" + vote;
$.ajax
({
type: "POST",
url: "vote.php",
data: data,
cache: false,
success: function(data)
{
for(var x in data) {
// Then refer to it within your callback
target.html(data[x].vote_up);
target.html(data[x].vote_down);
}
}
});
});