jquery load vs ajax for form post submission - javascript

If all I want to do is submit a form to a PHP processor with POST data and get the result, is there any reason to use the ajax method over the jQuery load method?
Using Ajax requires a bunch of code versus something very simple on one line in jQuery like this:
$("#myDIV").load("myProcessor.php", {field1: target.value});
Hmmm, maybe this only works well with one field? Sorry, just getting back into JS.

$(element).load(...) will automatically insert the server response into the selected element as html (jQuery documentation for .load()). This might result in your server exposing information about the request directly to the user, which is probably not what you're looking to do.
$.ajax() also allows very fine control over what happens during the request. You can accurately intercept exceptions and produce a callback when the request finishes succesfully. These are all reasons to use $.ajax() over $(element).load(...). However, if your only concern is sending the data in the POST header and working with the response, then using $.post with a callback function will probably be the simplest approach. http://api.jquery.com/jQuery.post/

The .load method is is roughly equivalent to $.get(url, data,
success) (src).
The .get method is a shorthand Ajax
function (src).
For a simple ajax call, .load is appropriate. Use .ajax if you want to deal with specials parameters.
PS: If you don't want a fat framework like jQuery, look here : http://microjs.com/#ajax

From jQuery website about load
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data.
you can read difference between load ajax on StackOverflow.
But, load is not for submitting a form using post method. Both POST and GET are different methods and works differently, data submitted using GET method will be available in the $_GET array but not in the $_POST.

Related

I need to create a post in the webpage without refreshing the page using ajax

In my webpage, the user can write a post and the data the user enters is then stored in the database. I want that data to be Selected by a query and posted into the webpage but without the page being reloaded.
I am aware that I need to use Ajax, but I do not know how to use it. I need the post to be added to the page when the post button available in the webpage is clicked.
If you do not know how to use it, why not try to read up on it? :)
To give you a gist of what you need to do, the button needs to be tied to an event handler in Javascript/JQuery. That event handler will be responsible for making the AJAX call and retrieving the information from the server. The call would be something like:
$.ajax({type: 'GET', url: '/path/to/information'})
Calling .done() on this particular AJAX call will execute the callback function specified in the parameter. Usually it's done like so:
$.ajax(...).done(function(data) { ... });
Where data is the response data on a successful (200) response. Once you receive the data, you would just use Javascript to update the html/text of an element on the DOM. How you implement this is solely up to you, but I suggest reading up and trying to get it to work before asking!

Understanding the difference between semantics of AJAX vs post/get?

I am trying to understand what the term 'AJAX' actually implies. I do understand it stands for Async JAvascript over Xml.. And I understand that it doesn't necessarily require XML (we can use json for example). I understand that AJAX is a paradigm of updating only a partial web page without requiring a full post/refresh to the server.
What my question is one of semantics: if I create a web page with a button that when pushed will call jQuery.Get() to a server to refresh a page with partially - does this mean I am using AJAX?
Or, is AJAX very specifically a set of Microsoft objects / technologies?
Thank you for the clarification
Jquery .get() and .post() is both .ajax() wrappers and as names suggests, .get() is using type: "GET" and .post() is using type: "POST" in ajax call.
So yes, when using jQuery .get() and .post() you are using .ajax() simplified version. Also .ajax() is simple wrapper over JS XMLHttpRequest (as whole jQuery does).
So in the end you are using nothing more than JS.
If the user clicks a button and the browser makes a request and replaces the entire contents of the current page with another page, then that's not AJAX.
On the other hand, if the browser loads a page, and then submits subsequent HTTP requests triggered by events which then cause the page to alter content or design, then that is AJAX. It doesn't matter which browser.
AJAX uses XMLHttpRequest to send requests, and typically uses the response to do make a change on the page. jQuery.get() (and jQuery.post(), etc) is just a wrapper that makes AJAX a bit easier to use, and more consistent across different browsers.
See also:
how does an Ajax request differ from a normal browser request?
Yes. You are using AJAX. jQuery.get is shorthand for:
$.ajax({
url: url,
data: data,
success: success,
dataType: dataType
});
http://api.jquery.com/jquery.get/
AJAX is actually a terminology applied to the use of combined technologies such as HTML, Javascript, and specially the xmlHttpRequest object.
This one (xmlHttpRequest) is actually the core of AJAX methods, since it's a way of obtaining data from a URL without refreshing the whole page. Every AJAX call makes use of the xmlHttpRequest object.
It is not subject to JQuery. In fact, JQuery, as most frameworks, is intended to simplify javascript methods. When you use JQuery's $.ajax() or $.get() or even $.post(), it is actually, behind the scenes, instantiating the core xmlHttpRequest and performing the request.
This methods are just simplifiers so you won't have to deal with all the arguments and parameters of making a http async request...

what's the diffrence between $.ajax / $.get / $.POST / .load()?

I'm trying to understand AJAX and JSON and I'm not sure I get it, there are methods and functions that are doing the same stuff...
You've got $.getJSON to retrieve JSON format data from server, and you have $.ajax + $.post + $.get + load() to send data data to the server?
Can I use all of those methods to send JSON data?
Really I'm confused! Help me figure this out.
All those are just shorthands for calling the $.ajax function.
load is for retrieving HTML and writing it to the DOM in one go. You want to load JSON.
get and getJSON use GET requests which are not well-suited for sending JSON data.
post does a POST request, but doesn't allow you to choose the contentType of the sent data
For sending JSON you should use the $.ajax function with its many options, see Send JSON data with jQuery.
An AJAX request is, at heart, an HTTP request. This is the same protocol which is used for all content on the Web (arguably, if it's not HTTP, it's not the Web) - loading a page, the images on the page, the CSS and JS includes, a submitted form, etc, etc.
As such, it inherits pretty much all of the flexibility of HTTP, meaning a generic function like jQuery.ajax ends up quite complex, with lots of options you don't normally need to worry about. This leads to the Shorthand Methods you mentioned, which bundle up common sets of options and functionality.
Among the things you might want to vary:
The "method" of the request: GET or POST (or less common ones like HEAD, PUT, DELETE...). A GET request is the simplest: request this URL, give me its contents; parameters to a GET request are shoved onto the "query string" of the URL. A POST request is how larger forms would be submitted on a normal page: the parameters are passed as a body of data separate from the URL and control headers; for an AJAX request this is often helpful to send a block of XML or JSON to a URL. This is a very broad overview, and there are many more distinctions in behaviour and meaning between the two.
The "content type" you want in the response (and, for a POST request, of the data you're sending). Not only does this tell both the server and the browser what data it is handling, ensuring it will pass it successfully, it can give jQuery (or whatever library) a hint of what to do next: if a call returns XML, you'll probably want to manipulate it as a DOM straight away; if it's JSON, you'll want to parse it as a JS object.
What you want to do once the data comes back. I've already mentioned parsing JSON or XML, but what if your response is actually a block of HTML that you want to inject straight into the parent page? Obviously you could do that yourself in the callback function, but again jQuery includes a shorthand form in the shape of .load().
All of the above are possible with jQuery.ajax, but you'd have to remember the parameters, even though you're falling into the same cases again and again, so chances are most of the time you'll be using whichever of the shorthands suits your needs at that moment.

Internet explorer intercepts XML response

I have a form whose target is an iframe.
When submitting the form, the response is XML and I have Javascript that analyzes the response.
I noticed that when running on IE, IE intercepts the response and treats it as an RSS feed, so my code never receives the response. If I disable the RSS feeds (from the internet option, content tab) everything works ok.
I set the content type of the response to “text/xml; charset=UTF-8” but still it does not work.
Is there any workaround?
The best workaround would be not to use an iframe in this case. It sounds like IE is catching the http response and reading it on its own. Is there a reason you're not making an AJAX call to retrieve the information? It sounds like you're relying on JavaScript to handle the response anyway, so I would think that using an XMLHttpRequest object would be better for you: http://www.w3.org/TR/XMLHttpRequest/
If that's too complicated, look into a library like jQuery: http://jquery.com/ that has built in (and much simpler) functions to make AJAX calls and handle responses.
To expand on this, you would bind the submit function of the form to a JS function (or use jQuery to do it) and pick up the form data, send it in an AJAX request, and handle the response. jQuery has a built in function serialize() which is meant to convert form data on a page into information ready for use in the ajax() function to send to the server. If you're unfamiliar with the XMLHttpRequest object, I would highly suggest using a library like jQuery for this task.
OK, found the problem…
My response XML contains FEEDBACK tags.
IE treat these tags as RSS feeds. Changing the tag name to FDBACK resolve this issue…
MS, why this is not documented???
Yes, also make sure the file is output with the correct Content-Disposition using headers, do that IE gets "response.xml" and not "response.php" or some such...
'Content-Disposition: attachment; filename="response.xml"'

sending data to another website and receive result

If i have a website1.com and website2.com, can I send data ( ex: value from input ) from website2.com to website1.com and receive result? with no page refresh or redirect. I'd like to use only javascript & ajax, no PHP or jQuery. If it is possible give me an example how to do it.
I thought about creating an script element ( with javascript) on website2.com with src like : website1.com?data=<value from input>, and when script element loads the src, it will show me an result, but maybe there is a better option to do this.
PS: I will have more separated datas to send.
Note: this is not XSS, just a public project for websites, which will need to update datas every x minutes and to send some data to website1.
Thanks.
Your question is not completely clear, but in general when you have to do cross-site AJAX you have to use JSONP
Since XmlHttpRequest does not work cross-domain, you have to use JSONP. Basically, this is adding a script tag dynamically as you're suggesting to do. Then, the server uses your GET datas, does whatever it wants, and usually "prints" a callback function.
When you call a file using the script tag, it will evaluate everything displayed. This is why, if, on the server side, you're doing :
<?php
echo 'alert(1);';
?>
This will be evaluated as javascript. You can then easily understand how to use a callback function (another GET parameter).
Also, in jQuery, there is an option called 'jsonp' when you call $.ajax (using "callback" as default GET parameter, but can be changed).
You could have some XSS issues but it is possible you could use ajaxgold. It is an pretty easy manner to send pretty much everything over.
Call send to website2
postDataReturnText( 'http://website2.com', 'data=bla', getResult );
Return the result
function getResult( text ) {}

Categories

Resources