I have a form having some data
<form id="abc" method="POST" action="abc.html">
<input type="hidden" id="a" name="a" />
<input type="hidden" id="b" name="b" value="save"/>
</form>
and in js file i am submitting this form
document.getElementById("abc").submit();
What i want to do is if it throws any exception then an alert popup should open. Can anyone help?
Both previous answers are wrong. They check that object form exists but don't handle server-side errors.
You could use jQuery Form Plugin:
$('#myForm')
.ajaxForm({
url : 'myscript.php', // or whatever
dataType : 'json',
success : function (response) {
alert("The server says: " + response);
}
})
;
or simple ajax :
$('#form').submit(function(){
$.ajax({
url: $('#form').attr('action'),
type: 'POST',
data : $('#form').serialize(),
success: function(){
console.log('form submitted.');
}
});
return false;
});
You could find more details in answers to this question - How do I capture response of form.submit
Related
My Ajax request works correctly when I use change and the input is checkbox, but my Ajax request does not work when use input type submit !!
I want my type in the input submit and when I do this the Ajax request will not work and the page will reload.
$(document).on('change','.filter-form',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : $(this).serialize(),
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
my form :
<form action="" class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>
I don't think submit buttons trigger the change event, so you'll have to listen for something else, also .serialize() do not give you the name/value pair of submit buttons.
Use the click event on the buttons and use the element properties to get the data to post.
$(document).on('click','.filter-form input[type=submit]',function(event){
event.preventDefault();
$.ajax({
type:'GET',
url:'filter/',
data : {[this.name]: this.value}
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
alert("error" + data);
}
});
});
First added a clicked property to the identify which submit is clicked. Then used the clicked property to get the value & name of the submit to pass in form submit event handler.
$(document).ready(function(){
// To identify which submit is clicked.
$("form.filter-form input[type=submit]").click(function() {
$("input[type=submit]", $(this).parents("form")).removeAttr("clicked");
$(this).attr("clicked", "true");
});
// Form submit event handler
$("form.filter-form").submit(function(event) {
event.preventDefault();
$clickedInput = $("input[type=submit][clicked=true]");
dataString = {[$clickedInput.prop('name')]: $clickedInput.val()};
console.log('dataString', dataString);
$.ajax({
type:'GET',
url:'filter/',
data : dataString,
dataType: 'json',
success: function (data) {
$('#product-main').html(data['form']);
},
error: function (data) {
console.log("error" + data);
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="filter-form">
<input type="submit" name="price" value="new">
<input type="submit" name="discount" value="discount">
<input type="submit" name="old" value="old">
</form>
With Ajax and JS/Jquery I'm trying to send a simple Contact form to a Classic ASP (aspemail) and sent a messagem from a page without reload.
<form id="form-submit" action="ASPEmail.asp" method="post">
Name<br>
<input id="name" type="text"><br>
E-mail<br>
<input id="email" type="text"><br>
Message:<br>
<textarea id="msg"></textarea><br>
<input type="submit" id="btn" value="SEND">
<img src="loading.gif" class="loading">
</form>
My ASPEMAIL.ASP is only test asp and I write only:
<%
Response.Write("ok")
%>
And my JQuery Script:
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script>
$(function() {
$("#form-submit").submit(function() {
var data = $(this).serialize(),
action = $(this).attr("action"),
method = $(this).attr("method");
$(".loading").show(); // show loading div
$.ajax({
url: action,
type: method,
data: data,
success: function(data) {
if(data === "ok")
{
document.location = "final.asp";
}
},
error: function(err) {
// there was something not right...
},
complete: function() {
$(".loading").hide(); // hide the loading
}
});
return false; // don't let the form be submitted
});
});
</script>
I put a redirect on success to test (My objective is a message only) - but nothing happens.
But after send the "LOADING" appears on screen and hide and then the submit and "complete" is working.
Any idea what is wrong?
you have 2 variables named data, try using a different variable here, as I believe you're "confusing" javascript here :)
success: function(dataReturned) {
if(dataReturned === "ok")
{
document.location = "final.asp";
}
},
I submit the form when trigger submit. How ever I cannot create user record. I show you the code.
<form method="POST" id="form_1" action="../api.php" enctype="multipart/form-data" novalidate="novalidate">
<input type="text" name="name" id="name" value="Amy" readonly="readonly">
<input id="fileBox" class="fileUpload" type="file" name="img" accept="image/*" required>
<input type="hidden" name="isSubmit" value="1"/>
</form>
<a id="btnSubmit" href="javascript:void(0)">Submit</a>
In js file:
$('#form_1').submit(function(){
var formData = new FormData((this)[0]);
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "isSubmit", formData: formData},
processData:false,
contentType:false,
success: function(data){
$("#thankyou").show();
}
})
return false;
});
$("#btnSubmit").click(function(){
var name = $("#name").val();
$.ajax({
type: "POST",
url: "../../api.php",
data: { action: "checkInputData", name: name}
})
.done(function(data){
data = $.parseJSON(data);
if ( data.status == 0 ){
$('#form_1').trigger('submit');
}
api.php :
if( $action == "isSubmit"){
$name= isset($_POST["name"])?$_POST["name"]:null;
createUser($conn, $name);
}
I found the the flow of the submit is not correct.
The flow of the above code is when I trigger submit then fall into success show thankyou div, but didn't create user record.
however if I removed the "return false" in ajax, the flow will becomes : trigger submit then fall into success show thankyou div then redirected to api.php then finished. In this case I can create the user record.
My target result should be I trigger submit then fall into success show thankyou div and create user record. How can I do this? And what's the differnce between having and without the "return false".
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
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',