Is there any method in jquery like $.post , $.ajax etc which works like a normal form submission. I know about .submit() but it requires a form element , can we send a normal request without a form element in jquery?
You can submit without a form using $.ajax(). Further, to make it behave like a normal form would, set the async property to false.
$.ajax({
url: "/controller/action",
data: {'foo':'bar'},
async: false
});
This will result in you being sent to:
"/controller/action?foo=bar"
window.location.href = '/controller/action?foo=bar';
You are not clear on what you want to achieve. From what I understand, I'd suppose you want to send a GET or POST (form-submit-like) request to the server and make it seem like a real one.
In that case you would:
Create a XMLHTTPRequest with appropriate parameters.
Make it synchronous.
With the response, overwrite the DOM.
Not entirely clear what you are after, however you can use jQuery's serialize (docs) to pass a collection of values from input not in a form or any other items. You would still need to post the data in some manner however.
Related
im using alot of $.ajax calls in my website that im working on and it seems to be slow and lagging at some points. Is there any faster way to retrieve data other than using the $.ajax ?
$.ajax({
type: 'POST',
url: path + 'helper/general/general.php',
data: {pass:pass},
success: function(data){
if(data == 'correct'){
$.ajax({
type: 'POST',
url: path + 'helper/process/ClassesProcess.php',
data: {classID: classID}
});
}else{
$('.feedback').html(wrong_password).slideDown();
}
}
});
Ways in which I think you could optimise this are:
Use === instead of == in an if statement, this way it will check the type before the value.
Instead of doing an ajax call with in an ajax call, surely your first call should do all the logic (try to avoid having logic in your front-end)
Instead of returning strings or html from your ajax calls, return JSON if you can... however be wary of using json_encode/json_decode in php as they seem to be two slow functions.
If the user is refreshing the page, they don't need to redownload the content for a lot of your ajax calls, if the data hasen't changed since that user's last request, return a 304 with no data instead of returning a 200 with the data. This will make the browser get the previous response from it's cache.
Avoid declaring a function where there should be a callback, instead, put the name of a pre-existing function, this will stop the function being reinitialised every time you execute you ajax method.
Finally, when using jQuery, try to target elements by id instead of class, jQuery finds the element a lot faster this way as ids should be unique in a webpage.
Here's the thing: I have an array which I must send to another page... not using an AJAX request. I'm trying to redirect my user to this new page, or maybe to open a popup with the new page, but this new page must receive the array data on a POST request.
How do I do this in javascript? I have no problem JSON encoding my array before sending it, I just don't know how to redirect my user to a new page with the data "attached", in javascript.
I'm using ExtJS4, so if there's anything on Ext.util, I have no problem using it.
Thanks.
You can do this (using javascript)
make a new FORM
set the action as the new page
set the method as POST
add a hidden field
set the value of the field to this Value you want to send
Pragmatically submit the form
You can Ajax POST to the target page's url:
Ext.Ajax.request({
url:'/target/url/', async:false, method:'POST',
jsonData: {
jsonArray: yourJsonArray
}
success: function() {
console.log('posted successfully');
}
});
async:false loses the asynchronous functionality; simply remove it if you don't need your POST to be synchronous.
I'm creating frontend upload for an app with appengine backend.
What I want to make is a file upload solution, and I dont want to be using plupload or those kinds of ready-made solutions.
I basically submitted the images to an iframe and then put a cover while it is uploading. Then after it finishes I performed an ajax call to get the image ids for the next view to be rendered. However, the render is always called before the upload is completed, thus I'm not getting any image ids from the backend. can anyonehelp?
here's my code for the upload
perform_input3:(event)=>
event.preventDefault()
$('#product-input-3').hide()
$('#product-input-3').submit()
$('#upload-cover').show()
item_id = $('#item3_id').val()
app.views.imageselect.render(item_id)
the app.views.imageselect.render(item_id) is below:
render:(data)=>
#item_id = data
item_id = #item_id
$.ajax(
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success:(data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
return #
)
I dont want to be using setTimeout function since it will not be flexible depending on the connection speed. Any help will be appreciated :)
Essentially, your question boils down to this: You want to wait to make your Ajax call to the server until the data you're requesting is available. Getting notifications from the server is tricky (depending on how your backend is implemented), so the best solution to your problem is probably to just make the Ajax call periodically (say, once per second) until you get a successful response from the server.
Here's some code that should do that:
do ajaxCall = =>
$.ajax
url: '/get_image_list/'
type: 'GET'
dataType: 'json'
data: {item_id: item_id}
success: (data) =>
#payload = data
$(#el).append imageSelectTemplate(#payload)
error: ->
setTimeout ajaxCall, 1000
If you are only targeting modern browsers, then XHR2's FormData can enable a very simple and elegant approach.
The concept is:
add file(s) binary data to a FormData object
make a $.ajax() call with the FormData object as the AJAX call's "data" parameter
when upload is done, the $.ajax()'s success() or complete() callbacks will be triggered
This approach works with the latest Firefox, Chrome, Safari - http://caniuse.com/xhr2.
See this post for details: Sending multipart/formdata with jQuery.ajax
What you're missing is some sort of callback from the $('#product-input-3').submit() call. I think the following would work (pardon my bad CoffeeScript):
perform_input3:(event)=>
event.preventDefault()
item_id = $('#item3_id').val()
$('#product-input-3').hide()
$('#upload-cover').show()
$('#product-input-3').submit()
$('#target-iframe').ready ->
app.views.imageselect.render(item_id)
This is predicated on the idea that calling 'submit' immediately puts the target iframe into non-ready state, which seems reasonable, but I'd test it. Once it finishes loading The other option I've seen around is to have the page the iframe loads call back into its parent (top-level) window. In JS, something like:
parent.imageUploaded()
Or, if you want to use bound events:
parent.$(parent.document).trigger('upload-complete')
Where, of course, you've set up an upload-complete event on the top-level document object.
So I'm using this plugin: jquery-in-place-editor, I'm trying to make a POST request according to the docs, but I'm not sure what URL to do the POST to, I can't seem to get it right.
If I'm in the show view for the object, which in this case the path is: /quote_line_items/90
But when the script executes I get this error: No action responded to 90. Actions: create, destroy, edit, index, new, show, and update
Which URL would I want to put in the scripts url: parameter?
Update
I just tried this.
$(".editable").editInPlace({
url: "/quote_line_items/update",
show_buttons: true
});
And I also tried:
$(".editable").editInPlace({
url: "/quote_line_items/update/90",
show_buttons: true
});
just to see what would happen, however, after the form is submitted it shows the show action for that page in an Iframe where the form was, which makes sense I suppose, like it did a GET request or something.
You probably want to do a post with _method as a parameter having the value update that is if you are doing restful routes.
Otherwise I would point to /quote_line_items/update with a post.
It looks like you moved on, but I do have an answer for you.
If quote_line_items is a map.resources, then what you want is a PUT to /quote_line_items/:id
jquery-edit-in-place does a post, but what you want is a put, which you can fake with the _method attribute, so try this url: '/quote_line_items/90?_method=put'
Does anyone know what is the difference between $("#id").load and $.ajax?
Let me clarify things for you a little bit :
$.ajax() is the basic and low-level ajax function jQuery provides which means you can do what ever you want to like you can work with XmlHttpRequest object. But once upon a time jQuery Developers thought that actually besides $.ajax(), they could provide more specific methods to developers so they wouldn't need to pass more parameters to make $.ajax() method work the way they want. For example they said instead of passing json as a parameter to $.ajax() to indicate return data type, they provided $.getJSON() so we would all know that the return type we expected was json, or instead of indicating send method as post or get, you could use $.post() or $.get() respectively.
So load() is the same thing, it can help you inject html data into your html. with load() method you know that an html portion is being expected.
Isn't that cool ?
I think I've been fallen in love.
For more information, you can visit jquery.com, they are even providing their new library and api tutorial page.
Edit :
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
is the same as below :
$.post("some.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
Now as you can see it is the simplified version of $.ajax(), to make post call, you need to pass some information of send method type which is post as shown at the first example but instead of doing this you can use $.post() because you know what you are doing is post so this version is more simplified and easy to work on.
But don't forget something. Except for load(), all other ajax methods return XHR (XmlHttpRequest instance) so you can treat them as if you were working with XmlHttpRequest, actually you are working with it tho :) and but load() returns jQuery which means :
$("#objectID").load("test.php", { 'choices[]': ["Jon", "Susan"] } );
in the example above, you can easly inject the return html into #objectID element. Isn't it cool ? If it wasn't returning jQuery, you should have been working with callback function where you probably get the result out of like data object and inject it manually into the html element you want. So it would be hassle but with $.load() method, it is really simplified in jQuery.
$("#feeds").load("feeds.php", {limit: 25}, function(){
alert("The last 25 entries in the feed have been loaded");
});
You can even post parameters, so according to those parameters you can do some work at server-side and send html portion back to the client and your cute jQuery code takes it and inject it into #feeds html element in the example right above.
load() initiates an Ajax request to retrieve HTML that, when returned, is set to the given selector.
All the jQuery Ajax functions are simply wrappers for $.ajax() so:
$("#id").load(...);
is probably equivalent to:
$.ajax({
url: "...",
dataType: "html",
success: function(data) {
$("#id").html(data);
}
});
A more concise summary and the most important difference is that $.ajax allows you to set content-type and datatype.
These two are important for making JSON requests, or XML requests. ASP.NET is more fussy with a missing content-type field (atleast when you use [WebMethod]) and will simply return the HTML of the page instead of JSON.
$.load() is intended to simply return straight HTML. $.ajax also gives you
caching
error handling
filtering of data
password
plus others.
From the documentation ...
$(selector).load(..)
Load HTML from a remote file and inject it into the DOM.
$.ajax(...)
Load a remote page using an HTTP request. This is jQuery's low-level AJAX implementation.
load is specifically for fetching (via GET unless parameters are provided, then POST is used) an HTML page and directly inserting it into the selected nodes (those selected by the $(selector) portion of $(selector).load(...).
$.ajax(...) is a more general method that allows you to make GET and POST requests, and does nothing specific with the response.
I encourage you to read the documentation.
Here's the source code for the load function: http://github.com/jquery/jquery/blob/master/src/ajax.js#L15
As you can see, it's a $ajax with some options handling. In other words, a convenience method.
The above answer may not be valid anymore in light of the use of deferred and promise objects. I believe that with .ajax you can use .when but you cannot do so with .load. In short, I believe that .ajax is more powerful than .load. For example:
some_promise = $.ajax({....});
.when(some_promise).done(function(){.... });
You get more granular control over the html loading. There is also .fail and .always for failure and "no matter what" cases. You don't get this in load. Hope I am correct on this.