This question already has answers here:
Send JavaScript variable to PHP variable [duplicate]
(3 answers)
Closed 9 years ago.
In my index.php, I have an update button as below.
<form action="update.php" method="post" >
<button type="submit">Update</button>
</form>
I have defined a javascript function to override the default form action. The javascript function is as below.
<script type="text/javascript">
$(document).ready(function() {
$('form').submit(function(e) {
e.preventDefault();
alert("HI");
$.ajax({
type: 'post',
url: 'update.php',
data: {
source1: "some text",
},
success: function( data ) {
console.log( data );
}
});
});
});
</script>
After I click on the update button, I am getting the alert. However, I am not redirected to update.php page as expected. I am trying to send some values in the ajax request which can be used for processing in the update.php page.
You are not redirected because PHP redirects do not affect the browser when run as an AJAX call. You'll need to specify a JavaScript redirect in the success function:
$.ajax({
type: 'post',
url: 'update.php',
data: {
source1: "some text",
},
success: function( data ) {
document.location.href = 'update.php'
}
});
However, I don't believe that this is what you want. You seem to want to add new form data on submitting the form, in which it might be better to prevent the default behaviour, add any additional data with hidden input fields, and then re-submit the form:
$(function ()
{
$('form').submit(function (e)
{
if ($(this).is(':not([data-submit="true"])'))
{
$('form').append('<input type="hidden" name="foo" value="bar">')
$('form').data('submit', 'true').submit()
e.preventDefault()
return false
}
}
)
}
)
</script>
Related
This question already has answers here:
How to stop form submit during ajax call
(7 answers)
Closed 2 years ago.
I am new to JQuery and ajax in general and I want to disable form submit after I get data from my controller back (I am using Asp.net core MVC). Thing is that even tho I cancel submit it submits anyways as shown bellow:
$("form").submit(function (e) {
var link = '#Url.Action("Action", "Controller")';
var args = {
arg1: Elem1.val(),
arg2: Elem2.val()
};
$.ajax({
type: "GET",
url: link,
data: args,
dataType: "json",
success: function (data) {
alert(data.canacess); //Shows False
if (data.canacess== true) {
AllEnable();
}
else { //Goes here
e.preventDefault(); //Dont do this
alert(data.erromessage); //Do this
}
},
error: function () {
alert("Error. Kontaktujte správce.");
return;
}
});
});
I think it has to do something with ajax because anywhere else in code it works.
Thanks for any help!
e.preventDefault() needs to be invoked within the scope of the submit function handler. Right now you're invoking it in the AJAX callback handler which is far too late to have any effect.
Is there any way that I can stop form from being submitted until I decide whether I submit it or not?
Yes. To do that you need to always call e.preventDefault() in order to stop the form submission so that you give the AJAX request time to execute and return a response. Then, based on that response, you can directly submit the HTMLFormElement object, note not the jQuery object, and send the form data to the specified action. Try this:
$("form").submit(function(e) {
e.preventDefault();
var form = this;
$.ajax({
type: "GET",
url: '#Url.Action("Action", "Controller")',
data: {
arg1: Elem1.val(),
arg2: Elem2.val()
},
dataType: "json",
success: function(data) {
if (data.canacess) {
AllEnable();
form.submit();
}
},
error: function() {
alert("Error. Kontaktujte správce.");
}
});
});
Also note that when using boolean values in conditions it's redundant to compare them to true/false. Similarly, the return in the error handler is redundant as it's the last statement in the function anyway.
So I'm using this piece of javscript/ajax to create a form that submits to another page on my site without reloading the page. My question is how can I program this same code to work with multiple forms on the same page? If I have two forms that I want to submit to two separate locations how do I specify which form triggers which piece of javascript?
<script type="text/javascript">
function submit() {
$("form").submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'csverify.php',
data: $('form').serialize(),
success: function() {
console.log("Signup was successful");
},//here
error: function() {
console.log("Signup was unsuccessful");
}
});});//here
}
$(document).ready(function() {
submit();
});
</script>
Not sure if it matters but I would like to use either name="" or ID="" to designate each form with a name.
You can create a method passing form's ID.Then get the form attribute action on different by form's ID.
Html part
<form id="form1" action="form1.php">
...
</form>
<form id="form2" action="form2.php">
...
</form>
JS part
<script type="text/javascript">
function submit(formID) {
var $form = $('#'+formID);
$form.submit(function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: $form.attr('action'),
data: $form.serialize(),
success: function() {
console.log("Signup was successful");
},//here
error: function() {
console.log("Signup was unsuccessful");
}
});
});//here
}
$(document).ready(function() {
submit('form1');
submit('form2');
});
</script>
My form
<form id="reservationForm" action="sendmail.php" method="post">
...
.
.
.
.
<input type="image" src="images/res-button.png" alt="Submit" class="submit" width="251" height="51px">
My javascript
$("#reservationForm").submit(function () {
e.preventDefault();
var $form = $(this);
$.ajax({
type: 'POST',
url: 'sendmail.php',
data: $('#form').serialize(),
success: function(response) {
alert("Success");
$('#reservationForm').fadeOut("slow");
}
});
return false;
});
i don't want to run any validation because i have user 'required' in all types. i just want to send data to my php while staying at the same contact form. but this only load my php file and send the e-mail. looks like it dosen't run my javascript. please help
You haven't defined the event argument in the callback. Change this line as follows and it should work:
$("#reservationForm").submit(function (e) {
...
EDIT: BTW: The .submit event handler of jQuery short hand is deprecated. You should be using .on('submit', ...instead.
i need help..why does my code not working?what is the proper way to get the data from a form.serialize? mines not working.. also am doing it right when passing it to php? also my php code looks awful and does not look like a good oop
html
<form action="" name="frm" id="frm" method="post">
<input type="text" name="title_val" value="" id="title_val"/>
post topic
</form>
<div id="test">
</div>
Javascript
$( document ).ready(function() {
$('#save').click(function() {
var form = $('#frm');
$.ajax({
url: 'topic.php',
type:'get',
data: form.serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
});
Php
<?php
class test{
public function test2($val){
return $val;
}
}
$test = new test();
echo $test->test2($_POST['title_val']);
?>
OUTPUT
You're telling your ajax call to send the variables as GET variables, then trying to access them with the $_POST hyperglobal. Change GET to POST:
type:'post',
Also, it should be noted that you are binding your ajax call to the click on your submit button, so your form will still be posting. You should bind on the form's submit function instead and use preventDefault to prevent the form posting.
$('#frm').submit(function(e) {
e.preventDefault(); // stop form processing normally
$.ajax({
url: 'topic.php',
type: 'post',
data: $(this).serializeArray(),
success: function(response) {
$('#test').html(response);
}
});
});
I am using ajax to update the db with a new folder but it refreshes the page after ENTER is hit.
on my form I have onkeypress="if(event.keyCode==13) savefolder();"
here is the javascript code that I have: what it does basically is after you hit enter it calls the function savefolder, savefolder then sends a request through ajax to add the folder to the db. Issue is it refreshes the page... I want it to stay on the same page.
any suggestions? Thank you
<script>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
// ajax request to add the folder
jQuery.ajax({
type: 'get',
url: 'addfolder.php',
data: 'foldername=' + foldername + '&foldercolor=' + foldercolor,
beforeSend: function() { alert('beforesend');},
success: function() {alert('success');}
});
return false;
}
</script>
This is working:
<form>
<input type="submit" value="Enter">
<input type="text" value="" placeholder="search">
</form>
function savefolder() {
var foldername= jQuery('#foldername').val(),
foldercolor= jQuery('#foldercolor').val();
jQuery.ajax({
type: 'get',
url: '/echo/html/',
//data: 'ajax=1&delete=' + koo,
beforeSend: function() {
//fe('#r'+koo).slideToggle("slow");
},
success: function() {
$('form').append('<p>Append after success.</p>');
}
});
return false;
}
jQuery(document).ready(function() {
$('form').submit(savefolder);
});
http://jsfiddle.net/TFRA8/
You need to check to see if you're having any errors during processing (Firebug or Chrome Console can help). As it stands, your code is not well-formed, as the $(document).ready() is never closed in the code you included in the question.
Simply stop the propagation of the event at the time of the form submission
jQuery(document).ready(function($) {
$("#whatever-form-you-are-pulling-your-values-from").submit(function(event) {
var foldername = $('#foldername').val();
var foldercolor = $('#foldercolor').val();
event.stopPropagation();
// ajax request to add the folder
$.ajax({
type: 'get',
url: '../addfolder.php',
data: 'ajax=1&delete=' + koo,
beforeSend: function() { fe('#r'+koo).slideToggle("slow"); },
success: function() { }
});
});
Since by default on a form the enter button submits the form, you need to not only handle this with your own code, but cancel the event after.
Try this code instead:
onkeypress="if(event.keyCode==13) {savefolder(); return false;}"
The onkeypress event will that the return value of the javascript and only continue with it's events if it returns true.