Jquery when ; value not set - javascript

I need to repalce the href of a 'title' class elements in the page on the basis of the 0 or x value returned from http://kasaragodyellowpages.com/pagedata.php?id=x. this url is set to 1 for testing. work currectly to ajax requests.
problem is late response and failure in when
<script type="text/javascript">
$(document).ready(function(){
$('.title').each(function() {
var url = null;
var l = this.href;
id_str= (l.replace('http://www.kasaragodyellowpages.com/index.php?page=item&id=',''));
var loadUrl = "pagedata.php";
$.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
}
}
);
if(url){
console.log('set data for '+url);
$(this).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
}
});
});
</script>
As in the image the ajax result is set after the setting the value from loop with out waiting for ajax success
After this i replaced with when
<script type="text/javascript">
$(document).ready(function(){
$('.title').each(function() {
var url = null;
var l = this.href;
id_str= (l.replace('http://www.kasaragodyellowpages.com/index.php?page=item&id=',''));
var loadUrl = "pagedata.php";
$.when($.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
}
}
))
.then(if(url){
console.log('set data for '+url);
$(this).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
});
});
});
</script>
But this didn't work

in your first code, replace your call to $.get with
$('.title').each(function() {
var url = null;
var self = this;
.
.
.
.
$.get(
loadUrl,
{id: id_str},
function(responseText){
if (responseText!=0) {
url='http://www.kasaragodyellowpages.com/index.php?page=page&id='+responseText;
console.log('data value for '+url);
if(url){
console.log('set data for '+url);
$(self).attr( 'href', url );
}else
{
console.log('NOT set data for '+url);
}
}
}
);
The reason is $.get is an asynchronous call. Meaning, all code after $.get will be executed even if the response from $.get has not been received yet.

Related

Ajax call in loop: Ajax requests getting cancelled except last

I have one ajax call in a loop as shown below.
reloadSetupAndRecurringAvailable = function( objDiscountRow ) {
var intProductId = objDiscountRow.find('.product-id').val();
var strUrl = '/?module=contract_setup_products-new&action=get_setup_and_recurring_available';
$.ajax( {
url: strUrl,
data: { 'product_id': intProductId },
success: function( response ) {
fltSetupAvailable = parseFloat( response.data.fltSetupAvailable );
fltRecurringAvailable = parseFloat( response.data.fltRecurringAvailable );
objDiscountRow.find('.setup-available').text( fltSetupAvailable + '%' );
objDiscountRow.find('.recurring-available').text( fltRecurringAvailable + '%' );
}
} );
reloadDiscountProducts = function() {
$('.discount-row').each( function() {
reloadSetupAndRecurringAvailable( $(this) );
} );
}
reloadDiscountProducts();
When the code executes, in the network tab the last ajax call shows successful and all the previous calls show in canceled status.
As per my findings it is due to asynchronization. The ajax request can take any time. How can I fix the code so that all the requests will be in completed status?

Jquery ajax call not firing

i'm making an app to track different craft beers i've tasted. part of that is making an AJAX call to set a cookie in the uder's browser -- i'm json_encoding the list.beerList array and trying to store it in a cookie. for some reason, the cookie is getting set, but Firebug isn't registering an AJAX call being made. and even when i send something back, the success condition of the jquery AJAX function isn't firing. code below:
angular.module( 'beerList', [] ).controller( 'beerListController', function($scope) {
var list = this;
list.beerList = [];
angular.element(document).ready( function() {
list.getCookie();
})
list.addBeer = function() {
var beerEntered = $( '#beer' ).val();
var breweryEntered = $( '#brewery' ).val();
var abvEntered = $( '#abv' ).val();
var notesEntered = $( '#notes' ).val();
list.beerList.push( { beer: beerEntered, brewery: breweryEntered, abv: abvEntered, notes: notesEntered } );
list.setCookie();
}
list.setCookie = function() {
var string = JSON.stringify(list.beerList);
$.ajax({
url: 'ABSOLUTE/PATH/TO/setCookie.php',
dataType: 'jsonp',
data: {
string: string
},
success: function(data) {
alert('success!');
}
})
}
list.getCookie = function() {}
})
thanks so much for your help!

Executing JavaScript returned from a .post [duplicate]

This question already has an answer here:
Evaluating scripts in an ajax response
(1 answer)
Closed 8 years ago.
I want JavaScript to execute the data that is returned from a post. I have found several similar threads but nothing that has cleared it up for me. eval() throws an unexpected identifier error.
The post:
$.post("./save.php",
{
'images_key' : images_array,
'userid_key' : $('#userid').val(),
'avatar_key' : $('#avatar_name').val()
},
function( data )
{
$( "#responseText" ).val( data );
eval(data);
}
);
The post is returning:
$('.frame').html2canvas({
onrendered: function (canvas) {
//Set hidden field's value to image data (base-64 string)
$('#img_val').val(canvas.toDataURL('image/png'));
//Submit the form manually
document.getElementById('myForm').submit();
}
});
Any ideas?
Thanks!
MORE INFO:
On button click I'm calling this function:
function saveCSS() {
var id_data = $(".frame div img").map(function() {
return $(this).attr("id");
}).get();
var title_data = $(".frame div img").map(function() {
return $(this).attr("title");
}).get();
var width_data = $(".frame div img").map(function() {
return $(this).css("width");
}).get();
var height_data = $(".frame div img").map(function() {
return $(this).css("height");
}).get();
var top_data = $(".frame div:has(img)").map(function() {
return $(this).css("top");
}).get();
var left_data = $(".frame div:has(img)").map(function() {
return $(this).css("left");
}).get();
var zindex_data = $(".frame div:has(img)").map(function() {
return $(this).css("z-index");
}).get();
var images_array = [];
$.each(id_data, function (index, value) {
images_array.push(value);
images_array.push(title_data[index]);
images_array.push(width_data[index]);
images_array.push(height_data[index]);
images_array.push(top_data[index]);
images_array.push(left_data[index]);
images_array.push(zindex_data[index]);
});
$.post("./save.php",
{
'images_key' : images_array,
'userid_key' : $('#userid').val(),
'avatar_key' : $('#avatar_name').val()
},
function( data )
{
// $( "#responseText" ).val( data );
// console.log(data);
eval(data);
}
);
}
The file save.php contains:
.
.
.
echo "
$('.frame').html2canvas({
onrendered: function (canvas) {
$('#img_val').val(canvas.toDataURL('image/png'));
document.getElementById('myForm').submit();
}
});
";
.
.
.
console.log(data) logs the echo as per expected however, in Chrome's console, when I execute saveCSS(), I see:
function( data )
{
// $( "#responseText" ).val( data );
// console.log(data);
eval(data);
**Uncaught SyntaxError: Unexpected Identifier**
}
);
I'm afraid I do not understand why I'm getting the error.
In order to execute the dat that is returning you have to eval it e.g.
$.post("./save.php",
{
'images_key' : images_array,
'userid_key' : $('#userid').val(),
'avatar_key' : $('#avatar_name').val()
},
function( data )
{
$( "#responseText" ).val( data );
eval(data);
}
);
That said unless you absolutely trust the code you are receiving from the server, I wouldn't recommend executing the data as it could lead to a XSS vulnerability in your site.

jQuery $.post not executing, how to fix

I am working on a Plugin for WordPress and am having issues with the js code below executing the $.post.
The js is called, form validation takes place, the form inputs are serialized into post data correctly, the $.post just doesn't execute.
The form is being posted from the Admin, currently I can't get the .submit action to work so am using .click to execute the js function. This may be related to the issue, I am not sure... The form will load without submitting if I use the .submit action, versus using the .click action... never had this issue before and it is pretty frustrating to say the least.
Here is the code:
jQuery(document).ready(function($) {
$("#edit_member_submit").click( function() {
// define
var numbers = /^[0-9]+$/;
var referrer_id = $("#referrer_id").val();
// Validate fields START
if( !referrer_id.match(numbers) ) {
alert("Please enter a numeric value");
return false;
}
// Validate fields END
$("#ajax-loading-edit-member").css("visibility", "visible");
// Convert to name value pairs
// Define a data object to send to our PHP
$.fn.serializeObject = function() {
var arrayData, objectData;
arrayData = this.serializeArray();
objectData = {};
$.each(arrayData, function() {
var value;
if (this.value != null) {
value = this.value;
} else {
value = '';
}
if (objectData[this.name] != null) {
if (!objectData[this.name].push) {
objectData[this.name] = [objectData[this.name]];
}
objectData[this.name].push(value);
} else {
objectData[this.name] = value;
}
});
return objectData;
};
var data = $("#edit_member_form").serializeObject(); //the dynamic form elements.
//alert(JSON.stringify(data));
data.action = "edit_member_info"; //the action to call
data._ajax_nonce = custajaxobj.nonce; // This is the name of the nonce setup in the localize_script
// Define the URL for the AJAX to call
var url = custajaxobj.ajaxurl;
//alert( JSON.stringify( data ) );
//alert( JSON.stringify( url ) );
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
return false;
});
});
Seems like the last section is having issues:
$.post(url, data, function(response) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(response);
});
$.post( "ajax/test.html", function( data ) {
$("#ajax-loading-edit-member").css("visibility", "hidden");
alert(data);
});

Callback never called on Jquery.post();

I'm having some trouble using JQUERY Post function.
I have 2 functions that call JQUERY Post function.
Both of them is working fine, but the callback function is never called (handleLike).
When I call handleLike manually, it's works perfect.
(Even if handleLike has just an alert inside, the callback function is not called)
Could you please help me with this thing?
<script type="text/javascript">
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
if (v_cb.class == 'map'){
var elemento = $('#maplike');
}else{
var elemento = $('#commentlike'+v_cb.id);
}
if (!(elemento.hasClass('disabled'))){
elemento.addClass("disabled");
var likes = elemento.find('font').text();
likes++;
elemento.find('font').html(likes);
}
}
$('#maplike').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
var JSONObject= {
"mensagem":"Testando Json",
"id":86,
"class":"map"
};
handleLike(JSONObject);
alert("Teste");
$.post(
'/cmap/maps/like',
{ id: id },
handleLike,
'json'
);
}
});
$('[id*="commentlike"]').click(function() {
//var map_id = $('#like').find('font').attr('value');
var id = $(this).attr("name");
if (!($(this).hasClass('disabled'))){
$.post(
'/cmap/comments/like',
{ id: id },
handleLike,
'json'
);
}
});
});
</script>
Diagnostic, not solution
Rationalizing and adding an error handler, you should get something like this :
$(document).ready(function() {
function handleLike(v_cb){
alert("Call back chamou!");
$('#erro').html(v_cb.mensagem);
var elemento = (v_cb.class && v_cb.class == 'map') ? $('#maplike') : $('#commentlike'+v_cb.id);
if (!elemento.hasClass('disabled')){
var f = elemento.addClass("disabled").find('font');
f.html(++Number(f.text()));
}
}
function ajaxError(jqXHR, textStatus, errorThrown) {
alert('$.post error: ' + textStatus + ' : ' + errorThrown);
};
$('#maplike').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/maps/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
$('[id*="commentlike"]').on('click', function() {
var $this = $(this);
if (!$this.hasClass('disabled')) {
$.post('/cmap/comments/like', { id: $this.attr("name") }, handleLike, 'json').fail(ajaxError);
}
});
});
untested
Barring mistakes, there's a good chance the error handler will inform you of what's going wrong.
I follow the Kevin B tip and use $ajax method.
It was a parseerror. Sorry.
The return of v_cb was not a json, it was a html. I correct my return, and everything was ok.

Categories

Resources