Form Post data using Ajax and jquery - javascript

I have a Form
<script type="text/javascript" src="result.js"></script>
<script type="text/javascript" src="jquery.js"></script>
<form name="form" method="POST" id="form">
<input type="text" value="" id="htno" name="htno" Maxlength="12" style="width:165px;" class="bodytext"></input>
<input type="button" value="Submit">
</form>
<div id="result" class="result"></div>
And result.js file is
$("#form").submit(function (event) {
event.preventDefault();
$("#result").html('');
var values = $(this).serialize();
$.ajax({
url: "url",
type: "post",
data: "htno=" + htno + "&code=2132",
success: function () {
alert("success");
$("#result").html('submitted successfully');
},
error: function () {
alert("failure");
$("#result").html('there is error while submit');
}
});
});
htno is the value the user enters through form
Data to be posted is htno & code
i am unable to get output using this, please can u tell me the fault . . . .

You should know that a form is submitted when the input type is submit.In your code change the type of button to submit.
just change the part
<input type="button" value="Submit" >
to
<input type="submit" value="Submit" >
and in your result.js remove this line
event.preventDefault();
because this line prevent your form from submitting without any reason.

try changing your
$("#form").submit(function(event) {
event.preventDefault();
by
$(document).on('submit','#form',function(e) {
e.preventDefault();
alto, try to alert data

The page you are trying to connect use temporary tokens. You cannot do what you are looking for. You are not allowed to do it. Ask owner of site for kind of API access, he could make you a good price... { this topic should be closed! }

Related

I'm posting form data with AJAX, but the form keeps submitting and refreshing the page anyway. What am I missing?

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('');
}
});
});

jQuery.post() has a side-effect of changing my URL parameters

I have a page with multiple forms. When the users fill in one of the forms, I want to send it to a server. However, I need the browser to keep displaying the original page, so that the users can submit other forms, if they wish to. Hence I cannot use the "action" attribute in the form and a "submit" type of button.
After consulting the jQuery.post docs, I arrived to the following solution:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button" onclick="submitForm();"> Submit </button>
</form>
<script>
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
</script>
</body>
</html>
The above code does what I want it to do, but it has a very peculiar and disruptive side-effect of modifying my URL to include the parameters I'm posting.
So when I fill in my name and email, I'm "redirected" to myself, but with the name and email parameters appearing in the URL:
http://localhost:8080/Prototype/TestPost.html?name=Lev&email=Storytime%40gmail.com
Now, I definitely do not want "name=Lev&email=Storytime%40gmail.com" to be a part of my URL. These parameters are also not intended for TestPost.html but rather to SaveForm.jsp, so it's all very wrong.
I also want to mention that SaveForm.jsp works as expected. It receives the parameters, saves them to the database and returns a success response.
What am I missing?
Thanks.
EDIT
Thanks, everybody. I could not avoid the refresh using the "return false" statement, so I had to use jQuery's "on click" option. I also don't understand how using ajax explicitly would make any difference, since jQuery's documentation seems to say that the post is just a syntactic sugar for Ajax.
The complete code which worked for me was:
<html>
<head>
<link rel="stylesheet" href="jquery-ui-1.11.3/jquery-ui.css">
<script src="jsFiles/jquery-2.1.3.min.js"></script>
</head>
<body>
<form id="form" method="post">
Name:<br> <input type="text" name="name"> <br>
Email:<br> <input type="text" name="email"> <br>
<button id="button"> Submit </button>
</form>
<script>
$( document ).ready(function() {
$("#button").click(function( event ) {
event.preventDefault();
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
}).fail(function() {
alert("Error submitting the form.");
})
});
});
</script>
</body>
</html>
If you don't especify the method attribute on the form it will be GET by default, that's why you get the URL params. Also, because you aren't not stopping the default action, your form is being submitted (the reloading effect), so I recommend you the following code to help you:
<script>
$(function() { //executes js code after html has been loaded
$("#button").on("click", function(e) {
e.preventDefault(); //avoids to reload the page
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
}).done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
}
});
</script>
And remove the onclick at the button to have a cleaner HTML:
<button id="button"> Submit </button>
If you do not want to use jQuery's on click and still stick to the submit function you can just add return false; in the end to prevent the form from submitting.
Like below
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData ,function() {
})
.done(function() {
alert("The form was submitted successfully");
});
.fail(function() {
alert("Error submitting the form.");
})
return false;
}
Hope this helps.
I guess, you are not submitting the form by ajax.
Add return false;, to that it does not redirect and submit via ajax.
function submitForm() {
var postData = $('#form').serialize();
var jqxhr = $.post("SaveForm.jsp", postData, function() {})
.done(function() {
alert("The form was submitted successfully");
})
.fail(function() {
alert("Error submitting the form.");
})
return false;
}

AJax not calling php file correctly, html forms

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

Ajax form with separate action values

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',

how can i know the cursor is now focus in input or textarea or select

I want to run ajax to get a value , if value is true ,then submit the form, the code bellow using onsubmit=xxx , but this form will submit immediately , not waiting ajax result. then I want to using an "a" tag with onclick function to submit the form , this can do the job, but when I using "enter" key to submit the form , will not run ajax codes. then I want to bind keypress when the cursor is in input field to submit the form. how to check the cursor is in or out of the form fields?
<?php
if(isset($_POST['act'])){
$rs=array(
'status'=>0
);
echo json_encode($rs);
exit;
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class="filters">
<form onsubmit="return filters.submit()">
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
</div>
<script type="text/javascript">
var filters={
form: $('.filters').find('form'),
submit: function (){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax'
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
return true;
}else{
return false;
}
}
});
}
}
</script>
As #Rajesh Jinaga said document.activeElement return the currently focused element but I want to explain you why it doesn't work.
When you are making your ajax call it won't wait until the ajax return true or false. It will execute. So you need to prevent the form to be submited and submit it with javascript when your ajax call is finished.
HTML
<form>
<input type="text" name="name" />
<input type="submit" value="submit" />
</form>
JAVASCRIPT (jQuery)
$('form').submit(function (e){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax'
},
success:function(rs){
// No need of EVIL eval('var rs='+rs);
if(rs['status']==1){
$(this).submit(); // Will submit the form.
}else{
alert("FAILED!");
}
}
return false; // Shortcut for e.preventDefault() and e.stopPropagation() so it will prevent the form to be submitted.
});
document.activeElement returns the currently focused element, that is, the element that will get keystroke events if the user types any.
$(this).submit() won't work because you are in different context, and success callback invoker send ajax related object but not form DOM object. Store object into a variable in the form context and use it in success callback.
$(function(){
$('form').submit(function (){
var form = this;
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax',
status: $('[name=status]').val()
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
$(form).submit(); // or $('form').submit()
}else{
alert('error');
}
}
});
return false;
});
});
#L105, thank you for your answer, I modify my code to match your answer , but the form can not submit using $(this).submit();
<?php
if(isset($_POST['act'])){
$rs=array(
'status'=> $_POST['status']
);
echo json_encode($rs);
exit;
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<div class="filters">
<form action="index.php" method="post">
<input type="text" name="status" />
<input type="submit" value="submit" />
</form>
</div>
<script type="text/javascript">
$(function(){
$('form').submit(function (){
$.ajax({
url:'index.php',
type:'POST',
data:{
act:'ajax',
status: $('[name=status]').val()
},
success:function(rs){
eval('var rs='+rs);
if(rs['status']==1){
$(this).submit(); // can't submit
}else{
alert('error');
}
}
});
return false;
});
});
</script>

Categories