This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery AJAX submit form
I have a form on a page A, and instead of me posting to a new page, is there a way that i can do onSubmit ajax request it instead? I want to make the page to be able to load in the result into a div.
I know how to write the script for the call sort of, but i wasn't sure if i had to hand write it or it if was possible to take all the form information and send it without having to code it all into the attributes. i was thinking I could just do some sort of thing like: onClick, post form but return results into a div.
Thoughts? Ideas?
Try using JQuery's serialize (API ref here)
EDIT: something like this:
$("input.submit").click( function() {
$.ajax( {
type: "POST",
url: $("form").attr( 'action' ),
data: $("form").serialize(),
success: function( response ) {
//Code to process the response
}
});
return false;
} );
$.ajax({
url: 'mypage.html',
success: function(data){
$('.result').html(data);
},
error: function(){
alert('failure');
}
});
Then you have a div:
<div class="result"> </div>
This will automatically populate with the result of your ajax post.
http://api.jquery.com/jQuery.post/
Also see TONS of related questions: Jquery checking success of ajax post
Related
I have a form, running through jquery validation which then submits via ajax to a PHP script to handle backend functions. Ajax collects form values through serializeArray() and looks to do the job. Script fires and data is sent through(I think) to PHP. I've tried probably close to 100 combinations to receive the data at the PHP side but with no luck. I'm convinced this must be simple, something I've overlooked. Code for the ajax is below, along with a screenshot of developer tools showing what's being sent.
No matter what I try on the PHP side, I either get an empty array, NULL through $_POST/$_GET. I've tried json_decode, parsing the string, var_dump etc.
var data=$(form).serializeArray();
$.ajax({
cache: false,
type: "POST",
dataType: "JSON",
url: "process/create_site.php",
data: data,
success: function(response) {
console.log(response);
//$(form).html("<div id='message'></div>");
//$('#message').html("<h2>Your request is on the way!</h2>")
// .append("<p>someone</p>")
// .hide()
// .fadeIn(1500, function() {
// $('#message').append("<img id='checkmark' src='images/ok.png' />");
// });
}
});
I managed to get to the bottom of this, after an embarrassing amount of time. I'd like to post the simple reason here to help others.
The entire JS block was wrapped in $(document).ready(function(){
which was causing the values to be stripped when posting to the PHP.
I can't find any documentation or answer to a question with a similar scenario - so here it is!
Ive been checking out how to add variables to a ajax request which I can use in my server side script. I checked this stackoverflow post here and checked the jquery api docs here for a ajax request. I am getting error variable in my code is not defined.
I have this line in my code
return $.ajax({
type: 'GET',
url: '/users/show',
data: {'currentusershow': variable},
});
I was wanting it to do something like this with the results so I can keep all my different script in the one file.
if ($.get("currentusershow")) {
// do something here
}
else if...
i am not sure how to add the value to my code?
Also my url does not work going to the show.js.erb where my code is kept.
You need to declare and assign some value to the variable before the request.
Also you need to change the method type from GET to POST.
var variable = 'some data';
/*$.ajax({
type: 'POST',
url: '/users/show',
data: {currentusershow: variable},
success: function (response) {
// Do something with respsone
},
error: function () {
alert("error");
}
});*/
$.get( "/users/show", {currentusershow: variable} )
.done(function( response ) {
//do something with the response here.
});
Mamun was kind of right here as I did not explain myself very well in my question but I thought I would post this and clarify my question with what I was trying to do. The ajax call should be
return $.ajax({
type: 'GET',
url: '/users/show',
data: { currentusershow: 'variable'},
});
where the key is currentusershow and the value variable is a string and leave out defining the variable else where in the code. That way the url comes through correctly to the server being /users/show?currentusershow=variable. And in my destination file add my ruby code there to use the variables. In my question that code was more a php type code as I did not know what I was doing at the time.
This question already has answers here:
how to reload DIV content without refreshing whole page
(8 answers)
Closed 9 years ago.
I want to load new content from the server to the DIV without refreshing the whole page.
I tried the following
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData +"&relationship="+ forData +"#",
success: function (response) {
$("#testDIV").html(response);
}
});
But the problem is the whole page is loading in <DIV id="testDIV">. I want to replace the old DIV with New DIV content returned from the server not with the whole page.
You can keep your same process sense you are interested in using AJAX directly and want to manage your done function (instead of success because .done() will replace it). Here is how...
.done(function(data) {
...
}
Inside of that done function, you can filter the page content to what you want. Simply request what you want to filter with jquery like this...
var $response = $(data);
var response_title = $response.filter(".title").html(); //I'm assuming you are trying to pull just the title (perhaps an < h1 > tag, in this little example, from the entire external page!
THEN!...
$("#testDIV").html(response_title);
With the done function, based on jQuery's API, you can use this format...
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
So your final code may look something like this...
$.ajax({
type: "GET",
url: "ht.tp://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+ occasionData +"&relationship="+ forData +"#"})
.done(function(response) {
var $response = $(response);
var response_title = $response.filter(".title").html();
$("#testDIV").html(response_title);
});
I like the answer by blackhawk. It uses the existing code with slight modification.
I would just condense it to a one line change like this:
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData+"&relationship="+ forData +"#",
success: function (response) {
$("testDIV").html($(data).filter(".title").html());
}
});
The code you are displaying is actually correct.
The problem comes from what your server is providing.
What you are doing here is GETing a whole page via an AJAX call, and replacing the content of One div with that whole page.
Your server should not render the whole page for that call, but only the content of the div you wish to replace. If you are using framework like rails or symfony, they often provide an easy way to detect if the query is a normal GET request, or an AJAX call.
Basically you have 4 strategies at your disposal :
Make the requests to a specific endpoint that is used only for the ajax call and that returns the content of the div you wish to replace. And not the whole page.
Make the request to the same page, and detect if the request is a normal HTTP request or an AJAX call. Based on that, return the whole page or just the content of the div. You'll probably have to look for the helpers in your framework / toolbox documentation.
Make the AJAX request but ask for a JSON object. Transform your JSON in HTML on the client side to replace the content of the div. This is the "my app is just an API" approach. This is my personal favorite as this JSON endpoint can be used for other purposes (eg: a mobile app) since it carries only content, and not presentation. This also tends to be the fastest way in terms of performance since a significant part of the computation is done on the client side. On the con side, this requires you to write more JS.
Always render the whole page, and filter only what you need on the client side. This is balchawk approach. Benefit is that you don't have to modify your server, but you will waste processing time and bandwidth by returning a whole page, when only a subset is necessary.
$(function(){
$('.classloader.').on('click', function(e){
$.ajax({
type: "GET",
url: "http://127.0.0.1:8000/result/?age="+ ageData +"&occasion="+
occasionData +"&relationship="+ forData +"#",
beforeSend: function() {
$("#testDIV").hide();
$('div#loading').show();
},
success: function(html){
$("#testDIV").html($(html).filter("#mainContent").html()).show();
$('div#loading').hide();
}
});
return false;
});
})
I'm using a javascript shopping cart on a store, and I want to send an order confirmation on checkout. The problem is that the cart isn't saved in database of any kind, and is printed with javascript. How would I attach it to the email? I've included the shopping cart script on the page that sends the mail.
<table class="simpleCart_items"></table> would print the cart, but how would I attach the printed cart to email?
Hidden input or something?
UPDATE
My ajax call looks like this:
var data = $('#yhteystiedot').serialize();
data.cartContent = $('.simpleCart_items').html();
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "order.php",
data: data,
dataType: "text",
error: function(){ alert("Jotakin meni pahasti pieleen! Yritä uudelleen?");
},
success: function() {
$(document).html("Tilaus lähti.");
}
});
You can make an ajax call to a php function that sends an email. The argument is the content generated by javascript.
You'll need to post the cart values to serverside PHP script and recreate the HTML for the cart in order to be able to send it through email. You can do direct form post or ajax post based on your need.
I asume your $.ajax() call looks something like this:
$('form').submit(function(){
var dataTrunk = $(this).serializeArray();
dataTrunk.push( { name: 'cartContent', value: $(your_table_selector).html()});
$.ajax({
url: 'mail.php', // your mail script
data: dataTrunk,
type: 'post'
});
return false;
});
In php you would trap $_POST['cartContent'] and render it in email and send it.
If you are sending email with html and plain text body, then it would probably be a good idea to strip html elements and replace them with chars that are compatible with plain text.
// edited: I've fixed the error
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Get URL parameter with jQuery
I have a form that posts data over ajax. The response comes back in the form of GET variables in the URL. For example if there was a failure of writing the form data the return address would be: http://example.com/?error=1
How would I check for this using jquery. Right now when I do a console.log on the msg variable I just get the html output of example.com (which I guess makes sense). I need the GET variables though. How would I achieve this?
$('#wp_email_capture').submit(function(e){
var email = $('#wp-email-capture-email').val();
$.ajax({
type: "GET",
url: "/",
data: "wp_capture_action=1&wp-email-capture-email=" + email
}).done(function( msg ) {
console.log(msg)
});
e.preventDefault();
});
AJAX by default will return the content from the request. What you want are the headers.
If you are being given a return address of http://example.com?error=1, then it means this is being returned as a redirect header.
To get the header information from an AJAX request, that has been answered here:
jQuery and AJAX response header