Why Does An AJAX Request Have To Have This? - ajax

<script type="text/javascript">
$(document).ready(function() {
$("button").click(function(){
$.ajax({
type: 'POST',
url: 'script.php',
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
});
</script>
why does an AJAX request have to have a placeholder for the function? (in this case it is 'data'). If you remove it, or use any other word it still works fine. Can someone please explain why?

Your data here is an alias for returned value (the "answer" for your ajax request to script.php), so you can reefer to it. It is NOT the placeholder for function itself.
How you name it is up to you - just like with names of lambda parameters in c++ (I find them similar to JavaScript anonymous functions in that case):
[](string data){
... = data...
}
or with "out" parameters of functions/methods in other languages.
For the C++ analogy: how it would look to pass an lambda as a parameter to another method (you would have to define the Button class of course):
button.click(/*...,*/ [&](string data){ //"on success"
MessageBox(NULL, data.c_str(), "Alert", NULL);
...
});

Related

this.IsMounted() is not a function

I'm trying to build a simple React App. It retrieves data from an ajax call and renders it to the page. The issue I'm having it setting the state of this.props after the ajax call. I'm receiving this error:
Uncaught TypeError: this.isMounted is not a function
I've been going through tutorials and looking at some example code, like this page on loading information through ajax on the react site https://facebook.github.io/react/tips/initial-ajax.html, but I don't see what would be causing this error. Here's my code:
var ANiceReminderApp = React.createClass({
getInitialState: function(){
return {
quotes: []
};
},
componentDidMount: function(){
$.ajax({
headers: { 'X-Mashape-Key':'xxxxxx'},
url: 'https://healthruwords.p.mashape.com/v1/quotes/',
type: 'GET',
dataType: 'JSON',
success: function(data){
var quote = data[0].media;
if(this.isMounted()){
this.setState({
quotes: quote
});
}
}
});
},
render: function() {
return (
<div className="container">
hello world
<img src={this.state.quotes}/>
<button>Need more inspiration?</button>
</div>
);
}
});
React.render(<ANiceReminderApp />, document.body);
Thanks in advance!
In event handlers, this refers to the object that raised the event. In your case, that would be the jqXHR object, which indeed lacks the .isMounted() method.
To deal with this situation you need to either keep a reference to the outer this and use that reference within the event handler, or use function.bind() to force the function to retain the outer context.
Here is an example of how to do the latter method:
$.ajax({
...
success: function(data) {
var quote = data[0].media;
if (this.isMounted()){
this.setState({
quotes: quote
});
}
}.bind(this); // Note the use of .bind(this) here
});
#gilly3's answer explains the issue. However, I prefer a different solution: React will efficiently auto-bind class methods, meaning that this will refer properly to the instance. So I generally use methods as callbacks:
React.createClass({
componentDidMount: function(){
$.ajax({
// the method is already bound to the component
success: this.onDataReceived
});
},
onDataReceived: function(data) {
var quote = data[0].media;
if(this.isMounted()){
this.setState({
quotes: quote
});
}
},
// ...
});
This has a couple of advantages:
In theory at least, React's binding is more efficient than using .bind. This is particularly true if you'd have to call .bind repeatedly for multiple calls.
It makes the callback more easily testable on its own.
It makes it easier to invoke the callback logic through some other code path (e.g. if you also want to accept data provided via props).
It's also worth seeing this discussion, which suggests that isMounted may be deprecated in the future - the suggested path in this case is to save a reference to the AJAX request and abort it on componentWillUnmount.

Using jQuery AJAX to Invoke Rails Server Method on Client Side

I am using Ruby on Rails, and I want to invoke a controller method as an onclick event of my pre-existing links.
I am using jQuery and AJAX to do the same. But I don't know much about AJAX.
Here is my code.
<script type="text/javascript">
$("a.browse_history").live("click", function()
{
alert("i am here");
$.ajax({
url: "/user_profile_controller.rb/save_user_history",
type: 'PUT'
});
});
</script>
In user_profile_controller.rb:
def save_user_history
$doc_list << "hello hi"
end
And my link is:
Click here
But this is not working..
Any solutions would be appreciated.
Your URL looks wrong. Run rake routes to get a list of existing routes in your app.
Should be something like
url: "/user_profile/save_user_history"
or
url: "/user_profiles/save_user_history"
Thank you for your reply Stefan.
I changed my code like this:
<script type="text/javascript">
function u_profile(user,url,query)
{
$.ajax({
type: 'POST' ,
url: "http://localhost:3000/user_profiles",
data : {
user_profile : {
user_id : user ,
query_term : query,
visited_url: url
}
} ,
success: function(data){
alert(data);
}
});
};
</script>
And i am invoking it as onclick event of link.
It full fills my requirement of creating an object in database with passed data.

jquery bind functions and triggers after ajax call

function bindALLFunctions() {
..all triggers functions related go here
};
$.ajax({
type: 'POST',
url: myURL,
data: { thisParamIdNo: thisIdNo },
success: function(data){
$(".incContainer").html(data);
bindALLFunctions();
},
dataType: 'html'
});
I am new to ajax and JQuery.
I have the above ajax call in my js-jquery code. bindALLFunctions(); is used to re-call all the triggers and functions after the ajax call. It works all fine and good as expected. However, I have read somewhere that is better to load something after the initial action is finished, so I have tried to add/edit the following two without any success.
Any ideas?
1) -> $(".incContainer").html(data, function(){
bindALLFunctions();
});
2) -> $(".incContainer").html(data).bindALLFunctions();
Perhaps you should have a look to the live and delegate functions. You can set a unique event handler at the beggining of your app and all your loaded ajax code will be automatically binded:
$("table").delegate("td", "hover", function(){
$(this).toggleClass("hover");
});
But if you prefer to use Jquery.ajax call you have to do something like this:
$.ajax({
type: 'POST',
url: myURL,
data: { thisParamIdNo: thisIdNo },
success: function(data){
$(".incContainer").html(data);
bindALLFunctions(".incContainer");
},
dataType: 'html'
});
and transform bindALLFunctions as:
function bindALLFunctions(selector) {
..all triggers functions related go here. Example:
$('#foo', selector).bind('click', function() {
alert('User clicked on "foo."');
});
};
that will only bind events "under" the given selector.
Your initial code was fine. The new version does not work because html() function does not have a callback function.
It's hard to tell from your question just what you intend to ask, but my guess is that you want to know about the ready function. It would let you call your bindALLFunctions after the document was available; just do $(document).ready(bindALLFunctions) or $(document).ready(function() { bindALLFunctions(); }).

What does `success: function(msg)` mean in my jQuery Ajax call?

I have two jQuery Ajax calls that I'm combining on a page. I'm stuck on the success: function() in each, as one is success: function(msg) and the other is success: function(data). I'm unsure of what both of these mean, and what they should be in the combined code. I'll place the two calls below, separately, and combined as I have them thus far.
Ajax Request #1: there is a $msg .= "<div class='pagination'><ul>"; on this functions php page. Not sure if that is what this is referring to.
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: "page="+page,
success: function(msg)
{
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(msg);
});
}
});
Ajax Request #2: As far as I can see, there is no data anywhere on this call's php file. Don't know what function(data) is referring to.
$.get("new_arrivals_data.php",{imgs: value}, function(data){
$("#gallery_container").html(data);
});
Combined Request: I have put a ? where msg was in the original call as I'm unsure what to put in it's spot.
$.ajax
({
type: "GET",
url: "new_arrivals_data.php",
data: {page:page, imgs: value},
success: function(?)
{
$("#gallery_container").ajaxComplete(function(event, request, settings)
{
gallery_show();
loading_hide();
$("#gallery_container").html(?);
});
}
});
msg and data are simply the names of the formal parameters. You use those to refer to the response data that is passed to that function when it is invoked.
You can rename it to any valid JavaScript identifier.
Although there isn't really any reason to call ajaxComplete inside the success: callback:
success: function( whatever_you_want_to_call_it ) {
gallery_show();
loading_hide();
$("#gallery_container").html( whatever_you_want_to_call_it );
}
$.get("new_arrivals_data.php",{imgs: value}, function( i_like_ice_cream ){
$("#gallery_container").html( i_like_ice_cream );
});
Remember, in both cases, you're passing a function as an argument. That function is invoked when the response is received.
Whatever code is invoking that function, is also passing the response into that function as the first argument so that you have access to it. That's why you defined the parameter.
It's very similar to declaring a variable in a function.
$.get("new_arrivals_data.php",{imgs: value}, function(){
var i_like_ice_cream = arguments[0];
$("#gallery_container").html( i_like_ice_cream );
});
This does almost the same thing. You've associated a variable with the first argument passed into your callback function.
It can be any valid variable name. Either data or msg will work, just as long as you use the same one within the scope of that function.
To explain, you are setting success to an anonymous function, pretty much just a function with no name. So when jQuery dispatches the success event, it calls the function that you have given it when creating the ajax request. It also passes in some arguments into that function (in this case, the resulting data from the ajax request). What you are defining is what that incoming information should be called in the scope of this new function.
Take the following code for example:
function workOnBob(aWorker) {
aWorker("Bob")
}
var sayHi = function(name) { alert("Hello " + name); };
var getMarried = function(groom) { alert(groom + " is getting married!"); };
workOnBob(sayHi); // "Hello Bob"
workOnBob(getMarried); // "Bob is getting married!"
You can see that workOnBob is a function, and it should be passed an anonymous function. It invokes that function with the string "Bob". Also, notice the anonymous functions, sayHi and getMarried, have named the arguments they receive differently within their own scope (name and groom respectively). They both get the string "Bob", but they both choose to call it something different.
Anonymous functions and closures can be confusing, but once you get the hang of them, they are a lot of fun.
It just a name for the variable containing the response data returned from the ajax call. Name it whatever makes the most sense to the context, to make your code more readable, e.g. html, resp, logged.

What's needed here for the ajax server response to be executed as-is in the jQuery ajax post function?

The jQuery function below returns this string:
'#prayer_date'.html("03/19/1968");
But it doesn't get executed because the function below doesn't act on the data variable.
What would you need to do to have the result above executed as-is in the function below?
$('.showprayer').click( function(event)
{
$.post('/show_prayer', { 'name' : $(this).text() }, function(data)
{
// how to execute the `data` server response as-is?
});
});
Your response would need to be valid script first, like this:
$('#prayer_date').html("03/19/1968");
Then in your function you can call eval(), like this:
$('.showprayer').click( function(event) {
$.post('/show_prayer', { 'name' : $(this).text() }, function(data) {
eval(data);
});
});
....but this is almost never a good solution, there's probably a better/more direct route to do what you're after. A slightly better/safer solution is to use the expanded $.ajax() form for a global eval, like this:
$('.showprayer').click( function(event) {
$.ajax({
url: '/show_prayer',
type: 'POST',
data { 'name' : $(this).text() },
dataType: 'script'
});
});
The difference is that this uses jQuery.globalEval() which sticks the script in the <head> as if it were a normal GET requested <script>, instead of actually calling eval() on it.

Resources