JQuery callback to previously defined function - javascript

I'm still learning JQuery (and as a result a little JavaScript) but I can't seem to find out how to use a previously defined function in a callback.
Say I have:
<script>
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
});
</script>
And I wish to use this in another function e.g:
<script>
$(document).ready(function() {
$.ajax({
beforeSend: ajax_start(),
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
});
</script>
Would this be correct? (I assume not as it doesn't...) what is the proper way of doing a callback?

Close.
$(document).ready(function() {
function ajax_start() {
alert("starting...");
}
$.ajax({
beforeSend: ajax_start, // <== remove the parens
url: "insert_part.php",
type:"POST",
data: "customer="+customer // <== as Skilldrick pointed out,
// remove the trailing comma as well
});
});
You need to do this because
ajax_start() evaluates to the value returned by executing the function named ajax_start, but
ajax_start evaluates to the function itself.
Edit re: OP comment
"how would I include a second function in the callback. Something like- beforesend: ajax_start,other_function (obv. not exactly like that)?"
There are a couple ways to do it. Combine them using an anonymous function:
$.ajax({
// if you need the arguments passed to the callback
beforeSend: function (xhr, settings) {
ajax_start();
other_function();
},
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});
Or just declare a named function that does what you want, and then use it:
function combined_function(xhr, settings) {
ajax_start();
other_function();
}
$.ajax({
beforeSend: combined_function,
url: "insert_part.php",
type:"POST",
data: "customer="+customer
});

Change the value of beforeSend to ajax_start. In other words, remove the parentheses.
With the parentheses, you're calling ajax_start() and setting beforeSend to the return value of ajax_start() (in this case, I believe that would be undefined).

just remove the parentheses, then you are referencing the 'function'-object. The () calls the function, so you would pass the return value of ajax_start.
$.ajax({
beforeSend: ajax_start,
url: "insert_part.php",
type:"POST",
data: "customer="+customer,
});
});

Related

Html Ajax button not doing anything

im sure this is something obvious but I cant figure it out
onclick of button retrieveScoreButton my button is simply not doing anything
any help is appreciated, im attempting to append the data to a table but cant even get it to register the clicking of the button so I cant test the function showsccore
<button id="addScoreButton">Add score</button>
<button id="retrieveScoreButton">Retrieve all scores</button>
<br>
<div id="Scores">
<ul id="scoresList">
</ul>
</div>
<script>
$(document).ready(function () {
$("#addScoreButton").click(function () {
$.ajax({
type: 'POST',
data: $('form').serialize(),
url: '/addScore',
success: added,
error: showError
}
);
}
);
});
$(document).ready(function () {
$("#retrieveScoreButton").click(function () {
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: alert("success"),
error: showError
}
);
}
);
});
function showScores(responseData) {
$.each(responseData.matches, function (scores) {
$("#scoresList").append("<li type='square'>" +
"Home Team " + matches.Home_Team +
"Away Team: " + matches.Away_Team +
"Home: " + scores.Home_Score +
"Away: " + scores.Away_Score
);
}
);
}
function showError() {
alert("failure");
}
</script>
</body>
</html>
There are a couple things wrong here:
console.log(id);
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: alert("success"),
error: showError
});
First, you never defined id. (After some comments on the question it turns out your browser console is telling you that.) What are you trying to log? You may as well just remove that line entirely.
Second, what are you expecting here?: success: alert("success") What's going to happen here is the alert() is going to execute immediately (before the AJAX call is even sent) and then the result of the alert (which is undefined) is going to be your success handler. You need a handler function to be invoked after the AJAX response, and that function can contain the alert.
Something like this:
$.ajax({
type: 'GET',
dataType: "json",
url: "/allScores",
success: function() { alert("success"); },
error: showError
});
(To illustrate the difference, compare your current success handler with your current error handler. One of them invokes the function with parentheses, the other does not. You don't want to invoke a handler function right away, you want to set it as the handler to be invoked later if/when that event occurs.)

Is there a way to save an ajax function/call so it can be reused?

I'm working on a web app using JavaScript and PHP and I'm finding myself re-coding the same ajax calls over and over again. Is there a way to save it as a function, with or without parameters, or even as a variable that can be used later?
Note: I'm still learning JavaScript as I go so I appreciate any tolerance for my ignorance.
For example, instead of this:
$("body").on("click", ".all-forms-link", function() {
$.ajax({
url: "forms.php",
type: "post",
data: {formsPage: 1},
success: function(data) {
stage.html(data)
}
});
});
//called several more times on different actions
Something like this:
function loadForms() {
$.ajax({
url: "forms.php",
type: "post",
data: {formsPage: 1},
success: function(data) {
stage.html(data)
}
});
}
body.on("click", ".all-forms-link", function() {
loadForms(); //or something similar
});
Sure. When you create a named function declaration, for example:
function foo(){
. . .
}
You may refer to that function by name anywhere a function is expected.
So, your code could be even simpler than what you showed with:
function loadForms() {
console.log("AJAX Call Initiated!");
$.ajax({
url: "forms.php",
type: "post",
data: {formsPage: 1},
success: function(data) {
stage.html(data)
}
});
}
// Just refer to your function's name (don't add parenthesis after
// the name though because we don't want to execute it with this line
// we only want to refer to it) where a function is expected.
$(document).on("click", ".all-forms-link", loadForms);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="all-forms-link">Click me</div>

"this.source is not a function" error while implementing autocomplete

$(document).ready(function(){
var var_name=null;
$('#id1').click(function(){
$.ajax({
type:"GET",
url:" ggs.erm.servlet.setup5.Page",
success:function(response){
var_name=response;
console.log(response);
}
})
});
$("#id").autocomplete({source:var_name});
});
This is the Code I am messing with,It says TypeError:this.source is not a function. Where I am wrong,Correct me???
jQuery Ajax methods are non-blocking, so it looks like you're trying to set an auto-complete source before the previous method resolves. You probably want to move the autocomplete assignment into the success method of your .ajax() call.
So, instead of what you have, use:
$.ajax({
type: "GET",
url: "ggs.erm.servlet.setup5.Page",
success: function(response) {
$("#id").autocomplete({ source: response });
}
});

jQuery pass parameters into function call from ajax success

I want to call a function when a jQuery Ajax request is successfull. I want to pass a parameter into a second function that apparently (it doesn't work) doesn't exist inside the jquery anonymous function.
Here is my Ajax function:
function core_get_title(url,id_of_link){
$.ajax({
type: "POST",
url: "url_handler.php",
data: {
url: url,
cmd: "get_title",
},
success: function(data) {
core_title_auto(data,id_of_link);
}
});
}
And when it calls core_title_auto, the id_of_link parameter is empty.
Any ideas?
check and see whats in id_of_link before ajax call by placing an alert function
function core_get_title(url,id_of_link){
alert("id_of_link"+id_of_link);
$.ajax({
/*...... your code */
});
}

Translating Prototype Ajax call into jQuery (adding form parameters and loading function)

I am trying to translate this on submit call into a identical call in jquery
onsubmit = "new Ajax.Updater('graph','/test/add', {asynchronous: true, evalScripts: true,
onLoading:function(request){document.getElementById('load').style.display='block'}, parameters:Form.serialize(this)});
So far I have this function:
$("form").submit(function(e){
$.ajax({
url: '/saffron_main/click_out_display',
success: function (data) {
$('#graph').html(data);
}
});
});
However, I am having trouble replicating two pieces of functionality.
parameters:Form.serialize(this)
onLoading:function(request){document.getElementById('load').style.display='block'}
$("form").submit(function(e){
$.ajax({
url: '/saffron_main/click_out_display',
data: $(this).serialize(),
success: function (data) {
$('#graph').html(data);
$("#load").css("display","block");
}
});
});
That should match your needs. If anything is unclear, don't hesistate to ask.

Categories