I want to clear all inputs value whenever result succeed.
I have tried unbind from Jquery but doesn't get any result
so any suggestion would be great
<html>
<head>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.1.1.min.js"></script>
</head>
<body>
<div id="Result"></div>
<form id="Form" action="File.php" autocomplete="off">
<input type="text" name="Name" />
<br/>
<input type="text" name="Pass" />
<br/>
<input type="button" id="Submit" value="Run Code" />
</form>
<script>
$(document).ready(function()
{
$("#Submit").click(function()
{
$("#Form").submit(function(e)
{
$.ajax(
{
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function(data, textStatus, jqXHR)
{
$("#Result").html(data);
}
});
e.preventDefault();
});
$("#Form").submit();
});
});
</script>
</body>
</html>
please feel free to ask for more details
You can clear all inputs using
$("input[type='text']").val('');
You are binding an event handler inside another event handler. Each time the button is clicked, a new handler is attached to the form. So, after n number of clicks, you'll be sending n number of ajax requests, as you can see here
Ideally, your code should be
$(document).ready(function () {
$("#Submit").click(function () {
$("#Form").submit();
});
$("#Form").submit(function (e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: "POST",
data: $(this).serializeArray(),
success: function (data, textStatus, jqXHR) {
$("input[type='text']").val(''); // reset the input values
$("#Result").html(data);
}
});
});
});
Demo.
Side note: You can simply use a submit button instead of triggering the form submission manually like this
Here you go:
$(document).find('input').each(function(){
$(this).val('');
});
More info on: http://api.jquery.com/val/
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>
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;
});
});
I have two forms for buy now and for pincode when I click buynow button sending request through ajax and same thing is done for pincode form also.
HTML
<form method="POST" action="/cart/add" id="myForm">
.....
....
<input type="button" class="buyNowBtn" id="btnBuyNow"/>
</form>
<form action="#">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
In the same buynow click event I need to trigger a pincode submit button, so I did this
(document).on('click', '#btnBuyNow', function (e) {
....
....
$("#pinCheckTest").trigger('click');
....
});
the above trigger event is successfully calling pincode click event
$('#pinCheckTest').click(function () {
$.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {
}
else{
}
}
});
but I need to get ajax response back to trigger event so that I can do some operation is it possible?
something like
(document).on('click', '#btnBuyNow', function (e) {
....
....
$var output=$("#pinCheckTest").trigger('click');//I need to get ajax response back to this click
if(output=='true'){
......
}else{
.....
}
....
});
You can define a variable outside of both click handlers, when .trigger() is called, assign $.ajax() to variable, use .then() within first click handler to process results of $.ajax() call.
Note, included event.preventDefault() to prevent submission of <form>, as pointed out by #IsmailRBOUH
var dfd;
$(document).on('click', '#btnBuyNow', function (e) {
e.preventDefault();
....
....
$("#pinCheckTest").trigger('click');
if (dfd) {
dfd.then(function(output) {
// do stuff with output
console.log(output)
})
}
....
});
$('#pinCheckTest').click(function (e) {
e.preventDefault();
dfd = $.ajax({
type: 'GET',
url: url,
success: function (output) {
if (output == 'true') {}
else{};
}
})
});
var dfd;
$("#first").click(function() {
$("#second").trigger("click");
if (dfd) {
dfd.then(function(data) {
alert(data)
})
}
})
$("#second").click(function() {
// do ajax stuff
dfd = $.when("second clicked")
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="first">first button</button>
<button id="second">second button</button>
Since you are binding the click event to a button inside form you have the prevent the default behaviour which is 'submit the form'. Change you code to :
$('#pinCheckTest').click(function (e) {
e.preventDefault();
//Your ajax call
});
Here is a demo to clarify the difference https://jsfiddle.net/qvjjo3jk/.
Update1:
Add an id to your form:
<form action="#" id="pinCheckForm">
<input type="text" id="pinCheck" class="pinCheck" placeholder="enter pin code" />
<button class="btn btn-info" id="pinCheckTest"> Check</button>
</form>
Then:
$('#pinCheckForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: url,
data: $(this).serialize(), //Sends all form data
success: function(output) {
if (output == 'true') {} else {}
}
});
});
Why does the below script cause the form to submit twice? I can't figure this out, even after trying other solutions posted around the internet. Submitting twice is causing duplicate entries in the database. Thank you in advance for looking into this!
<script type="text/javascript">
$(document).ready(function(){
$('#form-error').hide();
$("#form-submit").click(function(){
$("#form").submit();
});
});
$('#form').submit(function(e) {
register();
e.preventDefault();
});
function register()
{
jQuery.ajax({
method: 'POST',
url: 'actions/add.php',
data: $('#form').serialize(),
dataType:'json',
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
}
function hideshow(el,act)
{
if(act)
{
$('#'+el).hide(0).slideDown(500, 'linear');
}
else $('#'+el).hide();
}
function error(act,txt)
{
if(txt)
{
$('#form-error').html(txt);
}
$('#form-error').hide(0).slideDown(500, 'linear');
}
</script>
HTML Form:
<form id="form">
<p>First Name:</p>
<input type="text" name="firstname" />
<p>Last Name:</p>
<input type="text" name="lastname" />
<p>E-Mail Address:</p>
<input type="text" name="emailaddress" />
<p>Sequence Assignment:</p>
<select name="sequence">
<option value="1">Default Sequence</option>
</select>
<button id="form-submit">Add User</button>
<p id="form-error"></p>
</form>
There are duplicated event listeners for the submit event:
1. When submit button clicked:
$("#form-submit").click(function(){
$("#form").submit();
});
2. When form is submitted:
$('#form').submit(function(e) {
register();
e.preventDefault();
});
You need only one of them.
Change your code like:
<script type="text/javascript">
$(document).ready(function(){
$('#form-error').hide();
$('#form').submit(function(e) {
register();
e.preventDefault();
});
});
function register()
{
.
.
.
I had a similar issue to this. If you just single click on the button does it enter duplicate data?
The way I got around it is once the click happened I disabled the button until after the Ajax call.
function register()
{
//disable button
jQuery.ajax({
method: 'POST',
url: 'actions/add.php',
data: $('#form').serialize(),
dataType:'json',
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
error(1,msg.txt);
}
}
});
//Enable Button
}
Another option would be to do some checks in the php code that submits it to the database to see if that data already exists.
I want to call a function when I press enter in the input field. The problem is, that it just reloads the page at the moment, and doesn't call the JavaScript. The JavaScript works without any problems, when I'm pressin the button. Now I want to have the same result, when I press enter.
This is my form
<form onSubmit="changeView()">
<input type="text" value="London" name="region" id="region">
<input type="button" onClick="changeView()" name="mySubmit" value="Search" >
</form>
I also tried to put this into the text field onKeydown="Javascript: if (event.keyCode==13) changeView();
But it didn't really help.
This is my JavaScript function
function changeView(){
var region = document.getElementById('region').value;
$.ajax({
type: 'GET',
url: 'webservice.php',
data: {region: region},
success: function(response, textStatus, XMLHttpRequest) {
alert("SUCCESS");
map.panTo(new L.LatLng(response[0].lat,response[0].lon));
}
});
return false;
}
HTML:
<form action="webservice.php" method="post">
<input type="text" value="London" name="region" id="region">
<input type="submit" name="mySubmit" value="Search" >
</form>
Javascript:
$('#region').on('keydown', function(e) {
if (e.which === 13) {
$(this).parent('form').submit();
}
});
$('.form').on('submit', function(e) {
var self = $(this);
$.ajax({
type: self.attr('method') ,
url: self.attr('action'),
data: {region: $('#region').val()},
success: function(response, textStatus, XMLHttpRequest) {
alert("SUCCESS");
map.panTo(new L.LatLng(response[0].lat,response[0].lon));
}
});
e.PreventDefault();
return false;
});
it looks like you're using jQuery, have you thought about just biding an event to the text box
something like this
$(document).ready(function(){ // binds when the document has finished loading
$("#region").on('keypress', function(e){
if (e.which === 13){ // enter key
changeView();
}
});
});