make an ajax call in the very first page in JQM - javascript

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?

Related

Populate Ajax response with clickable elements that fires another Ajax with correct parameters

So i have a function running an Ajax call that receives data and populate that as a table.
The response contains some rows with data and i now want to add a small fontawsome icon that when clicked fires another function with a parameter.
So i have this:
var latestprecasedata = '';
function getPreCaseData() {
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/GetPreCase",
dataType: "json",
success: function (response) {
if (response != null && response.d != null) {
var data = response.d;
data = $.parseJSON(data);
$("#PreCaseTblBody").html("");
for (var i in data) {
$("#PreCaseTblBody").append("<tr><td>" + data[i].pSubject + "</td><td><span class='preplus' id='" + data[i].pID + "'><i class='fa fa-plus'></i></span></td><td>-</td></tr>");
}
if (latestprecasedata !== response.d) {
$("#precasestatus").removeClass("titleupd1").addClass("titleupd2");
latestprecasedata = response.d;
}
else {
$("#precasestatus").removeClass("titleupd2").addClass("titleupd1");
}
}
$("#PreCaseTblBody tr:odd").css('background-color', '#f9f9f9'); //
$("#PreCaseTblBody tr:even").css('background-color', '#f1ffee');
setTimeout(getPreCaseData, 10000);
}
});
}
This works and every 10 seconds data is repopulated. (Maybe not the fastest solution, but it works..)
As you all can se i have a span with class=preplus and id of a unique value coming from my Ajax response. When inspecting the page i can see that every row from my Ajax response have a unique id.
For example two row looks like this:
<tr><td>Cables</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
<tr><td>Skrews</td><td><span class="preplus" id="4815269"><i class="fa fa-plus"></i></span></td></tr>
So now i have the data populated with span containing a unique id that i want to pass to another function.
I've tried span, div, buttons but the only one time I actually got a event fire was when i placed my second function inside the
for (var i in data) {
... and i know, that's not right at all because all rows contained the last id obviously...
So my other function resides outside my first function and look like this (I've tried many different methods to get the id of my span but for now, I'm here)
$(".preplus").click(function () {
var qID = $(this).attr('id');
$.ajax({
cache: false,
type: "POST",
contentType: "application/json; charset=utf-8",
url: "case.aspx/UpdateQ",
dataType: "json",
data: "{'qid':'" + qID + "','pm':'plus'}",
success: function (data) {
}
});
return false;
});
Please guide me.

AJAX does what I need it to do, but errors still occur

I am writing a web page which reads data from an html table to be used on a MySQL query using PHP. This is a continuation of this question. I got AJAX send the data I need to use on to the PHP file with the code to update the information it sent. However, two errors have occured.
I get a message saying Error:Error: jQuery21405680291895882033_1487801210725 was not called
The data I send has a ":1" at the end of it, giving me an error.
How can I fix these two mistakes? Thank you so much!
JS code:
function getTableData(){
var array = [];
var headers = [];
$('#tablaListado th').each(function(index, item) {
headers[index] = $(item).html();
});
$('#tablaListado tr').has('td').each(function() {
var arrayItem = {};
$('td', $(this)).each(function(index, item) {
if($(this).find("textarea").length){
var costo = $(this).find('textarea').val();
arrayItem[headers[index]] = costo;
}else{
arrayItem[headers[index]] = $(item).html();
}
});
array.push(arrayItem);
});
actualizarCostos(array);
}
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: false,
jsonpCallback: jsonCallback,
cache: true,
data:{ "table_data": JSON.stringify(array[i])},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
},
traditional: true
});
}
}else{
alert("Input must be array");
}
}
function jsonCallback(data, status){
console.log(data + " " + status);
}
PHP portion:
//Added on top of the page
header('Access-Control-Allow-Origin: *');
...
function updateCosts($json){
conectar();
$array = json_decode($json, true);
echo "<script>console.log('$array');</script>";
$costo = $array["Costo"];
$sku = $array["SKU"];
$instruccion = "UPDATE articulos SET art_cost='$costo' WHERE art_SKU = '$sku'";
return ejecutarInstruccion($instruccion);
}
if(isset($_GET['table_data'])){
foreach($_GET['table_data'] as $index => $item)
{
// do something here
echo "<script>console.log('$item');</script>";
updateCosts($item);
}
// Response back - if needed
echo json_encode(array('status'=>true, 'msg'=>'Some Message'));
}
Edit:
I forgot to mention that I have tried changing 'jsonp' as 'json' on this code but I get an error saying the PHP file doesn't allow foreign data, even though I tried using header('Access-Control-Allow-Origin: *') on said file.
Your page is returning JSON, not JSONP. They aren't interchangeable. Remove the jsonp and jsonpCallback properties from the $.ajax() call, and change dataType to json:
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: true,
data: {
table_data: JSON.stringify(array[i])
},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status" + status + " \nError:" + err);
},
traditional: true
});
I'd suggest you have the following AJAX:
function actualizarCostos(array){
if(array.constructor === Array){
for(var i = 0; i < array.length ; i++){
console.log(array[i]);
console.log(JSON.stringify(array[i]));
}
$.ajax({
url: "http://www.page.com/Update.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
data:{ "table_data": JSON.stringify(array)},
success: function (data) {
console.log(data);
},
error: function(xhr,status,err){
alert("DEBUG: status"+status+" \nError:"+err);
}
});
}else{
alert("Input must be array");
}
}
Then do the For-Loop on the PHP side of the server. Maybe each variable in array has a hidden parameter to know its own index, or JSON is doing something strange like displaying the number of elements in the array (in this case 1 because you're iterating over each one)

Page not loading after Postback event completes - ASP.Net

I have a Javascript function on a button click with a POST to a WebMethod. After getting the response back; which is a redirect URL, the code goes to the IsPostBack event of the redirected page but that page never loads. I have written redirects all over the place but somehow this one just stays on the page it is called from.
jQuery.ajax({
type: "POST",
url: "MyProfile.aspx/UpdateProfile_Clicked",
async: false,
data: parms,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d != '') {
alert("Your profile has been updated.");
// response.d = "SubmitRequest.aspx"
var data = response.d;
if (data.indexOf("aspx", 0) > -1) {
redirect(data);
}
}
return false;
},
error: function (httpRequest, textStatus, errorThrown) {
LogAjaxErrorToServer(httpRequest, textStatus, errorThrown, parms, "UpdateProfile_Clicked");
}
});
function redirect(url) {
if (url == "") { return false; }
var indx = window.location.pathname.lastIndexOf('/', 0);
if (indx < 0) { indx = 0; }
var local = window.location.pathname.substr(0, indx);
local += "/" + url;
location.href = local;
return false;
}
So the code does go to the (!IsPostBack) for SubmitRequest.aspx but stays on the Profile.aspx. What am I missing? Thank you in advance for helping me
May

How to ensure that a function is executed completely, before navigating to another page?

I'm removing certain records using a webservice. The jquery ajax request is written in the onclick of a hyperlink. When im executing the script, line by line using firebug, it's getting removed otherwise it's not. Does any one meet any situation like this before? Please help
Code sample:
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
jQuery ajax functions return deferred objects, thus we return $.ajax. Then you should use deferred.done to execute the callback when the AJAX is fully finished. When the AJAX is done, navigate away using JS instead:
var func = function() {
...
return $.ajax({...}); //return our ajax deferred
}
$(".target").click(function() {
var target = this; //preserve "this" since this in the callback may be different
func().done(function(){ //our done callback executed when ajax is done
window.location.href = target.href; //assuming .target is a link
});
return false; //prevent the natural click action
});
You can use the async: false on the ajax call that is wait there to complete the call.
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: false,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
}
//Event that'll be fired on Success
});
}
Alternative you can make the submit after the request.
$(".target").click(function() {
func(); //This function should be executed completely before navigating to another page
return false;
});
var func = function() {
var items = $("#flag").find('td input.itemClass');
id = items[0].value;
var status = items[1].value;
var type = items[2].value;
var params = '{' +
'ID:"' + id + '" ,Type:"' + type + '" ,Status:"' + status + '"}';
$.ajax({
type: "POST",
async: true,
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed"); // keep a separate label to display this message
$("#YourFormID").submit();
}
//Event that'll be fired on Success
});
}
Simply move the Event to the "success" handler in your ajax request:
$.ajax({
type: "POST",
url: "WebMethodService.asmx/DeleteItem",
data: params,
//contentType: "plain/text",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
$("#deleteNotificationMessage").val("Item has been removed");
//Event that'll be fired on Success
}
});
Alternatively use jQuery ajax callback methods.

Updating jQuery Item during Ajax call

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');
}
}
});
}):

Categories

Resources