Is jQuery.ajax and $.ajax the same? - ajax

In tutorials can see jQuery.ajax and $.ajax
Like here http://www.thekludge.com/form-auto-save-with-jquery-serialize/
jQuery.ajax({
url: 'my_form.php',
And here http://www.yourinspirationweb.com/en/how-and-when-to-use-jquerys-serialize-method/
$.ajax({
url: 'elaboration.php',
Please advice is jQuery.ajax and $.ajax is the same?

In general they might be not the same.
$ can be used and overwritten by some other library that uses it as a global reference to itself.

According to the jQuery documentation,
a code example on that page is written as:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
$(this).addClass("done");
});
so yes, they should be the same.

jQuery.ajax and $.ajax are the same thing. The dollar sign is an alias for jQuery functions. In some cases, where other js files are using the dollar sign, it is necessary to use jQuery. Otherwise, the selector is ambiguous and errors will be thrown in the console.

Yes, they are the same. See the docs for details:
http://api.jquery.com/jQuery/
Some libraries such as prototype also use $ for their own purposes. jQuery can be put into noconflict mode to handle situations where you have another library on the same page that also uses $. In that case they would be different things.

Related

better way to use in AJAX requests? $.POST or $.AJAX?

I have seen many articles for making ajax requests..
most of them are using $.AJAX for jquery ajax posting and some of them are using $.POST for jquery ajax posting...
I want to know what is the best way if I want to post using ajax? which method makes the ajax request fast and in lightweight?
$.post is a shorthand way of using $.ajax for POST requests, so no difference.
$.ajax is generally better to use if you need some advanced configuration.
$.post is just shorthand for $.ajax({type: 'POST'}). It makes no difference to the speed or weight of the request, just changes the readability of your code.
$.post is just a shorthand for $.ajax({ type: 'POST' }) [see reference], so there is no acceptable performance improvement, but still a readability one.

CakePHP2.0 What is the correct way to access post variables in a CakePHP controller?

I am unsure as to how I access variables that I have posted using ajax in my controller. I though it might be something along the lines of:
$this->request->data['post']['varName'];
I don't think that is the correct way to access the variables I have posted as it doesn't seem to work, so my question is: "What is the correct way to access post variables in a CakePHP controller". For completeness I will include an example jQuery ajax call. If you could refer how to access the data with the example below that would be great
$.ajax({ type: "POST",
url: "someURL", // Not an actual URL just placeholder for example
data: {'foo': 5, 'bar': 12},
success: function()
{
alert('Post was successful');
}
});
So how would I access foo and bar in a cakePHP controller?
Also if you know where to find this information in the documentation could you please link me to it as I had a hard time finding the information.
Update!
Found the link to the documentation here.
Is $this->request-data['post']['varName']; a typo? If not, then you have a syntax error after the request property where you need a ->.
I think your problem could be solved by using this though:
echo $this->request->data['foo']; // Should print 5
echo $this->request->data['bar']; // Should print 12

Send ONE Javascript variable to PHP via AJAX

I've been looking around the forums without a solution to my problem. It's pretty simple, really, and I'd appreciate it if you could explain your answer if you would be so kind.
I'm new to AJAX and Javascript, and I need to send one variable from my javascript code and basically "convert" it into php. Here's what I have so far:
var selected = rowData.ID
jQuery.ajax({
url: "test.php",
type: 'POST',
data: { selected },
cache: false
});
I use this selected value further down in the code. I use PHP to display the (value of selected).
"vars": [
"(value of selected)"
],
However, I can't seem to make my ajax request work and send the variable to my PHP file. Here's what my PHP file looks like:
$row = $_POST["selected"];
Thanks in advance for the help.
try replacing your "data:" with this:
data: { 'selected': selected },
So this is very delayed answer, but I was having trouble getting a variable to send too. I'm not using php, but saw loads of examples like vlscanner gave, but who knows why it didn't work.
I stumbled across this explanation of how to send multiple parameters, and it works just as lovely for sending one parameter.
http://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods
multiple:
data: JSON.stringify({ Album: album, User: user, UserToken: userToken }),
or just one:
data: JSON.stringify({ Album: album}),
I'm no expert on timing,efficiency and all that, and it's possible that JSON.stringify adds unnecessary bulk and there is possibly some valid reason that sending data without the JSON.stringify didn't work. However, if you are in a bind and need something to work, this might help those of us still asking this question.
I'm suspecting that mine did not work because I was sending it to an asp method that likely requires the parameters to come as a JSON string. I have to research that next. Every step is a new discovery.

jQuery AJAX JSON dataType Conversion

Hopefully that title isn't too cryptic. What's happening is I have a jQuery AJAX script that I'm trying to use to access an API on a remote server, which returns a JSON response. However, the API returns the JSON as MIME type "text/html" (in the response header) instead of "application/json". It would seem obvious that I simply need to change the returned content type from text to JSON, to make the AJAX call interpret the data correctly.
Unfortunately, this is not the case. I have tried this in a multitude of different ways, all of which fail. The closest I've gotten to getting this API call to work is when the debugger tells me "Resource interpreted as Script but transferred with MIME type text/html". And the AJAX call errors out with my debug message that dumps the jqXHR object in JSON format, which tells me: {"readyState":4,"status":200,"statusText":"parsererror"}
Here is an example of my code (although I have changed the code many various ways, in my attempts at getting it to work, but this version seems to be the closest to correct):
$.ajax({
type: 'GET',
url: 'http://username:api-key#www.kanbanpad.com/api/v1/projects.json',
contentType: 'application/json',
dataType: 'jsonp',
converters: {
'jsonp': jQuery.parseJSON,
},
success: function(data) {
alert(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(JSON.stringify(jqXHR));
console.log(textStatus+': '+errorThrown);
}
});
If anyone can figure out what I need to do differently to make this work, I will be extremely grateful.
It may also be worth noting that if you copy/paste the API URL into a browser address bar and hit go, it gives the proper JSON response with the proper response header ("application/json")
So unless Kanbanpad updates their API, it cannot be directly accessed with JS. You will have to use PHP (or some other) to handle the requests.
It works just as well, it just requires an extra step is all.
Just for anyone that was looking for a solution.
dataFilter(data, type)Function
A function to be used to handle the raw response data of XMLHttpRequest.
This is a pre-filtering
function to sanitize the response. You should return the sanitized data. The function
accepts two arguments: The raw data returned from the server and the 'dataType' parameter.
I would change the content type in the dataFilter interceptor to json. Bear in mind this affects all ajax calls, so use info from data to decide which ones you want to convert.
Verify that your server is sending a jsonp response. This means the json should be enclosed with a string of your callback.
The callback name is passed in the parameters, and if you're not setting it explicitly, looks something like: jQuery15102810791094068532_1300988427891 (As per http://www.json-p.org/)
On your server, you need to format the response:
jQuery15102810791094068532_1300988427891({...json response ...});
Where you use the callback defined in your GET parameter 'callback'.
You might try setting the type to "json" and see if it works. I've had a number of parsererror's with the jquery's jsonp - you might try http://code.google.com/p/jquery-jsonp until it's a bit smoother.
Try changing your content-type to this
contentType: "application/json; charset=utf-8",

JQuery ajax calls not working in Firefox browser

I am trying to test Jquery ajax calls in Firefox but it it not working. I mean my server is not receiving any requests. But when I test in IE8 it works fine. Here is my ajax call:
$("#getWeatherReport").click(function(){
$cityName = "New York";
$.ajax({
type: "POST",
dataType:"xml",
url: "http://localhost:8080/Test/WeatherServlet",
data: "cityName="+$cityName,
success: function(data) {
alert($("report", data).text());
},
error: function(xhr, textStatus, errorThrown) {
alert('ERROR['+xhr.statusText+']');
}
});
});
It is not even calling error function. And from my server code(java) I am setting content type as "text/xml".
Any suggestions?
Your string is not correctly serialized, I'm not sure if that's the issue, but it may be and it's definitely a potential one for later, try this for an immediate test:
var $cityName = "New+York";
As a more permanent solution, pass data as an object, like this:
data: {cityName: $cityName},
Have you installed Firebug?
Your best bet would be to install Firebug, which comes with a console that'll notify you of any javascript errors. You can also use it (via the "Net" tab) to monitor all requests made by your page.
From what I can see, your code looks OK (other than the possible issue pointed out by #Nick Craver)
Also, why the '$' on your cityName variable? The '$' prefix in Javascript is meant to be reserved for machine-generated code (so that it has no chance of conflicting with user code).
try installing firebug plugin in ff :: https://addons.mozilla.org/en-US/firefox/addon/1843/
Then check the :::: Net Tab >> All selected
Refresh the page and see is your ajax call actually getting called. If yes is there any syntax error in the call or any variable null error. If all is fine then you can think of further issues
Usually, when I end up with a parseerror that means that the return header type is wrong or that somehow the server sent extra data with the response. For instance, if I'm looking to get JSON back and I get the JSON and some HTML from x-debug.
Also, The OPTIONS request is for cross-domain requests which is what #Nick was alluding to.
A helpful link to get you started.

Resources