Calling a user defined jQuery function - javascript

I'm a javascript newbie and I'm trying to call a jQuery function in this way:
function getProducts(){
$.post("products.php",
{
customer_ID:$("#customers").val()
},
function(data,status){
return status && data !== "";
});
};
$(document).ready(function(){
$("#customers").change(function(){
if(getProducts){
alert("trovato");
$("#products").prop("disabled", false);
$("#products").html(data);
}else{
alert("non trovato");
$("#products").empty();
$("#products").prop("disabled", true);
}
});
});
The if-else statement in the ready doesn't work although the function getProducts works properly. The problem, I suppose, is in the function call. What am I wrong with this? Thank you.

You need to wrap the response with a callback, like so:
function getProducts(callback){
$.post("products.php",
{
customer_ID:$("#customers").val()
},
function(data,status){
callback(status && data !== "");
});
};
$(document).ready(function(){
$("#customers").change(function(){
getProducts(function(status) {
if(status){
alert("trovato");
$("#products").prop("disabled", false);
$("#products").html(data);
}else{
alert("non trovato");
$("#products").empty();
$("#products").prop("disabled", true);
}
});
});
});

I'm not quite sure if this will work because of the asynchronized call inside of the function.
The obvious mistake is that you have to call a function like that: function(). You just forgot the parentheses.
If it won't work after that fix, you have to rework your program to use callbacks where you have asynchron calls.

Related

Jquery .load() callback not firing

Ive been struggling with this for hours now. I can't figure out why my .load() callback is not firing. Can anyone shed any light on this. Thanks for any help.
The load it's self works fine.
window.addEventListener('popstate', function(event) {
var linkplus = ((event.state) + ' #container'); //contents
if((event.state)==null){
$("#maincontainer").load("index.php #container", "null" , function(){
return false;
// why is this not working ??? //
alert("contents loaded");
});
}else{
$("#maincontainer").load(linkplus, function(){
return false;
$("#container").hide().delay(0).fadeIn(400);
project_nav();
});
}
});
hm, doesn't look like your alert would be hit right? You already return false before that.
When you return from a function, you return
$("#maincontainer").load("index.php #container", "null" , function(){
return false; // YOU RETURNED HERE, NOTHING BELOW IS EXECUTED
alert("contents loaded");
});
There's no need to return anything from load()
Hey I tried removing the "return false" with no success.I think it's because .load() is asynchronous?
Anyway, I got it to work using ".get" instead of .load and then selecting the contents with a variable. Thanks for the replies.
$.get( "index.php", function( data ) {
var content = $(data).find('#container').html();
$("#container").html(content);
alert("contents loaded");
});

getJSON with return value, Can someone take a look what is wrong here?

Im Trying to return a value from callback function with no success.
Can you see what is wrong here??:
function getval( callback ){
jQuery.getJSON('http://data.mtgox.com/api/1/BTCUSD/ticker?callback=?', function(data) {
// We can't use .return because return is a JavaScript keyword.
callback(data['return'].avg.value);
});
}
$(function () {
$(document).ready(function() {
getval( function ( value ) {
alert( 'Do something with ' + value + ' here!' );
} );
});
});
Here is JSFIddle link: http://jsfiddle.net/kf6qb/1/
Thank you very much!
Remove ?callback=? from the URL. That API doesn't support JSONP, and allows cross-domain calls.
See my FIDDLE
check this code its working FIDDLE
$(function () {
jQuery.getJSON('http://data.mtgox.com/api/1/BTCUSD/ticker?', function(data) {
// We can't use .return because return is a JavaScript keyword.
alert(data.return.avg.value);
});
});
Your data does not have a field called return. data['return'] is undefined.

Call A Function On ScrollExtend - jQuery

How to call a function on scrollExtend. I need the code like below but its not working fine. How to make it work?
$(document).ready(
function() {
$('#scrollBox').scrollExtend(function() {
//alert('scroll extend working');
//functionCall();
});
}
);
But the actual code of scrollExtend is like below in which i dont know how to call a function on it,
jQuery('.scroll_container').scrollExtend({
'target': 'div#scroll_items',
'url': 'more_content.html',
'newElementClass': 'list_item more_content'
});
I would use the built in function onScrollBeyond in JQuery.
Else there is a setting in scrollExtend that is called beforestart and onSuccess which both are callback variables which means you could put functions there like
$('#scrollBox').scrollExtend({
'target': 'div#scroll_items',
'beforeStart': myFunction,
'onSuccess': mySecondFunction
});
Regards
As BeadFist said, you can simply use onScrollBeyond:
$('.scroll_container').onScrollBeyond(functionCall);//if the function exists already, just pass a reference too it
$('.scroll_container').onScrollBeyond(function()
{
//your function
});
Mind you, for both scrollExtend and onScrollBeyond, you need the plugin, of course.
Try using onScrollBeyond:
$(document).ready(
function() {
$('#scrollBox').onScrollBeyond(function() {
//alert('scroll extend working');
//functionCall();
});
}
);
Try:
$('#scrollBox').scroll(function() {
if($('#scrollBox').scrollTop() + $('#scrollBox').height() == $(parentElm).height()) {
alert("bottom!");
}
});

Use jQuery to check if links still work

I made a quick function to check every link on the page using AJAX to see if they still work. This seems to be working, but it's adding the success and error class to every one. How can I get the error callback function to only throw if the AJAX response is 404?
$('li').each(function(){
$(this).children('a').each(function(){
$.ajax({
url:$(this).attr('src'),
success:$(this).addClass('success'),
error:$(this).addClass('error')
})
})
});
the success and error parameters expect functions.
You'd need to wrap the code in an anonymous function:
//there's no need to complicate things, use one call to each()
$('li > a').each(function () {
var $this;
$this = $(this); //retain a reference to the current link
$.ajax({
url:$(this).attr('href'), //be sure to check the right attribute
success: function () { //pass an anonymous callback function
$this.addClass('success');
},
error: function (jqXHR, status, er) {
//only set the error on 404
if (jqXHR.status === 404) {
$this.addClass('error');
}
//you could perform additional checking with different classes
//for other 400 and 500 level HTTP status codes.
}
});
});
Otherwise, you're just setting success to the return value of $(this).addClass('success');, which is just a jQuery collection.
First you need a success and failed handler, now the code just runs for every link.
You don't need the src attribute, but the href prop.
This should work:
$('li').each(function(){
$(this).children('a').each(function(){
$.ajax({
url:$(this).prop('href'),
success:function(){$(this).addClass('success')},
error:function(){$(this).addClass('error')}
})
})
});
I also find it more elegant to use index and value in the each loop, so:
$('li').each(function(){
$(this).children('a').each(function(index,value){
$.ajax({
url:$(value).prop('href'),
success:function(){$(value).addClass('success')},
error:function(){$(value).addClass('error')}
})
})
});
The other answers add the class for ALL errors, if you truly want it for a 404 only then this should do:
$(this).children('a').each(function(){
var self;
self = this; //retain a reference to this
$.ajax({
url:$(this).attr('src'),
success: function () { //pass an anonymous callback function
$(self).addClass('success');
},
statusCode: {
404: function() {
$this.addClass('error');
}
}
});
});
You need to wrap your success and error callbacks inside a function() call:
$('li').each(function(){
$(this).children('a').each(function(){
var $this = $(this);
$.ajax({
url:$this.attr('href'),
success: function() {
$this.addClass('success');
},
error: function() {
$this.addClass('error');
}
});
});
});

easiest confirm box plugin with jquery

My html code
<div id="delete">Delete</div>
My javascript code
$(function(){
$("#delete").click(function(){
var decision=decide("Do you really want to delete?");
});
});
function decide(str)
{
$("delete").after(str+'<button onclick="yes()">Yes</button><button onclick="no()">No</button>');
}
function yes(){return 1;}
function no(){return 0;}
Currently my yes and no are returning 0/1 but i want a return 0/1 from decide function depending upon no/yes.
Your code is asynchronous. You won't be able to assign it to your decision variable this way.
In other words: your decide function returns before the user clicks on any button, and will always return undefined.
Whatever you want to do with that Boolean, you'll have to do from within those yes/no functions.
Here's a quick sample of how to provide a callback:
$(function() {
$("#delete").click(function(){
decide("Do you really want to delete?", function(result) {
alert(result);
});
return false;
});
function decide(str, callback)
{
$('<div>'+str+'<button>Yes</button><button>No</button></div>')
.insertAfter("#delete")
.on('click', 'button', function() {
var result = $(this).text() == 'Yes' ? true : false;
console.log($(this).text(), result);
callback(result);
});
}
});​
Here's a demo: http://jsfiddle.net/x2Lf9/
Why not simple use a jquery plug in?
Try Impromptu
http://trentrichardson.com/Impromptu/

Categories