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.
Related
I've made a custom throttle for ajax requests.
Problem is I keep getting this error?
Uncaught TypeError: Failed to execute 'postMessage' on 'Window': 1 argument required, but only 0 present.
The line points to $.ajax({.
HTML:
<input class="image_title" />
<span class="the_title"></span>
JS:
$(function() {
var aj_count = 0;
var aj_flag = false;
var aj_flag2 = false;
var run_on = -1;
setInterval(function() {
aj_count++;
if (aj_flag === true) {
run_on = aj_count + 250;
aj_flag = false;
aj_flag2 = true;
}
if (run_on < aj_count && aj_flag2 === true) {
var $t = $(this);
var daid = $('.image_id').val();
aj_flag2 = false;
$.ajax({
type: "POST",
url: '/ajax/set_title.php',
data: {
'title' : $t,
'id' : daid
},
success: function(data) {
var data = JSON.parse(data);
$('.the_title').html( '<small>Title:</small> <strong>' + data.title + '</strong>' );
}
});
}
}, 1);
$('.image_title').on('input', function(e) {
aj_flag = true;
e.preventDefault();
return false;
});
$('.image_title').on('keydown', function(e) {
if (e.which == 13) {
e.preventDefault();
return false;
}
});
});
As you can see I have tried moving direct form vals into variables etc but I cannot get it to work anymore. When I replace the ajax section with a console.log it runs as expected. I've been looking around but I don't really understand what the error means still as ajax has an array passed to it.
Thank you for your time
The error is probably because of
var $t = $(this);
You're trying to send $t as the value of the title: parameter with
data: {
title: $t,
id: daid
},
But a jQuery object can't be serialized into a POST parameter.
You need to set $t to a proper title string. I don't know where that is in your application, but that should fix it.
i am filling up my dropdowns using this ajax call ..selectItems create select option tags in html using attribute_map
var $el = this.$el(model);
var rule_title = "Job Family: ";
var attribute_map = [];
var current_object = this;
$el.append(this.getRuleTitle(rule_title, model));
jQuery.ajax({
url : "<%= Rails.configuration.url_prefix %>/team/index/get_rule_attribute_values",
type : "GET",
data : { name : "jobFamily" },
dataType : "json",
success : function(data){
var attribute_array = data.value.rule_attribute_values;
attribute_array.sort(function(a,b){
if(a.display_name > b.display_name){
return 1;
}
if(a.display_name < b.display_name){
return -1;
}
return 0;
});
var index = 0;
var obj;
for (obj in attribute_array){
attribute_map[index] = [];
attribute_map[index][0] = attribute_array[index].display_name + " ( " + attribute_array[index].internal_name + " ) " ;
attribute_map[index][1] = attribute_array[index].internal_name;
index++;
}
current_object.selectItems($el,
attribute_map,
"jobFamily", model.jobFamily, {multiple : "multiple", "data-placeholder" : "Add Constraint..."}, "400px");
},
complete : function() {
console.log("completed");
},
error : function(jqXHR, textStatus,errorThrown){
var requestResponse = {
httpStatus: jqXHR.status,
error:jqXHR.statusText,
};
}
});
when i put async as false ..event handler works fine but in synchronous call , the just doesn't do anything
event handler looks like
$('.chosen-select jobFamily').on('change',function(evt, params){
console.log("completeddddddd");
var value = $('.chosen-select jobFamily').val();
console.log(value);
if (value == null) {
// Input is empty, so uncheck the box.
$('.jobFamily').prop("checked", false);
} else {
// Make sure the box is checked.
$('.jobFamily').prop("checked", true);
}
});
});
where '.chosen-select jobFamily' is class of select tag and '.jobFamily' is class of check box ... i have tried writing my jquery inside complete argument of ajax call , i tried writing my jquery inside
$('document).bind('ajaxComplete',function({
//above jquery
});
please help . i have spent more than 2 days on that . all code lies inside ready function.
I've read about the jQuery's Deferred object, but I can't seem to make much sense out of it, here's my problem, I've got the following code:
function preprocess(form) {
$(form).find(".input input").each(function() {
var required = $(this).attr("required");
var checkField = $(this).closest(".inputcontainer").children(".check");
var errorField = $(this).closest(".inputcontainer").children(".errormessage");
if (typeof required !== 'undefined') {
$(checkField).each(function() {
$(this).css("color", "#FFFF00");
$(this).html("✘");
});
$(errorField).each(function() {
$(this).css("color", "#FFFF00");
$(this).html("(Required)");
});
}
else {
$(checkField).each(function() {
$(this).css("color", "#FFFF00");
$(this).html("✔");
});
$(errorField).each(function() {
$(this).css("color", "#000000");
$(this).html("");
});
}
});
$(form).find("datalist").each(function() {
var datalist = $(this);
callService({
name: "datalist_" + $(this).attr("id"),
data: { },
success: function(json) {
$(json).each(function() {
var html = "";
$(this.options).each(function() {
html += "<option value='" + this.value + "'>";
});
$(datalist).append(html);
});
}
});
});
$(form).find("select").each(function() {
var select = $(this);
callService({
name: "select_" + $(this).attr("name"),
data: { },
success: function(json) {
$(json).each(function() {
var html = "";
$(this.options).each(function() {
html += "<option value='" + this.id + "'>" + this.value + "</option>";
});
$(select).append(html);
});
}
});
});
}
This code prepares a form to be ready to be presented to the user, which involves AJAX calls, which I have wrapped in a callService({}); call, what you can see is the following:
It checks input and puts possibly (Required) next to the fields. (No AJAX)
It loads options from <datalist> and <select>s dynamically. (AJAX)
Then I also have the following (simplified):
function setContent(html, url) {
html = $.parseHTML(html);
$(html).filter("form").each(function() {
preprocess($(this));
});
$("#pagemain").html(html);
}
This gets html from an AJAX call, then calls preprocess on all its forms and updates the #pagemain.
However now data is being displayed before the preprocess has completely finished.
The question: How can I do the $("#pagemain").html(html); after preprocessed ánd involving AJAX processes, have been finished?
Try:
function preprocess(form) {
//Your above code is omitted for brevity
var promises = [];
$(form).find("datalist").each(function() {
var defered = $.Deferred();//create a defered object
promises.push(defered.promise());//store the promise to the list to be resolved later
var datalist = $(this);
callService({
name: "datalist_" + $(this).attr("id"),
data: { },
success: function(json) {
$(json).each(function() {
var html = "";
$(this.options).each(function() {
html += "<option value='" + this.value + "'>";
});
$(datalist).append(html);
});
defered.resolve();//resolve the defered when ajax call has finished
}
});
});
$(form).find("select").each(function() {
var defered = $.Deferred();//create a defered object
promises.push(defered.promise());//store the promise to the list to be resolved later
var select = $(this);
callService({
name: "select_" + $(this).attr("name"),
data: { },
success: function(json) {
$(json).each(function() {
var html = "";
$(this.options).each(function() {
html += "<option value='" + this.id + "'>" + this.value + "</option>";
});
$(select).append(html);
});
defered.resolve();//resolve the defered when ajax call has finished
}
});
});
return promises;
}
Your setContent:
function setContent(html, url) {
html = $.parseHTML(html);
var promises = [];
$(html).filter("form").each(function() {
promises = promises.concat(preprocess($(this)));//Concatenating all promises arrays
});
$.when.apply($,promises).then(function(){// Use $.when to execute a function when all deferreds are resolved.
$("#pagemain").html(html);
});
}
Deferred's can be a little intimidating to learn at first, but, like most things, once the light bulb goes on and you get it, it's pretty simple. The simple setup for creating a deferred object is like this:
var defer = $.Deferred(function(dfd) {
// do the processing you need, and then...
// when processing is complete, make a call to...
dfd.resolve(/* return data goes here, if required */);
}).promise();
// use the deferred object like it was an ajax call
defer.then(/* do the stuff that needed to wait */);
So, using your example:
function setContent(html, url) {
html = $.parseHTML(html);
var defer = $.Deferred(function(dfd) {
$(html).filter("form").each(function() {
preprocess($(this));
});
dfd.resolve();
}).promise();
defer.then($("#pagemain").html(html));
}
neat solution will be using when :
http://api.jquery.com/jQuery.when/
$.when( {//your preprocessing function here
} ).done(function( x ) {
//your done action here
});
I am using JQuery to collect latest tweets using Twitter API, but I am having some issues when calling two functions.
$(document).ready(function(){
JQTWEET.loadTweets();
});
This, is working ok, but then I want to call this function:
showHideTweets: function() {
alert("hola");
var ojeto = $(JQTWEET.appendTo).find(".item").first();
$(JQTWEET.appendTo).find(".item").first().css("display", "block");
},
Both functions are inside: jqtweet.js ...
loadTweets: function() {
var request;
// different JSON request {hash|user}
if (JQTWEET.search) {
request = {
q: JQTWEET.search,
count: JQTWEET.numTweets,
api: 'search_tweets'
}
} else {
request = {
q: JQTWEET.user,
count: JQTWEET.numTweets,
api: 'statuses_userTimeline'
}
}
$.ajax({
url: 'tweets.php',
type: 'POST',
dataType: 'json',
data: request,
success: function(data, textStatus, xhr) {
if (data.httpstatus == 200) {
if (JQTWEET.search) data = data.statuses;
var text, name, img;
try {
// append tweets into page
for (var i = 0; i < JQTWEET.numTweets; i++) {
img = '';
url = 'http://twitter.com/' + data[i].user.screen_name + '/status/' + data[i].id_str;
try {
if (data[i].entities['media']) {
img = '<img src="' + data[i].entities['media'][0].media_url + '" />';
}
} catch (e) {
//no media
}
var textoMostrar = JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) ).replace('{USER}', data[i].user.screen_name).replace('{IMG}', img).replace('{URL}', url );
/*.replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) ) */
//alert(JQTWEET.timeAgo(data[i].created_at));
$(JQTWEET.appendTo).append( JQTWEET.template.replace('{TEXT}', JQTWEET.ify.clean(data[i].text) )
.replace('{USER}', data[i].user.screen_name)
.replace('{NAME}', data[i].user.name)
.replace('{IMG}', img)
.replace('{PROFIMG}', data[i].user.profile_image_url)
/*.replace('{AGO}', JQTWEET.timeAgo(data[i].created_at) )*/
.replace('{URL}', url )
);
if ( (JQTWEET.numTweets - 1) == i) {
$(JQTWEET.appendTo).find(".item").last().addClass("last");
}
}
} catch (e) {
//item is less than item count
}
if (JQTWEET.useGridalicious) {
//run grid-a-licious
$(JQTWEET.appendTo).gridalicious({
gutter: 13,
width: 200,
animate: true
});
}
} else alert('no data returned');
}
});
callback();
},
showHideTweets: function() {
alert("hola");
var ojeto = $(JQTWEET.appendTo).find(".item").first();
$(JQTWEET.appendTo).find(".item").first().css("display", "block");
},
The problem is that if a call functions like this:
$(document).ready(function(){
JQTWEET.loadTweets();
JQTWEET.showHideTweets();
});
Second function executes before tweets has been loaded, so it have nothing to search in, because I can see the alert("hola") working, but Ojeto is 0.
I was trying to create some kind of callback inside loadTweets(); but I could not.
The callback isn't a bad idea.
change loadTweets to look like this:
loadTweets: function(callback) {
And call it here:
$.ajax({
...
success: function(data, textStatus, xhr) {
...
if (callback) callback();
}
});
And then in your DOM ready callback:
$(document).ready(function(){
JQTWEET.loadTweets(JQTWEET.showHideTweets);
});
Your other option (which I actually prefer, in general) is to use a deferred object:
loadTweets: function(callback) {
var def = $.Deferred();
...
$.ajax({
...
success: function(data, textStatus, xhr) {
...
def.resolve();
}
});
return def.promise();
}
...
$(document).ready(function(){
JQTWEET.loadTweets().done(JQTWEET.showHideTweets);
});
Try jQuery methods chaining:
$(document).ready(function(){
JQTWEET.loadTweets().showHideTweets();
});
I have searched the net, i´ve tried implementing "preventdefaults" and "return false" statements all over the place, but I can´t seem to find a way to prevent this form submitting and reloading the page. It only reloads when the form has been validated. I´m kind of a beginner, but I really tried hard achieving the script to validate a form (which has "post"-method and "#" as action), and make an ajax-call. It´s a school assignment and would be graceful towards any pointers you guys could give.
$(document).ready(function()
{
$("#submit").click(function()
{
var gbname = $("#gbname")[0];
var gbmessage = $("#gbmessage")[0];
formFields = [gbname, gbmessage]
var warning = false;
for (i=0; i<formFields.length; i++)
{
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "")
{
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true)
{
alert("Vänligen fyll i fälten korrekt!");
return false;
}
else
{
$.post('ajax.php', {gbname: gbname, gbmessage: gbmessage},
function(data)
{
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" +gbname+ "</p> <p class='messages'><b>Meddelande:</b>" +gbmessage+ "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
});
return false;
}
return false;
});
});
Your references to the input elements as objects and the data returned from your AJAX call were a bit muddled.
Also incorporated the suggestion of binding to the form's submit event. DEMO
$(document).ready(function () {
function clearForm(){
$('input.reset').each(function(){
$(this).val('');
});
}
$("form").on('submit', function () {
alert('submitted!');
var gbname = $("#gbname");
var gbmessage = $("#gbmessage");
formFields = [gbname[0], gbmessage[0]]
var warning = false;
for (i = 0; i < formFields.length; i++) {
formFields[i].style.backgroundColor = "white";
if (formFields[i].value == "") {
formFields[i].style.backgroundColor = "red"
$(formFields[i]).bind("keyup", resetBgColor);
$(formFields[i]).bind("change", resetBgColor);
warning = true;
}
}
if (warning == true) {
alert("Vänligen fyll i fälten korrekt!");
return false;
} else {
var J = JSON.stringify({
"gbname": gbname.val(),
"gbmessage": gbmessage.val()
});
console.log(J);
$.ajax({
type: "POST",
url: '/echo/json/',
datatype: 'json',
data: {
json: J,
delay: 3
},
success: function (data) {
$("#successmessage").html(data);
$("#successmessage").hide();
$("#successmessage").fadeIn(1500); //Fade in error/success-meddelande
var comment = $("<div class='film2'><p class='names'><b>Namn:</b>" + data.gbname + "</p> <p class='messages'><b>Meddelande:</b>" + data.gbmessage + "</p></div>");
$("#kommentarer").prepend(comment);
clearForm();
} // end success
}); // end ajax
return false;
} // end else
return false;
});
});
I suggest using
$("form").on('submit', function (e) {
[...]
if(validationErrors) {
alert(Errormessage);
e.preventDefault();
}
[...]
instead of returning false.
https://developer.mozilla.org/en-US/docs/DOM/event.preventDefault
In order to get it to work, you have to use the event as a parameter of your callback function.