I was making Wikipedia viewer, and I implemented Wikipedia title search ajax calls were working fine until I added forms tag around input & button tag.
<form class="pure-form">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="submit" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</form>
My ajax code is:
$("button").click(function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp){
console.log(JSON.stringify(resp));
},
error: function(err){
console.log("ERR")
}
});
});
I was doing all this on codepen: http://codepen.io/theami_mj/pen/KMKPvZ
Use type='button', type='submit' will submit the form and page will be unloaded.
$("button").click(function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp) {
console.log(JSON.stringify(resp));
},
error: function(err) {
console.log("ERR")
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<form class="pure-form">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="button" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span>Go!
</button>
</form>
I feel the problem was with form submission with submit button type added. Just add one line of code i.e. e.preventDefault() to prevent default action of your button which is submitting the form, so that it would not submit the form
$("button").click(function(e) {
e.preventDefault()
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Manoj";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp) {
console.log(JSON.stringify(resp));
},
error: function(err) {
console.log("ERR")
}
});
});
UPDATED FIDDLE
You should attach you click handler / AJAX call to the form's onsubmit event handler:
<form class="pure-form" onsubmit="myAjaxCall">
<input type="text" id="txtff" class="pure-input-rounded" placeholder="Search for...">
<button type="submit" class="pure-button"><span class="glyphicon glyphicon-search" aria-hidden="true"></span></button>
</form>
This would be your script (just created a function called myAjaxCall instead of attaching a click event handler).
myAjaxCall = function() {
var url = "https://en.wikipedia.org/w/api.php?action=query&format=json&list=allpages&aplimit=5&apfrom=Albert";
$.ajax({
url: url,
jsonp: "callback",
dataType: "jsonp",
success: function(resp){
console.log(JSON.stringify(resp));
},
error: function(err){
console.log("ERR")
}
});
}
http://www.w3schools.com/jsref/event_onsubmit.asp
This is normal behavior. button with type submit will send the form. Try to just replace type="submit" with type="button".
You should get rid of the form, or you should add
$("form").on("submit", function(e){
e.preventDefault();
return false;
});
To your JS code, to prevent the default behaviour of the form.
Alternatively, you could move all the logic from your button click event here, too:
$("form").on("submit", function(e){
e.preventDefault();
// your AJAX call here
return false;
});
Related
I am trying to build my first website and I encountered a problem that I couldn't resolve by now. So, when an user wants to add an item to the cart, or to increment the quantity, I want to prevent the page from refreshing when hitting the submit button. I've looked for many answers, I tried to apply Ajax/JQuery, but unsuccessful.
Here is my code:
html
<form action="{% url 'cart-add' %}" method="GET" id="myform">
{% csrf_token %}
<label>
<input type="hidden" name="{{ product.pk }}">
<input type="number" max="{{ product.quantity }}" min="1" name="quantity" value="1">
<button type="submit" value="">Add to chart</button>
</label>
</form>
Ajax/JQuery script
<script type="text/javascript">
$(document).ready(function () {
$('myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("myForm").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
When I hit add-to-cart submit button, it throw me to the "cart.html". I do not want to do that, instead I want to prevent that and throw a message to the user saying that his/her item has been successfully added.
Can somebody help me? Thank you very much for your time. I much appreciate it!
You need to return false, otherwise, the function with carry on with the default behaviour after the function is complete:
<script type="text/javascript">
$(document).ready(function () {
$('#myform').on('submit', function(e) { // fix typo
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("myForm").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
// Prevent function from saving
return false;
});
});
</script>
Update: looking at the jQuery documentation, I don't know if return false is necessary if e.preventDefault() is present.
Is $('myform') a typo? Should it be $('#myform')?
To reference a HTML's ID, use a #idName.
To reference a HTML class, use a .className
To reference a HTML element, just enter name
$('myform') is looking for a <myform></myform> element.
$('#myform') is looking for a <... id="myform"></...>
$('.myform') is looking for a <... class="myform anotherRandomClass"></...>
Your form is submitting normally because your jquery selector is wrong. You have to change $('myform') to $('#myform')
<script type="text/javascript">
$(document).ready(function () {
$('#myform').on('submit', function(e) {
e.preventDefault();
$.ajax({
url : $(this).attr('action') || window.location.pathname,
type: "GET",
data: $(this).serialize(),
success: function (data) {
$("#myform").html(data);
},
error: function (jXHR, textStatus, errorThrown) {
alert(errorThrown);
}
});
});
});
</script>
In ASP.NET MVC Project, i want button to not make submit if the result come from AJAX code is false.
But the it always make submit.
That is the code:
#using (Html.BeginForm("Add", "Category", FormMethod.Post))
{
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
}
and that is Javascript code:
$('#myid').on('click', function(event) {
var data = {};
data.CategoryName = $("#myCategoryNameId").val();
data.CategoryID = $("#myCategoryId").val();
$.ajax({
type: 'POST',
data: JSON.stringify(data),
url: '/Category/ValidateCategoryName',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (!result) {
event.preventDefault();
}
}
});
});
I'd replace the submit button input element with a button element so that clicking the button will trigger the onclick event without submitting the form. Then when you get the ajax response you can conditionally use jQuery to submit the form. This might require some tinkering to get the form from the onclick but it'll prevent you from submitting the form too early like I suspect your problem is.
#using (Html.BeginForm("Add", "Category", FormMethod.Post))
{
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<button class="btn btn-primary" id="myid">Add</button>
}
and
$('#myid').on('click', function(event) {
var data = {
CategoryName: $("#myCategoryNameId").val(),
CategoryID: $("#myCategoryId").val()
};
$.ajax({
type: 'POST',
data: JSON.stringify(data),
url: '/Category/ValidateCategoryName',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result) {
$('#myid').closest('form').submit();
}
}
});
});
To elaborate on my comment above. change
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
to
<input class="btn btn-primary" id="myid" type="button" value="Add" />
And in your success function, change
if (!result) {
event.preventDefault();
}
to
if (result) {
$('#myid').closest("form").submit();
}
This way you will only submit the form when result is true, it the ajax call fails or result is false then the form won't be submitted.
DISCLAIMER: The code above may not work, but i hope you get the generel idea.
What I know from a very long time is the Form default redirect action will not wait until ajax returned its result .. So you can use a boolean variable to control that .. see the next code
$(document).ready(function(){
var DefaultFormAction = false; //set the default form action to false
$('form').on('submit' , function(e){
var $this = $(this);
if(DefaultFormAction == false){ // when the default action is false
e.preventDefault(); // prevent the default redirect
setTimeout(function(){ // I use setTimeout here for testing .. Use the next code in your ajax success
DefaultFormAction = true; // return default action to true
$this.submit(); // then submit the form again
} ,10000);
console.log('This result when default is false you will go to the default form action after 10second');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
</form>
To test the Form default redirect action will not wait until ajax returned its result you can use e.preventDefault() inside the setTimeout and even you make a time is 1ms without $this.submit() it will still use the default redirect
$(document).ready(function(){
var DefaultFormAction = false; //set the default form action to false
$('form').on('submit' , function(e){
var $this = $(this);
if(DefaultFormAction == false){ // when the default action is false
setTimeout(function(){ // I use setTimeout here for testing .. Use the next code in your ajax success
e.preventDefault(); // prevent the default redirect
} , 1);
console.log('This result when default is false you will go to the default form action after 10second');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form>
<input name="CategoryID" id="myCategoryId" type="text" value="0" />
<input name="CategoryName" id="myCategoryNameId" type="text" value="" />
<input class="btn btn-primary" id="myid" type="submit" value="Add" />
</form>
Cleanest way to do so:
$(document).on('submit','form' function(event) {
event.preventDefault();
event.stopImmediatePropagation();
$this = $(this);
var data = {};
data.CategoryName = $("#myCategoryNameId").val();
data.CategoryID = $("#myCategoryId").val();
$.ajax({
type: 'POST',
data: JSON.stringify(data),
url: '/Category/ValidateCategoryName',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
if (result) {
$this.submit();
}
}
});
});
I have a form in my code, and I would simply like to display the fields from that form on my webpage, using AJAX. I tried e.preventDefault() and return false but none of these seem to be working.
I trigger the submit through a button click event.
My Jquery code:
$("body").on('click', '#save', function (e) {//button which triggers submit
$('form').submit();
e.preventDefault();
});
$('#form').on('submit', function(e){
e.preventDefault();
e.stopPropagation();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
type: 'POST',
url: '/results',
data: $('#form').serializeArray(),
success: function (data) {
//if no error from backend validation is thrown
return false;
$('#tabShow').html(data);
},
error: function () {
alert('error');
}
});
My form html is : <form class="form-horizontal" method="POST" action="/results" id="form">
In my web.php:
Route::post('/results', function() {
$m=Request::all();
var_dump($m);
});
The problem with this code is that it refreshes the current page that I am on.
I have a save button, which should submit the form. I can't use a type submit because of my other functions.
Thank you for the help.
Do the request in the Save button click event, eg.
HTML
<form id="contact-form" class="form-horizontal" action="/echo/html/" method="post">
<!-- many fields -->
<button id="save" class="btn btn-primary btn-lg">Submit</button>
</form>
JS
$("body").on('click', '#save', function (e) {//button which triggers
var contactForm = $('#contact-form');
e.preventDefault();
$.ajaxSetup({
beforeSend: function(xhr) {
xhr.setRequestHeader('X-CSRF-TOKEN', $('meta[name="csrf-token"]').attr('content'));
}
});
// Send a POST AJAX request to the URL of form's action
$.ajax({
type: "POST",
url: contactForm.attr('action'),
data: contactForm.serialize()
})
.done(function(response) {
console.log(response);
})
.fail(function(response) {
console.log(response);
});
});
Working demo
Try using return false at the end of your script (also remove preventDefault() )
I'm working on a web application, and i have a problem with a return of Ajax.
I can see the result of the return of AJAX, but my problem is that this result appears and then disappears. I found a solution that is return false, the problem being that once the display is done and I return false, my div remains on the page but I can not reuse the button on which I made my onclick (to call my javascript function and so the ajax call).
If someone has a solution.
This is the code :
<input class="Admin-Bouton" type="submit" onclick="affOtp();return false" value="Générer" form="formParametres" />
<div id="syntheseOTP"></div>
function affOtp() {
$(function(){
$.ajax({
url: 'vue/ressources/affOtp.php',
type: 'POST',
dataType: 'html',
data: { idEmploye: nom },
success: function(msg) {
console.log(msg);
document.getElementById("syntheseOTP").innerHTML = msg;
},
error: function(resu, statut, erreur) {
console.log(erreur);
alert("papa");
}
});
});
};
That happen because the form will be submited and the page refresh, you could avoid that by using type button instead of submit :
<input id="Admin-Bouton" class="Admin-Bouton" type="button" onclick="affOtp();return false" value="Générer" form="formParametres" />
I suggest to attach the event click in the js code instead of inline-event onclick :
$('#Admin-Bouton').on('click', affOtp);
HTML will be like :
<input id="Admin-Bouton" class="Admin-Bouton" type="button" value="Générer" form="formParametres" />
Hope this helps.
Edit: Left out "return" before affOtp();
<input class="Admin-Bouton" type="submit" onclick="return affOtp();" value="Générer" form="formParametres" />
<div id="syntheseOTP"></div>
function affOtp() {
$(function(){
$.ajax({
url: 'vue/ressources/affOtp.php',
type: 'POST',
dataType: 'html',
data: { idEmploye: nom },
success: function(msg) {
console.log(msg);
document.getElementById("syntheseOTP").innerHTML = msg;
},
error: function(resu, statut, erreur) {
console.log(erreur);
alert("papa");
}
});
});
return false;
};
Since none of the answers are still working for you, I would recommend you to do following changes (keeping in mind you don't want to change type="submit").
<input id="AjaxButton" class="Admin-Bouton" type="submit" value="Générer" form="formParametres" />
<!-- remove onlick attribute and add a Id attribute in above line -->
<div id="syntheseOTP"></div>
Now make sure you add a click event handler in your scripts.
$('#AjaxButton').on('click',affOtp);
function affOtp(e) { // add e as input parameter
// removed unnecessary wrapper
e.preventDefault(); // this will now stop the click event.
$("#syntheseOTP").html("Loading...."); // add loading text into div
$.ajax({
url: 'vue/ressources/affOtp.php',
type: 'POST',
dataType: 'html',
data: { idEmploye: nom },
success: function(msg) {
console.log(msg);
$("#syntheseOTP").html(msg); //refactored to use jquery syntax
},
error: function(resu, statut, erreur) {
console.log(erreur);
alert("papa");
}
});
};
My form:
<form class="form-inline signup" action="php/signupForm.php" role="form" id="signupForm">
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Email address">
</div>
<div class="form-group">
<button type="submit" class="btn btn-theme ladda-button" data-style="expand-left">
<span class="ladda-label" id="notice">Get notified!</span>
</button>
</div>
</form>
the end of my php script
$response = array(
"status" => $status,
"message" => $message
);
echo json_encode($response);
My page is receiving data like:
{"status":0,"message":"This email is already on list!"}
using JS I need to parse that data and then update text within an element.
<span id="notice">Get notified!</span>
here's my script which doesn't work, after senging form data to my php script I get a white screen that shows the json strong
$(document).ready(function() {
$.ajax({
dataType: 'json',
$('#notice').text(data.message);
});
});
You have to handle the response in a callback.
$(document).ready(function() {
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
data: $(this).serialize(),
url: $(this).attr('action'), // Or the path of the PHP file
dataType: 'json',
}).done(function(response) {
$('#notice').text(response.message);
});
});
});
See the related docs here
That ajax call is not well formed, missing success callback and url e.g:
$(document).ready(function () {
$.ajax({
url: '/the/url/where/your/data/comes/from/',
dataType: 'json',
success: function (data) {
$('#notice').text(data.message);
}
});
});
Your code as is, is just executing at page load and not on submission of a form. You need to attach an onsubmit event, prevent the default action of doing the form submit and do your ajax call in there. Also your ajax call itself was malformed
$("#yourFormID").submit(function(e){
e.preventDefault();
$.ajax({
url:"/urlToServerScript",
data:{} //any form data the script needs you should be put here,
dataType:"json" //type of response the server will output
}).then(function(data){
$('#notice').text(data.message);
});
});