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,
Related
I have a page showing log files which I want to give the user the ability to select and delete. The deletion is done through an AJAX request where the ID of each log-for-deletion is sent via the parameters.
The problem is that there are instances where there are hundreds of logs and in these cases the AJAX request seems to fail. I assume because there is just too much data sent via the parameters. I have tried breaking the AJAX request into parts, but only the first request is sent, afterwards all other requests are shown in Chorme as "cancelled". Following is my code:
var logFiles = [];
function deleteLogBatch() {
if (logFiles.length == 0)
return false;
if (logFiles.length > 10)
var elements = 10;
else
var elements = logFiles.length;
var params = 'action=deletelog';
for (var i = 0; i < elements; i++) {
params += '&lf' + i + '=' + escape(logFiles.shift());
}
$.ajax({
type: "POST",
url: './ajax/logs.php',
data: params,
success: function(response) {
checkResponse(response);
deleteLogBatch();
}
});
}
$('body').on('click', '#confirm-log-delete', function(event) {
event.preventDefault();
$('.select-log').each(function() {
if ($(this).is(":checked")) {
logFiles.push($(this).attr('id'));
}
});
deleteLogBatch();
}
Any help as to why this is happening and what is the proper way of doing this would be appreciated.
You should use async ajax calls
$.ajax({
type: "POST",
url: './ajax/logs.php',
async: true,
data: params,
success: function(response) {
checkResponse(response);
deleteLogBatch();
}
});
It will not wait to previous ajax call
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.
How would I merge these two bits of code and can someone explain what the key and value would be.
I'm building a notifications system and I'm wanting to store the last new notification_id but not have it inserted into the div over and over again if its the same one, so then the ajax searches for anything else within my server that maybe new.
Ajax
<script type="text/javascript">
function loadIt() {
var notification_id="<?php echo $notification_id['notification_id'] ;?>"
$.ajax({
type: "GET",
url: "viewajax.php?notification_id="+notification_id,
dataType:"json",
cache: false,
success: function(dataHandler){
}
});
}
setInterval(loadIt, 10000);
</script>
Localstrorage
window.localStorage.setItem('key', 'value');
var dataHandler = function (response){
var isDuplicate = false, storedData = window.localStorage.getItem ('key');
for (var i = 0; i < storedData.length; i++) {
if(storedData[i].indexOf(response) > -1){
isDuplicate = true;
}
}
if(!isDuplicate){
storedData.push(response);
}
};
var printer = function(response){
if(response.num){
$("#notif_actual_text-"+notification_id).prepend('<div id="notif_actual_text-'+response['notification_id']+'" class="notif_actual_text">'+response['notification_content']+' <br />'+response['notification_time']+'</div></nr>');
$("#mes").html(''+ response.num + '');
}
};
You've confused oldschool Ajax by hand with jQuery. The parameter to the success function in jQuery is not a function name or handler. Its a variable name that will contain the response from the server. The success function itself is equivalent to the handler functions you would have created doing it the old way.
So not:
success: function(dataHandler){ }
...
...
var dataHandler = function (response){
But rather:
success: function(response) { doCallsToSaveToLocalStorage(response); }
I have the following code which (amount other things) gets an image URL from the server:
$.ajax({ url: 'Script.php',
data: {action: 'Random'},
type: 'POST',
dataType: "html",
success: function(data) {
var results = data.slice(0,-1).split('|');
var workers = [];
for(i=0; i<results.length; i++)
{
workers[i] = workers[i].split(',');
}
for(i=0; i<workers.length; i++)
{
var j = i+1
$('#random-worker' + j + '-pic').attr("src", workers[i][3]);
$('#random-worker' + j + '-name').html(workers[i][0]);
$('#random-worker' + j + '-pro').html(workers[i][1]);
$('#random-worker' + j + '-city').html(workers[i][2]);
}
}
});
Also, I have this code to display a loading gif while the ajax requests process
var $loading = $('.div-loading').hide();
$(document)
.ajaxStart(function () {
$loading.show();
})
.ajaxStop(function () {
$loading.hide();
});
What happens is that the Ajax is completed and the $loading div is hidden and only then the elements gets their values and the Image gets the new source. Is there a way to completely end the loading process and only then hide the $loading div?
Thanks.
I need to update the user's points on each drop he successfully make, but for some reason the $.ajax call seems to not work as desired...
I am getting the current points using $('#userPoints').val(), then I would like to make each and addition to the current number or set first score - if...else.
Any help?
function Point() {
var phpPoints = $('#userPoints').val();
if (phpPoints != null) {
var Usrpoints = phpPoints + 5;
} else {
var Usrpoints = 5;
}
alert('Points: '+phpPoints);
var sndData = { acts:'Points', points: Usrpoints };
$.ajax({ // begin add ajax
type: "POST",
url: "game/lib/updateGame.php",
dataType:"html",
cache: false,
data: sndData,
success: function(sndData) {
$('div#UpdateUser').html(sndData).fadeIn('slow');
}
}); // end ajax
}
here instead of td use the element in which you are droping
$('td').bind('dropstop', function(){ Point();
});