I have wrote an ajax function and it partially works. Doesn't give any errors . but when i add alert to check my values it works completely . It renders the complete thing . Can any one tell me where did i do wrong in here
$.ajax({
type : "POST",
url : "/usermanageajax/",
data : 'key=' + key_value,
success : function (data) {
var element = users.salary[users.salary.length -1];
var hrs = users.hours[users.hours.length -1];
var html = "<span title=\"" + users.name + "\">Name \"" + users.desc(0,50) + "...\" "+ "has " + element + " of "+ hrs + "</span>";
// alert('*');
$('#title').html(html);
chart_s = draw_chart(data);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
}
});
The justification of this issue is that the alert call blocks the calling of the two next line. Seems that the browser needs some milliseconds to achieve something before performing the two next lines.
Try to call setTimeOut on the two other lines to be called after few milliseconds.
Again, what is the browser you are testing on?
The fact that it works with the alert indicates a race condition.
Try moving your code to a complete handler instead of a success handler. You can also check for success there.
Related
I'm using WebvoltyTemplate that utilizes it's own search template but it also is responsible for filtering products. Every time I try to search for a product in main searchbar and also when I try to show filter list with a simple button it uses ajax request. The problem is that every time it throws an error.
POST https://www.example.com/modules/wtcmssearch/ajax.php? 403
send # core.js:39
ajax # core.js:39
error wtcmssearch.js:62 error
The 'error' message comes from that part of code that doesn't actually tell anything.
$(document).on('keyup','.wtcmsheader-search .wtsearch-header-display-wrappper .wtheader-top-search .wtheader-top-search-wrapper-info-box .wtcmssearch-words',function(){
var obj = $(this).parent().parent().parent().parent().find('.wtsearch-result');
obj.html('');
obj.show();
var search_words = $(this).val();
var cat_id = $('.wtcms-select-category').find('.selected').val();
if (search_words.length != 0) {
$.ajax({
type: 'POST',
url: baseDir + 'modules/wtcmssearch/ajax.php?',
cache: false,
data: 'search_words='+ search_words + '&category_id='+ cat_id +' &token=' + static_token,
success: function(data)
{
obj.html('');
obj.append(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
}
});
The core.js function that throws an error is a very long one-liner:
function(e){var t,n,r,i,o,a,s,u,l,c,d,f,p,h,v,m,g,y,x,b="sizzle"+1*new Date,w=e.document,T=0,C=0,k=oe(),S=oe(),j=oe(),_=function(e,t){return e== .....................
Every file has right permissions set. I have no idea where should I start looking for a problem root. Any idea?
EDIT:
I have found out that another feature doesn't work because of that- adding to wishlist. It Also throws an error in core.js:39. I would like to send the whole line but it's about 83k characters.
EDIT 2:
I noticed that when I try to look up the ajax.php file through my browser it also throws an 403 exception. No idea how to investigate further. I turned of apache mod_security, didn't help.
We have the following script that works fine on all browsers.
However when the same script is placed inside the Fullcalender eventRecieve function (external events drag, drop and re render) the script does not post data to insert_events.php - but this only happens in Firefox- it does post data as expected in both Chrome and Edge. So in summary we have a situation as follows:
Edge, Chrome, FF - script is standalone --> posts data as expected
Edge and Chrome - script is inside eventRecieve --> posts data as
expected
FF script is inside eventRecieve -->fails to post data as expected
Code:
var title = "Job Request";
var description = "nothing";
var start = "2017-08-28";
var url = "google.com";
var propertyid = "WR388GG-8621";
$.post("insert_events.php?propertyid=" + propertyid, {
title: title,
description: description,
start: start,
url: url
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
}
);
We originally thought this issue was down to the Ajax code with FF and
searched high and low for some ideas and spent a day trying to work out what was going on. But actually the problem is only showing up in Firefox and only when the script is triggered by Fullcalendar's eventRecieve function as below.
Code:
eventReceive: function(event) {
var title = "Job Request";
var description = "nothing";
var start = "2017-08-28";
var url = "google.com";
$.post("insert_events.php?propertyid=" + id, {
title: title,
description: description,
start: start,
url: url
},
function(data, status) {
alert("Data: " + data + "\nStatus: " + status);
});
$('#calendar').fullCalendar('rerenderEvents');
window.location = 'new place to go';
},
Any ideas?
Credit goes to A Dyson on this one. It would seem that Firefox alone will trigger the redirect (window.location = 'new place to go';) before the Ajax call is made. The same is not true of Chrome or Edge - which handle the Ajax call first. Please upvote A Dyson's comment which should be the accepted answer. Apologies for dismissing A Dysons correct comment to soon.
Please check: http://jsfiddle.net/TWiStErRob/s2jSA/ where I try set up all possible variations I could think of for:
success, error, complete
ajaxSetup
ajaxSuccess, ajaxError, ajaxComplete
done, fail, always
As I see:
a lot of events are missing for JSONP
I would expect the same output as for JSON
Global AJAX events don't work as the Deferred's callbacks, i.e. registration order matters, but only with the same type of events.
Not a biggie, I can live with it.
complete is running after success/error
Good to know.
It seems that for JSONP the events are almost useless, can someone please explain why and give a workaround?
Reason
From http://api.jquery.com/category/ajax/global-ajax-event-handlers/
Note: Global events are never fired for cross-domain script or JSONP requests, regardless of the value of global.
From http://bugs.jquery.com/ticket/8338
JSONP requests are not guaranteed to complete (because errors are not caught). jQuery 1.5 forces the global option to false in that case so that the internal ajax request counter is guaranteed to get back to zero at one point or another.
If you want all requests to fire the events, no matter what (and at the risk of the same inconsistencies 1.4.4 exhibited), you can use the following prefilter:
jQuery.ajaxPrefilter(function( options ) {
options.global = true;
});
Workaround
The above code indeed makes it work:
$.ajaxPrefilter(function global_ajaxPrefilter(options, originalOptions, jqXHR) {
options.global = true;
});
$(document).ajaxSuccess(function global_ajaxSuccess(event, XMLHttpRequest, ajaxOptions) {
if(config.logResponses) {
console.log(XMLHttpRequest.responseText);
}
});
$(document).ajaxError(function global_ajaxError(event, jqXHR, ajaxSettings, thrownError) {
console.error("error: " + jqXHR.status + " " + thrownError);
});
However for my purposes the following approach works better:
$.ajaxPrefilter(/*dataTypes, */ function global_ajaxPrefilter(options, originalOptions, jqXHR) {
if(config.logResponses) {
jqXHR.done(function global_ajaxSuccess(data, textStatus, jqXHR) {
console.groupCollapsed(options.url + (options.data ? '&' + $.param(options.data) : ''));
console.log("Options: " + JSON.stringify(options));
console.log("Data: " + JSON.stringify(data));
console.groupEnd();
});
}
jqXHR.fail(function global_ajaxError(jqXHR, textStatus, errorThrown) {
console.error(textStatus + ": " + errorThrown));
});
});
Notice the different argument list of global_ajaxSuccess and global_ajaxError:
options: available in both solutions (contains URL)
data: is available as text in global handler, and object in done
interface is much familiar with done/error
I'm using a customized example of plupload, where
one or more files are first uploaded to an Amazon S3 bucket, and
then file info + user-entered data (e.g. description) is POSTed
via ajax to my controller action in a loop.
This controller action then verifies that the file was upload to the S3 bucket and then saves the info into the database, returning a success or failure to the ajax call.
I use the 'UploadComplete' event to check for any upload errors, and if there are none, perform the actual POSTs in a loop.
What I'd like to do is wait until the entire loop has finished processing and then display the confirmation message (all success, all failed, mix of both) accordingly.
Current code:
uploader.bind('UploadComplete', function (up, files) {
var errorsPresent = false;
var errors = '';
// re-enable buttons
$('div.plupload_buttons a').removeClass('disabled');
$.each(uploader.files, function (i, file) {
if (errorDescArray.hasOwnProperty(file.id)) {
errorsPresent = true;
errors += errorDescArray[file.id] + '<br />';
}
else if (file.status = plupload.DONE) {
var jqXhr = $.post('/documents/add', {
'__RequestVerificationToken': $('#__AjaxAntiForgeryForm input[name=__RequestVerificationToken]').val(),
'filename': file.name,
'size': file.size,
'location': $('#' + file.id + '_location').val(),
'description': $('#filedesc_text_' + file.id).text()
}).error(function (response) {
errorsPresent = true;
errors += response.responseText + '<br />';
});
}
});
//
if (errorsPresent) {
$('#uploadErrors').html('<div data-alert="alert" class="alert-message block-message fade in error">×<p>' + errors + '</p></div>');
}
else {
// set confirmation message
var message = files.length + ' file(s) were successfully uploaded.';
// clear file list
$('ul.plupload_filelist').html('');
// remove files from list
uploader.splice();
// hide modal
$('#upload-modal').modal('hide');
// show confirmation
$('#flashMessage').html('<div data-alert="alert" class="alert-message block-message fade in success">×<p>' + message + '</p></div>');
}
});
The above is obviously flawed in that the second half of the snippet doesn't really wait for the POSTs to complete, with the result that the success confirmation is displayed even if POST has an error response.
So my question is this: How do I perform an ajax post in a loop (unless there's a better way) and process the confirmation message after the loop has finished processing?
I'm trying to post data with AJAX and insert it into a database table.
The problem is, half of the data is missing and I don't know why. I have checked all the names of parameters etc. because it seemed I had a typo somewhere (I was missing some characters but I fixed that) but still it won't work.
Even console.log() and alerts give me the full data I want to post but it never arrives, the php outputs empty parameters. When deactivating the JavaScript or removing "return false;" the php script is opened as expected and works perfectly well, no data is lost (as expected).
Maybe I'm really just missing one single character somewhere ...
I also tried escaping (escape()) the strings but it didn't change anything.
Here's the code and some logs/alerts/echos
$("#itemspeichern").click(function(){
setVisible("#item-process");
var itemname = escape($("#itemname").val());
if ($("#itemneu").is(":checked")) {
var itemneu = $("#itemneu").val();
} else {
var itemneu = 0;
}
var itembild = escape($("#itembild").val());
var itemkurzb = escape($("#itemkurzb").val());
var theset = escape($("#theset").val());
console.log("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild" + itembild + "&itemkurzb" + itemkurzb + "&theset=" + theset,
success: function(result){
alert("itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset);
document.getElementById("item-process").innerHTML = result;
}
});
return false;
});
What this does is:
- output the data of all fields on the console
- showing all the data in the alert
but when it is done saving it the database is missing the values of itembild and itemkurzb. Getting the query as response from the php file showed that indeed the parameters are empty for those fields. Here's what I did in php (I shortened it a bit, don't comment on SQL injection and stuff :P)
$ergebnis = mysql_query("INSERT INTO mk7_items(id, de, neu, kurzbeschreibung, bild) VALUES(DEFAULT, '".$_POST["itemname"]."', ".$_POST["itemneu"].", '".$_POST["itemkurzb"]."', '".$_POST["itembild"]."')");
the last two fields are empty when I get the response and nothing is saved into the db.
As I said, setting JS to OFF and running it on php only works perfectly well.
Any ideas? Any stupid mistakes I did there?
You're missing a couple = in your data, it should be this:
data: "itemname=" + itemname + "&itemneu=" + itemneu + "&itembild=" + itembild + "&itemkurzb=" + itemkurzb + "&theset=" + theset,
Or better, stop using escape (which is deprecated in favor or encodeURIComponent due to escape not handling non-ASCII data very well) and use an object for your data parameter:
var itemname = $("#itemname").val();
//...
$.ajax({
url: "<?php actualPath(); ?>save-admin-action.php",
type: "POST",
data: {
itemname: itemname,
itemneu: itemneu,
itembild: itembild,
itemkurzb: itemkurzb,
theset: theset
},
//...
});
That way $.ajax will take care of converting your data to the proper POST (or GET or ...) format and you don't have to worry about the details.
try this in your $.ajax call instead of your selfmade query string:
data: {
itemname: itemname,
itemneu: itemneu,
itembild: itembild,
itemkurzb: itemkurzb,
theset: theset
}
By passing the data as Object, jQuery will escape the values for you :)
Edit:
You could also serialize the complete form like this:
data: $('#yourform').serialize()
if you use special characters in posted items, you use this function before every vars...
sample :
var txt = encodeURIComponent(document.getElementById('txt1').value);