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();
}
}
});
});
Related
I want it to only "reload" into the #searchuserc. I have searched so much information but I can't solve the problem.
$(document).ready(function() {
$("#onlineusers").load("online.php");
$("#searchuserc").show();
setInterval(function() {
$("#onlineusers").load("online.php");
}, 5000);
$(".search").click(function() {
$("#onlineusers").hide();
e.preventDefault(); // Prevent Default Submission
$.ajax({
url: 'searchuser.php',
type: 'POST',
data: $(this).serialize(), // it will serialize the form data
dataType: 'html'
})
.done(function(data) {
$('#searchuserc').fadeOut('slow', function() {
$('#searchuserc').fadeIn('slow').html(data);
});
})
.fail(function() {
alert('Ajax Submit Failed ...');
});
});
});
this is my HTML file
<form method="POST">
<input type="text" id="searchuser" name="searchuser" placeholder="Sök efter en användare..." />
<input type="submit" class="search" name="searchbtn" value="Sök" />
</form>
<div id="searchuserc">
</div>
Instead of
$(".search").click(function() {
...
use
$(".search").closest("form").submit(function(e) {
...
Code inside the handler can stay the same.
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");
}
});
};
I have a html file where users can input a value.
I wrote a script in PHP that checks if this value is present in the databse. If it's present it returns
{"active":true}
Now my goals is that when the user inputs their value and submit they will be redirected to a certain page if this active is true. If it's false they should see an error message.
So here's what I've tried with my AJAX call:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
data: data,
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
Here is my HTML:
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="#" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue" />
</form>
For some reason I get an error:
Uncaught ReferenceError: data is not defined
I am new to AJAX and I am not sure if what I am trying is correct.
Any help would be greatly appreciated!
Thanks in advance.
Can you try:
$(".aanmeldenmodal").submit(function(e){
e.preventDefault();
I am updating my answer in whole
<html>
<body>
<form action="api/check.php" id="requestacallform" method="GET" name="requestacallform" class="formcheck">
<div class="form-group">
<div class="input-group">
<input id="txt1" type="text" class="form-control" placeholder="Jouw subdomein" name="name"/>
</div>
</div>
<input type="submit" value="Aanmelden" class="btn btn-blue checkform" />
</form>
</body>
</html>
jQuery part is like
$("document").ready(function () {
$("body").on("click", ".checkform", function (e) {
e.preventDefault();
var request = $("#txt1").value;
$.ajax({
type: 'GET',
url: 'ajax.php',
data: {request: 'request'},
dataType: 'json',
success: function (data) {
if(data.active==true){
alert("success");
}else{
alert("failure");
}
}
});
});
});
ajax.php should be like this
if(isset($_GET['request'])){
//check for the text
echo json_encode($arr);
}
In api/check.php
You can pass data in json format
$json = json_encode($data);
retrun $json;
You can also not share any data so You can remove data from jQuery.
data:data
Your Jquery look like this:
$("document").ready(function(){
$(".checkform").submit(function(e){
e.preventDefault();
$.ajax({
type: "GET",
dataType: "json",
url: "api/check.php",
success: function(data) {
if(data.active=="true"){
alert("success");
location.href="where_you_want";
}else{
alert("failure");
}
}
});
return false;
});
});
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;
});
I am trying to find the best way to send variables from Javascript to PHP without GET method. I found a way to send through POST method with AJAX:
<form method="POST" id="post" enctype="multipart/form-data">
<input type="file" name="image_upload[]" id="img1" />
<input type="file" name="image_upload[]" id="img2" />
<input type="file" name="image_upload[]" id="img3" />
<input type="text" name="description" id="description" />
<textarea class="intext" name="editor" id="editor"></textarea>
<input type="text" name="state" id="state" disabled="true" />
<input type="text" name="city" id="city" disabled="true" />
<input type="submit" id="submit" />
</form>
And I am trying to submit the form with jQuery:
$('#post').submit(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "cpage.php",
data: {
'variable1': 'content var1',
'variable2': 'content var2'
},
success: function () {
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
NOTE: the variable "position" has been declared before and works fine.
Result: I get "Internal Server Error" in the alert. Any ideas?
First of All - show us what is going on the server side.
And now about the files being sent:
You should use FormData element for file submit threw Ajax, its not supported by old browser, the browsers that would support this are : ie>9, chrome > 7, opera > 12 safari >5, android > 3 gecko mobile > 2, opera mobile >12.
Use something like this:
$('#post').submit(function (event) {
event.preventDefault();
if( window.FormData !== undefined ) //make sure that we can use FormData
{
var formData = new FormData($('form#post'));
$.ajax({
type: "POST",
url: "cpage.php",
data: formData ,
//Options to tell jQuery not to process data or worry about content-type.
cache: false,
contentType: false,
processData: false,
success: function (data) {
console.log(data); // <- for debugging
$('#post'), $('form').unbind('submit').submit();
},
error: function (name, err, desc) {
alert(desc);
}
});
} else {
//fallback
}
});
As you can see I added console.log(data), try looking at the returned data to identify any other problems.