Updating jQuery Item during Ajax call - javascript

I am making an ajax call to send out a couple of emails when the user clicks a button. I am trying to update a "Please wait..." div before and after the call with the status, as well as report any errors. The problem... is that the div doesn't actually update until the ajax call is complete.
If I comment out the ajax call the status update works fine, but fails if the ajax call takes place. My Windows programming experience tells me the div needs to be refreshed, but I'm not sure how this is done, or if this is the right method.
For example:
$("#msgEmail").show();
$("#msgEmail").html("Preparing to send");
$.ajax({ blah blah blah...
Any pointers in the right direction will be much appreciated!
On nnnnnn's suggestion I started testing on other browsers. The problem occurs on Chrome and Safari, but works as expected on Firefox and SeaMonkey. It sure looks like he's right about this. Now I just need to figure out to implement setTimeout() in this scenario.
Update: Code:
.click(function() {
$('#myTable :checkbox:checked').each(function() {
sId = $(this).attr('cid');
sName = $(this).attr('cname');
ret = true;
$("#msgImage").slideDown();
sUpdate = 'Sending alerts to class: '+ sName;
$("#msgEmail").slideDown();
$("#msgEmail").html(sUpdate);
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData= "cid="+sId+'&sname='+sName+'&subject='+sSubject+'&message='+encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function (msg)
{
if(msg >= '1')
{
ret = true;
}
}
});
if(ret)
$("#msgEmail").html('Finished sending alerts');
$("#msgImage").slideUp();
ret = false;
return false;
})

Place your ajax call in the callback for 'slideDown'. Set the message before calling 'slideDown'. This will ensure your message is updated before the ajax call is sent.'
sUpdate = 'Sending alerts to class: ' + sName;
$("#msgEmail").html(sUpdate);
$("#msgEmail").slideDown(function() {
sSubject = "Notificatiom";
sMessage = $('#message').val();
sData = "cid=" + sId + '&sname=' + sName + '&subject=' + sSubject + '&message=' + encodeURIComponent(sMessage);
$.ajax({
url: 'dostuff.php',
data: sData,
dataType: 'text',
type: 'POST',
async: false,
success: function(msg) {
if (msg >= '1') {
ret = true;
}
}
});
});

I ll get you an on hw this stuff is going to be
$(document).ready(function(){
$.ajax({
url :'YOur url',
.....
.....
ajaxSend :function(){
$('#yourdiv').html('please wait...');
}
success:function(msg){
if (msg >= '1') {
$('#yourdiv').html('validated');
}
}
});
}):

Related

jQuery AJAX url to PHP file doesn´t work

On my website I have a normal contact form in which you can put in your name, email and a message.
For this form I have script.js, which proofs if the user input is correct and complete. If everything is alright, an AJAX call should point to form-mail.php, in which I send the request from the user to the owner.
script.js and form-mail.php work, but I don´t know the mistake in the AJAX call?
if (sum == 0) {
document.getElementById("name").style.borderColor = "green";
document.getElementById("email").style.borderColor = "green";
document.getElementById("nachricht").style.borderColor = "green";
$.ajax({
type: "POST",
url: "mailform/form-mail.php",
data: $("#myForm").serialize(),
beforeSend: function() {$("#myForm").css({"opacity": "0.2"})}
}).done(function(msg) {
$("#emailform").fadeOut(1000);
setTimeout(function () {
$("#myForm").append('<p id=\"adder-content\" style=\"display:block;width:100%;margin:0 auto;padding-top: 3em;text-align:center;color:green\"><span>' + msg + '</span></p>').css({"opacity": "1"});}, 1000);
});
e.preventDefault();
window.location.href = "http://www.just.a.test";
}
I had this code in two other projects and it worked, but since yesterday there´s a problem with it.
I think the problem is with
window.location.href = "http://www.just.a.test";
before the completion of the ajax call it redirects. Remove it or place it in the done section of the ajax call.
This should work
if (sum == 0) {
document.getElementById("name").style.borderColor = "green";
document.getElementById("email").style.borderColor = "green";
document.getElementById("nachricht").style.borderColor = "green";
$.ajax({
type: "POST",
url: "mailform/form-mail.php",
data: $("#myForm").serialize(),
beforeSend: function() {$("#myForm").css({"opacity": "0.2"})}
})
.done(function(msg) {
$("#emailform").fadeOut(1000);
setTimeout(function () {
$("#myForm").append('<p id=\"adder-content\" style=\"display:block;width:100%;margin:0 auto;padding-top: 3em;text-align:center;color:green\"><span>' + msg + '</span></p>').css({"opacity": "1"});
window.location.href = "http://www.just.a.test";
}, 1000);
});
e.preventDefault();
// window.location.href = "http://www.just.a.test";
};
Try this
$.ajax({
url: 'mailform/form-mail.php',
type: 'POST',
data: {data:data},
before:function(){
$("#myForm").css({"opacity": "0.2"});
}
success:function(response){
console.log(response);
}
});

make an ajax call in the very first page in JQM

I am trying to show a popup in my first page if a php post returns a json file with data.
I tried with:
$(document).on("pageinit", '#home', function() {
ajax call even with async:false,...
And after that, I fill up the element with some list elements if json has data:
if(userLastPush == 1){
var getPushXdays = '{"day":"4"}';
$.ajax({
type: "POST",
url: urlServer+"getPushXDays.php",
data: getPushXdays,
async: false,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(response) {
//console.log(response);
html = '';
if(response.message != "empty"){
jQuery.each(response, function(category, val) {
if(val.id_Event == 0){
html +='<li>' + val.message + '</li>';
}else{
html +='<li>' + val.message + '</li>';
}
});
}
$(".popupPush").append(html).listview('refresh');
if(checkPushing == 0){
$("#checkpush").trigger("click");
}
},
error: function(xhr, status, message) {}
});
}
But it just works sometimes. Others, ajax never ends or never shows data. I tried by using a function instead and function is called but no return from ajax. Is there a way to make this getting all data before page is load?

Why webkit notification event does not trigger?

I have wrote a webkit notification script on my web app to pull notifications from a database. The code is seen below:
function checkNotifications() {
if (window.webkitNotifications.checkPermission() == 1) {
window.webkitNotifications.requestPermission();
}
else {
$.ajax({
type: "GET",
dataType: 'json',
url: '/check_notifications',
success: function(data){
if (data){
var ticketId = data.ticket_id;
console.log(data);
var comment = data.comment;
var createdDate = data.created_at;
var notificationComment = data.comment;
var notificationId = data.notifcation_id;
var notification = window.webkitNotifications.createNotification('/pt_logo_small.png', 'Project Ticket '+ticketId+ ' Updated!', 'Ticket has been updated. Click here to see!');
notification.show();
console.log(notificationId);
notification.onclick = function(){
this.close();
console.log("NOTIFICATION WAS CLICKED!")
$.ajax({
type: "GET",
dataType: 'json',
url: '/read_notifications/' + notificationId,
success: function(){
window.location = '/pto/' + ticketId;
},
error: function(){
window.location = '/pto/' + ticketId;
}
});
console.log(ticketId, comment, createdDate);
};
}
}
});
}
setTimeout(checkNotifications, 20000);
}
For some reason. I if select another tab, or go to another path inside my webapp, the script still runs to display the notifications, however the .onclick event never triggers.
Anyone have any idea why the even wouldn't trigger?
According to Apple, onclick should bring the page which created the event to focus, which it does. However nothing inside my .onclick function triggers.

cant pass the value from data using ajax

this is very frustrating, 2 hours passed and still can't get it working.
I just want to test on how to pass a value to my method using ajax.
Code:
Javascript
$('#form-payment').submit(function () {
var request = $.ajax({
url: "<?php echo site_url(array('home', 'update_credit_card')); ?>",
type: "POST",
data: 'someNumber=12'
});
request.done(function(data) {
console.log('boom' + data);
});
request.fail(function(jqXHR, textStatus) {
console.log('error' + textStatus);
//print_r(jqXHR);
});
});
PHP
function update_credit_card()
{
var_dump($_POST['someNumber']);//returns NULL value
$somenumber = $_POST['someNumber'];
if ($somenumber == '12') {
print "Number is 12";
} else {
print "Number is not 12";
}
}
The code is very simple but for the life of me can't get it to work. T_T.
Badly need help.
You can also use like this.
var values={};
values['arg1'] = 1;
values['arg2'] = 2;
$.ajax({
type:'POST',
url:'....',
data: values,
success:function(){}
});

asp.net button client side confirmation before submit

I have this problem: I need to validate that files have not been uploaded already, for which I use a webservice with Jquery called by isAlreadyUploaded() which returns true or false. Should the files exists, a confirmation to proceed is asked. THEN, once that is finished, I want to call the Button1_Click function to finish the operation. My problem is tha both of them are being called at the same time, thus avoiding the confirmation.
Maybe I am approaching the problem the wrong way. If so, feel free to correct me.
<asp:Button ID="Button1" runat="server" Text="Upload" onclick="Button1_Click" OnClientClick="return isAlreadyUploaded()" />
<script>
function isAlreadyUploaded() {
var mystring = "";
$.ajax({
type: "POST",
url: "Main.aspx/alreadyUploaded",
data: "{'swfFile':'" + $("#<%=FileUpload2.ClientID%>").val() + "','flvFile':'" + $("#<%=FileUpload3.ClientID%>").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
mystring = msg.d;
alert(mystring);
if (mystring != "") {
if (confirm(mystring)) {
return true;
} else {
return false;
}
} else {
return true;
}
}
});
}
</script>
It should work if you add the following option:
$.ajax({
/* ... code ...*/
async : false,
/* ... code ...*/
});
You're making an asynchronous request to the server when you need to make a synchronous request.
http://api.jquery.com/jQuery.ajax/
Because ajax is async by nature isAlreadyUploaded will not wait for the server to respond and since you are not returning anything from isAlreadyUploaded it will be treated as true and the button will submit the form.
You can set async property of ajax config to false so that it will wait for the server to respond before leaving from the function.
function isAlreadyUploaded() {
var mystring = "", retVal = false;
$.ajax({
async: false
type: "POST",
url: "Main.aspx/alreadyUploaded",
data: "{'swfFile':'" + $("#<%=FileUpload2.ClientID%>").val() + "','flvFile':'" + $("#<%=FileUpload3.ClientID%>").val() + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
mystring = msg.d;
alert(mystring);
if (mystring != "") {
if (confirm(mystring)) {
retVal = true;
} else {
retVal= false;
}
} else {
retVal = true;
}
}
});
return retVal;
}
There is an ConfirmButtonExtender in the ajax toolkit which might be what you're looking for.
Here is an example i found:http://www.asp.net/ajaxLibrary/AjaxControlToolkitSampleSite/ConfirmButton/ConfirmButton.aspx

Categories

Resources