I want submit a form with GET request on page reload. How can I achiev this with Javascript/JQuery or without Javascript/JQuery in ASP.NET Core MVC web app. Thanks.
here is the code
this will submit on reload
$(window).on('beforeunload', function(){
$("form").submit();
});
or you can use URL to pass GET value
$(window).on('beforeunload', function(){
var v= $("input").val();
$(location).attr('href', 'http://example.com/index.php?value='+val);
// or window.location.href='http://example.com/index.php?value='+val;
});
you can use ajax if above method doesn't work
$(window).unload(function(){
$.ajax({
type: 'GET',
url: 'script.php',
async:false,
data: {value:"username"}
});
});
if async is set to false browser waits for request to complete else it will not.
that is why above first two method may not work.
Related
I do a jQuery ajax POST which successfully delivers the correct data to the server.
After the POST is complete, the browser has redirected to the post url page... which I don't want. Neither of the alerts occur. The POST data has arrived at the server just fine.
i.e. after the ajax is performed within a page at http://myDomain/myPage.html as shown below, the browser address bar shows http://myDomain:39991/updateEnabled and no alerts have happened.
var enabledAjax = $.ajax({
url: 'http://myDomain:39991/updateEnabled',
method: 'POST',
data: $('#enabledForm').serialize(),
dataType: 'jsonp'
});
enabledAjax.done(function (msg) {
alert('done')
})
enabledStatus.fail(function (jqXHR, textStatus) {
alert('textStatus');
})
In express, i have router.post('/updateEnabled', urlEncodedParser, updEnab);
Within updEnab all I do at the moment is a console.log of req.body and res.end()
I've tried a 'success' method within the ajax params but that doesn't work either.
What am I doing wrong that is causing the redirect to the POST url?
hello when you submit form this is submitting normally so you need to use this.
event.preventDefault()
this will stop stop normal submitting of form.
To stop the redirection you can use the return statement like this:
enabledAjax.done(function (msg) {
return false;
})
=====UPDATE AGAIN==== (if anyone cares!)
the solution I posted before stopped working for whatever reason. I included a beforeSend in my ajax request and pasted the portion of my js that validates my form into it. Works like a charm now!
$('#form').on('submit', function(e) {
e.preventDefault(); //prevents page refresh
$.ajax({
type: "post",
beforeSend: function(){ // check that form is complete
},
url: "client_config_send2.php",
data: $(this).serialize(),
success: function(data){
alert('Thank you'); hide_request();window.location = "#top";
}
});
});
EDIT
See my answer below, using 2 .preventDefault!
I have read through many pages / examples of this, but for some reason I can't get it to work on "my" form.
I'm simply trying to submit my form without refreshing the page or opening a new page / tab for the confirmation message.
The form:
<form id="form" name="Configurator" method="post" action="">
.... //Client configures his product, display an image if they choose, and request a quote.
<button id="submit_button" type="submit" name="Submit" >Request</button>
</form>
The client_config_send2.php works, it simply pulls a bunch of parameters from the form (configuration, contact info) and puts it into an email. This part works fine before I try to integrate the ajax.
The JS:
$('form').on('submit', function(e) {
e.preventDefault();
if(!validateForm(this)){
return true;
}
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
done: function(data){
alert("Thank you, we will get back to you shortly");
}
});
})
</script>
The validateForm() function also works, it checks if the configuration is valid, if the email / contact info is complete, etc.
At this point, the validateForm works: if info is missing, the alert pops up. However when validateForm() returns true, the form doesn't submit, nothing happens.
I have tried success instead of done, return false instead of true in the JS, and many other things I found online but I am lost. Never used AJAX before so I'm not 100% confident with the subtleties of the language!
Thanks in advance!
"client_config_send2.php" is a filename. The URL you give to Ajax needs to be, well, a URL like http://example.com/client_config_send2.php.
Change done to success:
success: function(data){
success only fires after your request got response and the response code is OK(http 200).
Update the code below:
$('form').on('submit', function(e) {
e.preventDefault();
if(!validateForm(this)){
return true;
}
var formdata = $(this).serialize();
$.ajax({
type: "post",
url: "http://www.example.com/client_config_send2.php",
data: formdata,
success: function(data){
alert("Thank you, we will get back to you shortly");
}
});
})
</script>
Could you try removing/commenting event.preventDefault();
If this method is called, the default action of the event will not be triggered. (http://api.jquery.com/event.preventdefault/)
Try coding in the following format. The logic uses an if/else statement to make the ajax call.
$('form').on('submit', function(e) {
//If form could not be validated
if(!validateForm(this)){
//prevent the form form submitting
alert("Your form is not valid for submission!");
e.preventDefault();
}
//else
else{
//form input is valid
//make the ajax call
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
done: function(data){
alert("Thank you, we will get back to you shortly");
}
});
}
});
});
Here is the final code that does exactly what I want:
- the validateForm() function works as it should. If the form is not complete, it returns false, an alert pops up and the form does not submit
- if validateForm() returns true, the form gets submitted, the confirmation alert pops up and the page does NOT refresh. Users can then build a new configuration and submit a new request without re-entering all the contact info.
The 2 .preventDefault did the trick!
$('form').on('submit', function(e) {
e.preventDefault(); //prevents page refresh when form is submitted
//If form could not be validated
var x = validateForm();
if(x == false){
//prevent the form form submitting
e.preventDefault();
}
//else
else {
//form input is valid
//make the ajax call
$.ajax({
type: "post",
url: "client_config_send2.php",
data: $(this).serialize(),
success: function(data){
alert('Thank you! we will get back to you within 24 hours. Please check your junk / spam folder if you do not receive a response within that time.');
}
});
}
});
Thanks everyone for your help!
I have been working on this for a while and posted several related topics about it, but this is slightly different question. I have the following AJAX code with some html forms below it with in #container and .myselect is the class of a drop-down box. When I change the value in the box I want to be able to then use that value on other fields below the select. The AJAX code kinda works in that the alert shows the right value when changed but as you can see I have tried lots of success functions but no luck. The closest is
$('#reloadtest').html(data); which will show the value in my PHP and every time I change the value from then on it will change alot, but it reloads the page within the container.
Basically I want to know how I can reload the data but not the whole html/page so I can use the value of the drop down in my PHP.
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
type: "POST",
data: { orderidType : orderidVal },
success: function(data) {
//$('#container').reload('#container', function() {});
//$('#quoteselect').reload('#quoteselect', function() {});
//$('#container').load('orders.php #container', function() {});
//$('#quoteselect').load('orders.php #quoteselect', function() {});
//$('#testreload').reload('#testreload', function() {});
//location.href = "test2.php"
$('#reloadtest').html(data); //this allows me to use the variable but reloads the whole page within the page
}
})
});
});
If you are doing an ajax-request you have to allocate an URL where to send the request.
If you don't Request anything jQuery reloads the page. As you can see here in the jquery-api-docu the URL is the very first and most important parameter of the request.
$.ajax({
url: "/url/to/the/php/script.php",
success: function(data){
//do something ... with data parameter
}
});
would be the simple way of using ajax-request with javascript.
use two divs - one in which you can put ajax response and in other the remaining HTML code
it reloads your page because you have not specified what page to request.
use the code below and replace /path/to/script to your actual script path
$(document).ready(function(){
$('#container').on( 'change', '.myselect', function() {
var orderidVal = $(this).val();
alert(orderidVal);
$.ajax({
cache: false,
async: true,
type: "POST",
url: '/path/to/script',
data: { 'orderidType' : orderidVal },
success: function(data) {
$('#reloadtest').html(data);
}
});
});
});
The server is written in web2py, and hosted on google app engine. I can visit my index.html by entering domain.com/index and I can send form by entering domain.com/register where "register" is a function defined by default.py
However, in html, where I would like to send form to the server and get a response, I use ajax which has cross domain issues. So I use "register" as URL, and it does not work. Help?
$("#signup").click(function() {
$.ajax({
type: "POST",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
By typing domain.com/register, I can totally trigger the function. What is the problem here? And the form is sent to domain.com... In browser it appears as htt[://domain.com/?email=ada#ad.com&password=adsa
Its very possible register is looking for GET instead of POST
try changing the type in ajax
$("#signup").click(function() {
$.ajax({
type: "GET",
url: "register",
data: $("#formsignup").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data);
}
});
return false; // avoid to execute the actual submit of the form.
});
I want to trigger this function, which uses the jquery's post method, when a form is submitted:
function update_point_session(){
$.post('/update_point_session/',
{session: true},
function(data){}
);
return true;
}
I uses the onsubmit to trigger it.
The problem is that it won't send it when the form is submitted. But if I return false; it will (though the form itself, of course, will not). It looks as if the $.post is not send before the page is directed to another one by the form..
So I think I somehow have to return true; AFTER the $.post. I tried to do this by putting it inside function(data){} but it did not work..
How can I send BOTH the post from jquery and from the form?
There are a couple of things you can do.
Make the AJAX synchronous
Since $.post is, according to the documentation, equivalent to
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
You can simply replace $.post with the equivalent $.ajax call, and also add async: false to the options. This will submit the form with AJAX and then, due to the return true; from the function, will also let the browser post the form normally.
Submit the form only after the AJAX completes
This involves some event handler juggling:
// attach submit event handler to the form
$("#myform").submit(function() {
// Handler immediately detaches itself, so that
// we don't have an infinite loop when we call
// $(this).submit() ourselves below
$(this).unbind('submit');
// Do the AJAX
$.post(
'/update_point_session/',
{session: true},
function(data){
// When the AJAX completes, tell the browser
// to re-submit the form
$(this).submit();
}
);
// Prevent the browser from submitting it NOW,
// because the AJAX is still running
return false;
});
You must wait for the asynchronous post to complete before unloading the page. You can send back a redirect url from the server as json something like this:
$('form').submit(function(e){
$.post(this.action || '/update_point_session/', $(this).serialize(), function(data){
// send back a redirect url from the server
if(data.url) location.href = data.url;
});
e.preventDefault()
});
I would do something like this.
$('form#myFormId').submit(function(evt){
var form = $(this);
evt.preventDefault(); // Prevents default submission
$.post('/update_point_session/', {session: true}, function(data){
form.unbind('submit'); //Unbind js submit event
form.get(0).submit(); //submit the form
});
});