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

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;
}

Related

Call AJAX to send value with button

I read a lot of similar questions, and I tried all solutions but nothing seems to work. I want to send an AJAX request by clicking a button and send what the user typed in a textarea and display it in a div(chatbox). When I click the button, nothing happens. It never calls the function that has the AJAX code. Do you have any ideas what is going on?
P.S. I included the JavaScript files but nothing's changed.
<form action="ajax()">
<textarea id="txtArea" name="txtArea" ></textarea>
<input type="submit" value="Submit" />
</form>
<script type="text/javascript">
//AJAX function
function ajax() {
alert("insert");
var txtArea = $("#txtArea").val();
$.ajax({
type: "POST",
url: "InsertMessage.php",
data: {
txtArea: txtArea
}
success: function(data) {
alert(data);
$("#chatbox").load("DisplayMessages.php")
$("#txtArea").val(""); //Insert chat log into the #chatbox div
}
error: function() {
alert('there was an error, write your error handling code here.');
}
});
}
$(document).ready(startAjax);
//setInterval(function(){
// $("#chatbox").load("DisplayMessages.php");
//}//,1400);
</script>
Your question is not so clear, But for sending data in post method when submiting a form and then show result in a div, try something like this:
html:
<form>
<textarea id="txtArea" name="txtArea" ></textarea>
<input type="submit">
</form>
<div id="resultDiv">
</div>
js:
$( "form" ).submit(function( event ) {
var txtArea = $("#txtArea").val();
$.ajax({
type:"POST",
url:"InsertMessage.php",
data:{txtArea:txtArea}
success: function(data){
alert(data);
$("#resultDiv").html(data);
}
error: function(){
alert('there was an error, write your error handling code here.');
}
});
});
The action attribute has to contain a URL, not Javascript. You can use:
<form action="javascript:ajax()">
or:
<form onsubmit="ajax(); return false;">
or you can bind the event in jQUery:
$(document).ready(function() {
$("form").submit(function() {
ajax();
return false;
});
});

Classic ASP + Ajax Form - success function not working, complete is ok

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";
}
},

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

Call php in HTML form on action but don't redirect

I have an HTML form as follows:
<form id="ContactForm" name="ContactForm" method="post" action="emailinfo.php">
and then a submit button that calls verify():
Send
verify is defined as such:
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
}
}
Currently, when I click the submit button, the browser redirects to emailinfo.php, which is just a blank white screen because that php file just sends off an email and does nothing else. How can I run that php file without redirecting to it?
What you want to do is use AJAX to send a request to the emailinfo.php file when the button is clicked. Making the form action blank will cause the form to post to the same page you're on.
If you're using jQuery, it's pretty easy to submit the form via ajax:
$(document).ready( function() {
$('.button1').click(function(){
var f = $('#ContactForm');
$.ajax({
type: "POST",
url: "emailinfo.php",
data: f.serialize()
});
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
//document.getElementById('ContactForm').submit();
var name=$('#name').val();
var email=$('#email').val();
var formData = "name="+name+"&email="+email;
$.ajax({
url : "emailinfo.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
//data - response from server
alert(data);
},
});
}
}
</script>
<form id="ContactForm" name="ContactForm" method="post" action="">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
Send
</form>
ContactFormFirst change that a tag to a button, then assign that verify() to its onclick. then in verify(). use ajax to post the values from your form to emailinfo.php.
u can use
$.post(
"emailinfo.php",
$( "#ContactForm" ).serialize(),
function( data ) {
/* do things with responce */
} );
What I usually do in this scenario is ajax, but if you do not want to use ajax, you can simply add 'return false' for it not to be redirected when using form submit:
function verify()
{
if(document.getElementById("name").value=="" ||document.getElementById("email").value=="")
{
alert("Please enter a name and an email.");
}
else
{
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
return false;
}
}

Form Post data using Ajax and jquery

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! }

Categories