.ajax() can send a post request and get data in return where as .load() can get any element in the rendered page. How to create a form when submitted(asynchromously) instead of getting back some data should get the page element of the rendered page that would be generated had there been normal submission instead of ajax submission?
I dont want to write views(Django) for xhr, normal requests separately. So, When I submit a form by ajax I dont want to hijack default action but only want to get some element of the rendered post submission page instead of actually being redirected to that post submission page which would have happened hadn't it been an xhr request.
Update:
load will do a POST rather than a GET if you supply the data to send as an object rather than a string. From the docs:
Request Method
The POST method is used if data is provided as an object; otherwise, GET is assumed.
So:
$("#target").load("/path/to/resource selector_for_relevant_elements", {});
..should convert the load from GET to POST. Of course, you'd replace {} with the arguments you want to send.
Original answer:
You can do the POST directly with ajax and then process the returned HTML yourself. For instance, to turn this load:
$("#target").load("/path/to/resource selector_for_relevant_elements");
..into a POST:
$.ajax({
url: "/path/to/resource",
method: "POST",
dataType: "html",
success: function(html) {
// Build the elemnts of the result in a disconnected document
var page = $("<div>").append(html); // See note below
// Find the relevant elements and put them in target
$("#target").html(page.find("selector_for_relevant_elements"));
}
});
I've done the wrapper div because that's what jQuery's load function does. You may want to look at the source for load (that line number will rot, of course, but the filename is unlikely to change) to see if there are other tricks you need to replicate.
Related
I have a form that loads some of its Data dynamically via Ajax, where, apart of a lot of other stuff, I fill a dropdown list. When selecting an item it will load the corresponding data into a table.
That all works fine, but now I want to be able to, by default, load the data of the first element once the page loads.
But since the dropdown populates over Ajax, it is filled slightly after $(document).ready(), so that doesn't work.
One way it might work would be to just wait for a second or two, since then it should all be loaded, but that really isn't something I fancy doing.
Any idea how I could achieve that?
I already tried it with onloadeddata="loadData($(this)[0].selectedOptions[0].value)" on the select tag, but that doesn't seem to do anything.
EDIT:
And I don't want to execute this in the ajax success function as data might also be loaded in other ways. It should really be the dropdown field or something that watches the dropdown, that executes this.
JQuery Ajax provides a callback for successful request.
$.ajax({
url : 'stackoverflow.com/api',
type: 'GET',
success : successMethod
})
function successMethod(){
// foo
}
Once the request receives a response successMethod will be called.
jquery ajax have a success function in which you can do such kind of functionality. To do so you can try:
success: function(response) {
// fill the form value with 'response'
$('#dropdown_id').val('any_value'); // this will set the dropdown to specific value
}
$.ajax({
url: "test.html",
...
}).done(function(data) {
// do something with your data in here
});
How to issue request
PUT /user/someuser1
and parse result in browser?
Note that AJAX solution in this answer https://stackoverflow.com/a/2153931/258483 does something different: it passes the answer to closure function, while I need synchronous solution, i.e. pass the answer to entire browser window.
Like the following code
location.href = '/user/someuser1';
does with GET request.
UPDATE
I did the following way:
<script type="text/javascript">
function execute2() {
url = '/user/' +$('#screenname2').val();
$.ajax({
url: url,
method: 'GET', // PUT
converters: {"text json": window.String}
}).done(
function(http) {
document.open();
document.write(http);
document.close();
window.history.pushState(null, "New User", url);
}
);
}
</script>
<p>PUT /user/<input type="text" value="someuser1" id="screenname2"> <input type="button" value="Go" onclick="execute2()"></p>
Used GET for test purposes.
Unfortunately, my service returns JSON and it displays differently than if I get it with location.href: in my case it shows as plain text, while if location.href it displays with indentation.
Also, I can't navigate back to initial page -- it changes address in address bar, but not shows the content of referrer page...
HTML doesn't provide any means to make a PUT request, only GET and POST.
The only way to make one is with JavaScript and XMLHttpRequest. Then the only way you can handle the response you get is to process it with JavaScript.
Therefore, the closest you can come is to:
Make the request with XHR
Use the callback to read the response
Replace the content of the current document with the content of the response using DOM
Update the URL using pushState
before we start apologies for the wording and lack of understanding - I am completely new to this.
I am hoping to run a php script using Ajax - I don't need to send any data to the php script, I simply need it to run on button press, after the script is run I need to refresh the body of the page. What I have so far:
HMTL Button with on click:
<font color = "white">Next Question</font>
JS Ajax call:
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'php',
success:function(content,code)
{
alert(code);
$('body').html(content);
}
});
}
this runs the php script but doesn't stay on the current page or refresh the body - has anyone got any ideas - apologies if this is completely wrong I'm learning - slowly.
Many thanks in advance.
**As a small edit - I don't want a user to navigate away from the page during the process
How about using load instead of the typical ajax function?
function AjaxCall() {
$(body).load('increment.php');
}
Additionally, if you were to use the ajax function, php is not a valid type. The type option specifies whether you are using GET or POST to post the request.
As far as the dataType option (which is what I think you mean), The Ajax doesn't care what technology the called process is using (like ASP or PHP), it only care about the format of the returned data, so appropriate types are html, json, etc...
Read More: http://api.jquery.com/jquery.ajax/
Furthermore, if you are replacing the entire body content, why don't you just refresh the page?
your ajax should be
function AjaxCall() {
$.ajax({
url:'increment.php',
type: 'post',
success:function(data)
{
console.log(data);
$('body').html(data);
}
});
}
if you want to learn ajax then you should refer this link
and if you just want to load that page then you can use .load() method as "Dutchie432" described.
If you are going to fire a javascript event in this way there are two ways to go about it and keep it from actually trying to follow the link:
<font color = "white">Next Question</font>
Note the return false;. This stops the following of the link. The other method would be:
<font color = "white">Next Question</font>
Note how this actually modifies the href to be a javascript call.
You can study about js and ajax here http://www.w3schools.com/ajax/default.asp will help a lot. Of course all js functions if called from internal js script should be inside <script></script> and if called from external you call the js gile like <script src"somejs.js"></script> and inside js there is no need for <script> tags again. Now all those function do not work by simply declaring them. So this:
function sayHello(){
alert("Happy coding");
}
doesn't work because it is just declared and not called into action. So in jQuery that you use after we declare some functions as the sayHello above we use:
jQuery(document).ready(function($){
sayHello();
});
Doing this we say that when everything is fully loaded so our DOM has its final shape then let the games begin, make some DOM manipulations etc
Above also you don't specify the type of your call meaning POST or GET. Those verbs are the alpha and omega of http requests. Typically we use GET to bring data like in your case here and POST to send some data for storage to the server. A very common GET request is this:
$.ajax({
type : 'GET',
url : someURL,
data : mydata, //optional if you want to send sth to the server like a user's id and get only that specific user's info
success : function(data) {
console.log("Ajax rocks");
},
error: function(){
console.log("Ajax failed");
}
});
Try this;
<script type="text/javascript">
function AjaxCall() {
window.location.reload();
}
</script>
<body>
<font color = "white">Next Question</font>
</body>
On one of my pages I have "tracking.php" that makes a request to another server, and if tracking is sucessful in Firebug Net panel I see the response trackingFinished();
Is there an easy way (built-in function) to accomplish something like this:
If ("tracking.php" responded "trackingFinished();") { *redirect*... }
Javascript? PHP? Anything?
The thing is, this "tracking.php" also creates browser and flash cookies (and then responds with trackingfinished(); when they're created). I had a JS that did something like this:
If ("MyCookie" is created) { *redirect*... }
It worked, but if you had MyCookie in your browser from before, it just redirected before "track.php" had the time to create new cookies, so old cookies didn't get overwritten (which I'm trying to accomplish) before the redirection...
The solution I have in mind is to redirect after trackingFinished(); was responded...
I think the better form in javascript to make request from one page to another, without leaving the first is with the ajax method, and this one jQuery make it so easy, you only have to use the ajax function, and pass a little parameters:
$.post(url, {parameter1: parameter1value, param2: param2value})
And you can concatenate some actions:
$.post().done(function(){}).fail(function(){})
And isntead of the ajax, you can use the $.post that is more easy, and use the done and fail method to evaluate the succes of the information recived
As mentioned above, AJAX is the best way to communicate between pages like this. Here's an example of an AJAX request to your track.php page. It uses the success function to see if track.php returned 'trackingFinished();'. If it did then it redirects the page 'redirect.php':
$.ajax({
url: "track.php",
dataType: "text",
success: function(data){
if(data === 'trackingFinished();'){
document.location = 'redirect.php';
}
}
});
The example uses JQuery.
Having trouble accessing javascript code in a mixed html/js ajax response. jQuery ajax doc states:
If html is specified, any embedded JavaScript inside the retrieved
data is executed before the HTML is returned as a string
Which I can confirm by adding a simple snippet to the html reply:
<script type="text/javascript"> alert($(this)); </script>
How then to retain access to the js code vs. one-and-done execution?? Trying to implement a modal login (to prevent data loss on session timeout in form submission screens). Of course I need to be able to access the ajax'd js code to then validate email/password fields and ajax authenticate user credentials on the remote server.
Here's the modal login coffeescript snippet:
# submit form
$.ajax
success: (data) -> ...
error: (data) ->
popAuth(data.responseText) if(data.status == 401)
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
title: title
})
Perhaps I can add a success callback to popAuth() ajax options to store the returned js code? How about jQuery "live" handler? Unfortunate that this scenario is not as straight forward as one would hope ;-) I have seen $.getScript as an option, but would prefer to not separate html from js since server-side already assembles html + js and the original ajax call pulls it all down in one go. (i.e. avoid creating a dedicated server-side controller to send back js file content bundle)
I am of course open to alternative solutions to workaround this issue. For example, I could store login fields and js login validation code on every screen (JVM CRUD application living behind WordPress front end so every screen is basically auth required) in a hidden div, and then pop the modal login window "locally", which I assume would get around the annoying one-and-done js execution of remote ajax content.
Anyway, Ideas appreciated! client-side is both wonderfully simple and...horribly complex ;-)
Ok, fending off the veritable deluge of responses, I'll take a stab myself.
As I understand it now, since mixed html/js content is one-and-done executed, we have one chance to capture ajax response js code and bind it to current scope.
First, in the original ajax call (i.e. form submit that returns a potential 401 not authorized status) set the context of the modal login's ajax setup to $(this), the currently executing scope that contains jquery validation and other shared js code needed for modal login ajax submit to work.
In my case, using fancybox, adding context param it now looks like:
popAuth = (title) ->
$.fancybox({
href: "/login"
ajax: { type: "GET" }
context: $(#)
title: title
})
Then, since the parent window contains the majority of needed javascript, the only requirement is to create a js file that binds modal login form button click event to validation and $.ajax submission.
# login.coffee
jQuery ->
$('#loginSubmit').click (e) ->
e.preventDefault()
isValid = $('#loginForm').validate().form()
if isValid
$('#spinner').show()
$.ajax
data: $('#loginForm').serialize()
success: (data) ->
$('#status').fadeOut()
location.href = '/foo'
error: (data) ->
$('#status > div').html( data.responseText )
$('#status').fadeIn()
complete: () ->
$('#spinner').hide()
Done, all good, works ;-)