I have a contact form with multiple submit buttons which have different action values.
<form action="confirm.php" data-query="send.php" method="POST" class="form">
I am using data-query attribute to fetch action link for one of the submit buttons.
<input type="submit" name="submit1" id="submit1">
<input type="submit" name="submit2" id="submit2" value="Submit B">
Ajax code is below:
<script>
$(function() {
$('#submit2').click(function(e) {
var thisForm = $('.form');
e.preventDefault();
$('.form').fadeOut(function() {
$("#loading").fadeIn(function() {
$.ajax({
type: 'POST',
url: thisForm.attr("data-query"),
data: thisForm.serialize(),
success: function(data) {
$("#loading").fadeOut(function() {
$("#success").fadeIn();
});
}
});
});
});
})
});
</script>
I am getting the success message but the php code isn't getting executed.
The PHP code is working fine without the AJAX method.
.serialize() doesn't give you button values, you'll have to add it manually, something like
data: thisForm.serialize()+'?button2=Submit%20B',
Related
I have 2 separate form that are working fine, but my subscribe button is calling add comment form. So when button from second form is clicked my add_comment.js is also called. On my website I have only buttons for subscribtion and for adding comments on one specific page. I'd like to make my add_comment called when form or button with specific id is clicked or submitted and every other button to call news.js which is working fine. I searched for answer but none was good for me
First Form
<form name ="add_comment" id="add_comment" class="comment-form">
//some inputs name, email..
<button type="submit" name="submit" id="buttonKomentar">Submit</button>
</form>
Second Form
<form action="" method="post" novalidate>
<input type="text" class="form-control" placeholder="Your Email">
<button class="btn btn-block btn-default" id="buttonSub">Subscribe</button>
</form>
News.js
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "dodaj_za_news.php",
data: {
email: $("#email").val(),
},
success: function(result) {
$('#news').html(result);
},
error: function(result) {
$('#news').html(result);
}
});
});
add_comment.js
$(document).ready(function(){
$("#buttonKomentar").on("click", function(e){
$.ajax({
type: 'post',
url: 'add_comment.php',
data: $('form').serialize(),
success: function (data) {
$('#potvrda').html(data); }
});
});
});
First form doesn't have closing tag. If it is the same in your code, then the second form is treated as a part of parent form.
So I'm making a very small, very simple chat application using mostly JQuery / AJAX.
Here is my HTML form.
<form class="chat_form" method="post" id="chat_form" autocomplete="off">
<input class="form-control" type="text" name="chatMe" placeholder="Type here..." autocomplete="off">
<input type="submit" value="Submit" name="submit">
</form>
Here is my script:
<script type="text/javascript">
$('.chat_form').submit(function(){
$.ajax({
url: "runMe.cfm",
type: "POST",
data: $('.chat_form').serialize(),
success: function() {
$('.chat_form input').val('');
}
});
});
</script>
To my understanding, that's supposed to submit all the form information to my action page then clear the input - and it does. That part works fine. I'm getting my data.
But whenever I submit the form, the entire page reloads as if it's ignoring a key part of my code.
Any help on that part? Thanks.
Solution 1:
By adding e.preventDefault();
Example:
$('.chat_form').submit(function(e){
e.preventDefault();
//ajax code here
});
Solution 2
Alternatively, by adding little javascript onsubmit="return false" code in form tag:
Example:
<form class="chat_form" method="post" id="chat_form" autocomplete="off" onsubmit="return false">
You need to call e.preventDefault() for can submit the form only from the javascript code.
$('.chat_form').submit(function(e){
$.ajax({
url: "runMe.cfm",
type: "POST",
data: $('.chat_form').serialize(),
success: function() {
$('.chat_form input').val('');
}
});
e.preventDefault() // put that line of code here or on last line on success function
});
You have propagation of the event by default, you probably need one or both of these calls:
e.preventDefault();
e.stopPropagation();
When the submit() is called on your object, it won't stop there. It will call the default afterward, so you want to add a parameter and then do those calls as in:
$('.chat_form').submit(function(e){ // <- add parameter here
e.preventDefault();
e.stopPropagation();
$.ajax({
url: "runMe.cfm",
type: "POST",
data: $('.chat_form').serialize(),
success: function() {
$('.chat_form input').val('');
}
});
});
I have the following form in my HTML page:
<form id="submission" action="testresponse.php" method="post">
<input id="URL" name="URL" type="text">
<button name="Submit" type="submit">Submit</button>
</form>
testresponse.php just contains <?php print_r($_POST); ?> to print all the post variables.
I am trying to submit the form and have it return the values on the same page that the page was submitted (i.e. return the POST variables somewhere above the form)
I used the following jQuery code:
$( document ).ready(function() {
var frm = $('#submission');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log(data.responseText);
}
});
ev.preventDefault();
});
});
But for some reason data.responseText always returns blank
Is there a way to have my form send a POST request to a PHP page and return the result?
Change from
console.log(data.responseText)
to
console.log(data)
Below is my code of html and jquery, i want to dsiplay results on submit button on the same page rather than its goes on next page. But it is not returning me any results and go to next page.
HTML code
<form id="create" action="/engine_search/search/" method="get">
<input style="height:40px;" type="text" class="form-control" placeholder="Search" name="q">
<center>
<input style="float:left; margin-left:150px;" type="submit" class="btn btn-default" value="Search">
</center>
</form>
jquery code:
<script>
$(document).ready(function() {
$('#create').submit(function() { // catch the form's submit event
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
<input style="float:left; margin-left:150px;" type="submit" class="btn btn-default" value="Search" onclick="return SubmitFunction(this);">
Javascript :
function SubmitFunction(thisId){
$.ajax({ // create an AJAX call...
data: $(thisId).serialize(), // get the form data
type: $(thisId).attr('method'), // GET or POST
url: $(thisId).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
}
You should use event.preventDefault();
<script>
$(document).ready(function() {
$('#create').submit(function(event) { // catch the form's submit event
event.preventDefault();
$.ajax({ // create an AJAX call...
data: $(this).serialize(), // get the form data
type: $(this).attr('method'), // GET or POST
url: $(this).attr('action'), // the file to call
success: function(response) { // on success..
$('#created').html(response); // update the DIV
}
});
return false; // cancel original event to prevent form submitting
});
});
</script>
Look for console for any errors. It might be helpful.
UPDATE:
This is the error:
412 (Precondition Failed)
I am trying to call a php script from ajax, I currently have the below ajax, which when the button in the form (also below) is clicked will call a php script passing it the form data, which will then be submitted to the database.
However, it is not working; and what's more I am just getting a blank error back, so I do not even know what is going wrong.
Could someon please point me in the right direction?
Thanks.
HTML form:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<!--<input id="report-submit" value="" name="submit" type="submit" onclick="submitReport()"/> -->
<button id="report-submit" name="submit" onclick="submitReport()"></button>
</form>
AJax call:
function submitReport()
{
var ID=$('#reportedID').val();
var reason=$('#reason-box').val();
var formData = "ID="+ID+"&reason="+reason;
alert(formData);
//This code will run when the user submits a report.
$.ajax(
{
url: 'submit_report.php',
type: "POST",
data: formData,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
}
Now I have already tested the php script, and that works fine, the problem started when I added the ajax call so I know it is something to do with the ajax not the php.
This should correct the problem with submitting:
Your jQuery Ajax call won't succeed because the POST data isn't supplied in the correct format.
If the ajax should succeed the form is also posted resulting in a 405 error.
<button id="report-submit" name="submit" onclick="submitReport(event)"></button>
function submitReport(event)
{
event.preventDefault();
....... // your code
}
Now the default action of your form will be prevented (resulting in a 405 error). And only the ajax request is submitted.
In the button element we pass the event object on to the function. We use event.preventDefault() to make sure the button doesn't run it's default action, which is submitting the form.
You could also prevent this by deleting the form element as a wrapper, but maybe you want to use other features (like validation) on the form.
Form data in a jQuery ajax request needs to be an object called data:
var formData = {"ID" : ID, "reason" : reason};
jQuery will reform this to a correct query string for the submit.
I would do it like this:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160"></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" type="submit" name="submit" value="submit"></button>
</form>
<script type="text/javascript">
jQuery("document").ready(function(){
var $ = jQuery
$("form").submit(function(){
var data = "";
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
url: "submit_report.php",
data: data,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
return false;
});
});
</script>
and then use $reason=$_POST['reason-box']; and $ID=$_POST['reportedID']; inside your PHP script
this is optional to choose the form for submitting data or you can do it without the HTML form this is what i do
<textarea id="reasonbox" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" ></button>
and the using folloing javascript and jquery style
<script type="text/javascript">
$(function() {
$("#report-submit").click(function(){
try
{
$.post("your php page address goes here like /mypage.php",
{
//in this area you put the data that is going to server like line below
'reasonbox':$("#reason-box").val().trim(),
'reportedID':$("#reportedID").val().trim()
}, function(data){
data=data.trim();
//this is data is sent back from server you can send back data that you want
//like message or json array
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>
I hope it helps