Display reesults from another html on same page using jquery web - javascript

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.

Related

Ajax in django form

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>

Issue with action and onsubmit in form

I have a form in HTML where I have used onsubmit to validate input and action to call the URL on form submit. This is my HTML code:
<form method="POST" onsubmit="return validateInput();" action="editConf" id="edit-form">
// HTML Form code
<div class="modal-footer">
<p id = "edit-footer" align="center"> </p>
<button type="reset" onClick="resetForm()" class="btn btn-secondary" data-dismiss="modal" >Cancel</button>
<button type="submit" class="btn btn-primary">Save changes</button>
</div>
This is my script code:
function validateInput() {
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: { data: document.getElementById('data') },
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
return true;
} else {
return false;
}
}
});
I am facing the issue that the URL in action completes its execution first so even if the form is not valid it is submitting. How to solve this issue ?
Since $.ajax is asynchronous, you can't use the return value of the success function.
You need to prevent the default submission immediately, then call submit() in the success function.
Also, in the data: option you need to get the value of an input, the input element itself.
function validateInput() {
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: {
data: $("#data").val()
},
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
$("#edit-input").submit();
}
}
});
return false;
}
To prevent this from looping infinitely, because submit() runs the same validation function first, remove onsubmit from the form, and move it to the submit button.
<button type="submit" class="btn btn-primary" onclick="return validateInput();">Save changes</button>
You should prevent default event if you want to have custom async validation.
<form id="myForm" method="POST" action="editConf" id="edit-form">
fix your script to
$('#myForm').on('submit', validateInput)
function validateInput(event) {
event.preventDefault(); //Here we stoped defauld submit event
// some validation code
$.ajax({
url: "validate_credentials",
type: 'POST',
data: { data: document.getElementById('data') },
dataType: 'json', // added data type
success: function(res) {
if (res && valid) {
$("#bigerror").innerHTML = res;
return true;
} else {
return false;
}
}
});
Now the form won't be submitted. But now you have to think how you want to send data of the form to the server. There are several variants.
1) You can get form data and send it with ajax imitating the form
2) You can store a flag somewhere marking your form valid and if it is valid don't stop submit the form from your script and don't stop the event.

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

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 to submit a form through ajax in safari browser in grails

I am trying to submit a form through ajax function while button
but on safari browser its submitting like a normal form submitting.
and In other browser its working properly through ajax function
<g:form action="addEmpHistory" name="formNew" method="post">
<button id="submitBtn" name="submitBtn" onclick="submitform(formNew);"></button>
</g:form>
//Ajax code
function submitform(data){
$("#"+data).submit(function(event) {
new Event(event).preventDefault();
event.preventDefault();
$.ajax({
type: 'POST',
url: '/user/addUSer',
data: $('#'+data).serialize(),
success: function (data) {
location.reload();
}
});
});
}
Seen as you are using jQuery, consider removing onclick
<form action="addEmpHistory" id="formNew" name="formNew" method="post">
<button id="submitBtn" name="submitBtn">Submit</button>
</form>
and replacing your submitform function with jQuery event binding, something like:
$(document).ready(function() {
$("#formNew").submit(function() {
$.ajax({
type: 'POST',
url: '/user/addUSer',
data: $("#formNew").serialize(),
success: function(data) {
alert(data);
}
});
return false; // prevent actual form submit
});
});

Categories