I have a servlet to check validity of a user in my DB. I have a field which takes the username and on blur an ajax post request is made. But in the browser console I am getting the following error:
POST http://localhost:8084/Project/[object%20Object] 404 (Not Found)
Here is the code I am trying with javascript/jquery
function checkValidity(str){
$.post({
url: "/checkValidity.do",
data: {"paramType":"username","field":str},
sucess: function(data){
if(JSON.parse(data.exists)){
alert("Account already exists");
return false;
} else {
alert("Not found");
}
}
});
}
I cannot find where I am doing wrong.
Thank you.
change
$.post({
to
$.ajax({
and add type:'POST'
So complete code would be.
function checkValidity(str)
{
$.ajax(
{
url : "/checkValidity.do",
data : {
"paramType":"username",
"field":str
},
type : 'POST',
sucess : function(data)
{
if(JSON.parse(data.exists)){
alert("Account already exists");
return false;
} else {
alert("Not found");
}
}
});
}
Related
I have form that when submitted it uses AJAX and its posts data to reg1.php. I want it to do some bits with the data posted and then redirect to a page to use it.
When I redirect after how do I post the posted data with it to list.php? Or is there another way of doing it?
<script>
$(document).ready(function () {
$(".loginform").submit(function() {
data = $("#loginform").serialize();
$.ajax({
type: "POST",
url: "reg1.php",
data: data,
success: function(result) {
if (result == 'success') {
//$('.output_message').text('Message Sent!');
//$('#loader').hide();
alert("SUCCESS");
window.location.replace("list.php");
} else {
//$('.output_message').text('Error Sending email!');
alert("NO SUCCESS");
//$('#loader').hide();
}
}
});
return false;
});
});
</script>
I have a form in an Asp.net MVC 5 project which has a Submit button. When the Submit button is clicked, I want to do the following:
Perform client=side validation using jQuery on various fields (required fields have been filled, email format is valid, etc...). That part is working fine.
Make an Ajax call that will perform some server side validation by calling an action from the controller and return a JSON response. The response contains a Success property and Errors property which contains a list of errors.
The Success property will return true if no error are found and the Errors property will be null. If errors are found the Success property is returns false and the Errors property contains a list of relevant errors.
I'm calling '\ApplicationForm\Validate' action from my ApplicationForm controller and this part is working fine.
When no errors are found in part 2, I want my form to be submitted as normal and call the '\ApplicationForm\Index' action so that my data can then be added to my database. I cannot get this part to work!!
The Submit button is defined as follows:
<div class="form-group">
<div>
<input type="button" id="btnApply" value="Apply" class="btn btn-primary" />
</div>
</div>
My JavaScript code is defined as follows:
$('#AppllicationForm').submit(function () {
if (!$(this).attr('validated')) {
if ($(this).valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
$('#ApplicationForm').attr('validated', true);
$('#ApplicationForm').attr('action', '/ApplicationForm/Index')
.submit();
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
}
}
return false;
});
The above is using a regular button but I've also tried to define its type as Submit but to no avail.
I know similar questions have been posted in the past but I cannot find one that has actually helped me out to find a resolution to my problem, so please bear with me and do not mark this question as a duplicate unless there is an actual question/answer with an actual resolution to my problem. Much appreciated!
The closest scenario I found to what I'm trying to achieve is can be found from this article on SO: Submit a form from inside an ajax success function that checks the values
I've been trying so many different things at this stage but nothing is working out. I either don't get the Index action to be called after the ValidateForm action, or either one or the other action is called or the only Index action is called or my model gets messed up, and the list goes on.
I'm clearly not doing this correctly or missing something but I'm at a complete stand still for now. I'm hoping that it will be something silly that I've missed and hopefully someone will clarify this for me.
Any help would be greatly appreciated.
Try it out :
$('#btnApply').click(function (e) {
alert('submit');
e.preventDefault();
var form = $('form'); // change selector your form
if (!form.attr('validated')) {
if (form.valid()) {
$.ajax({
type: "POST",
data: form.serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
console.log('response received.');
if (response != null && response.success) {
console.log('No validation errors detected.');
form.attr('validated', true);
form.attr('action', '/ApplicationForm/Index')
.submit();
} else if (response != null && !response.success) {
console.log('Validation errors detected.');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
},
error: function (response) {
console.log(response);
$('validationSummary').hide();
}
});
}
}
});
Please try it out:
$('#btnApply').on('click', function (e) {
e.preventDefault();
var form = $( "#AppllicationForm" );
if (!form.attr('validated')) {
if (form.valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
form.attr('validated', true);
form.submit();
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
}
}
return false;
});
Your form action attribute will be '/ApplicationForm/Index'. When you click on the button, you make the validation and if everything is OK, then submit the form.
Please check below solution :
$('#btnApply').on('click', function (event) {
if ($('form').valid()) {
event.preventDefault();
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
$('validationSummary').show();
if (response != null && response.success) {
console.log('No Validation errors detected');
$('#ApplicationForm').attr('validated', true);
$('form').submit(); // Here form will be submmited to Index action.
return true;
}
else if (response != null && !response.success) {
console.log('Validation errors detected');
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
console.log(response);
return false;
}
});
});
And decorate your ValidateForm method with [HttpPost] attribute.
I thought I'd share my solution as I ended up hiring a freelancer to have a look at it as I was under time constraint and could not afford to spend any more time on this.
How did it fix it? He added a second ajax call from within the first one. The annoying (and costly!) part is that I did try this but I had one important missing line i.e. var formValidated = $('#AppllicationForm').serialize();.
After these changes were made, I just had to rejig some of my logic regarding which div should be displayed and/or hidden but bar that it was pretty standard stuff.
Here's the final code that worked as expected:
$('#AppllicationForm').submit(function () {
if ($(this).valid()) {
$.ajax({
type: "POST",
data: $(this).serialize(),
url: "/ApplicationForm/ValidateForm",
dataType: 'json',
success: function (response) {
if (response != null && response.success) {
var formValidated = $('#AppllicationForm').serialize();
$.ajax({
url: '/ApplicationForm/Index',
data: formValidated,
type: 'POST',
success: function (result) {
$('#mainDiv').hide();
$('#Congrats').show();
}
});
return true;
}
else if (response != null && !response.success) {
var errors = response['errors'];
displayValidationErrors(errors);
window.scrollTo(0, 0);
}
return false;
},
error: function (response) {
$('validationSummary').hide();
return false;
}
});
}
return false;
});
Hope this helps others.
I am running an ajax request, then once I get the result back I choose if it should be continued or if the form should not submit. I am checking if the email exists.
Issue is I moved the return false out of the success: as it was not working there and now in a seperate function it is not working either. I get the alert("FALSE"); but the form still submits which is no good as I want an error pop up to happen.
$.ajax({
type: "POST",
url: "/ajax/checkdata.php",
data: "email="+email,
success: function(data){
var returned = true;
if (data == "Email Exists") {
returned = false;
} else {
}
emailModal(returned);
}
})
function emailModal(result){
if (result) {
alert("TRUE");
} else {
alert("FALSE");
return false;
}
}
You'd have to always prevent the form from submitting, and then in the check for the email figure out wether to show an error or submit the form using the native submit handler
$('form').on('submit', function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: "/ajax/checkdata.php",
data: {email : email},
context: this
}).done(function(data) {
if (data == "Email Exists") {
alert(data);
} else {
this.submit();
}
});
});
How do I alert a json_encode() message and reload the page? The function below only displays an undefined alert message
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
data = $.parseJSON(data);
alert(data.response);
location.reload();
}
});
});
You're trying to get a undefined index response
Provided that your PHP script returns:
{
"msg": "<your-message-here>"
}
In your javascript you can do it:
$.ajax({
type : "POST",
url: "transferProduct.php",
dataType: 'json',
success : function(response) {
alert(response.msg);
location.reload();
}
});
Use code in this way
transferProduct.php
if($result1 == false)
$response['msg'] = "Transfer failed due to a technical problem. Sorry.";
else
$response['msg'] = "Successfully transferred";
echo json_encode($response);
code page
$("#transfer").click(function() {
$.ajax({
type : "POST",
url : "transferProduct.php",
data : {},
success : function(data) {
datas = $.parseJSON(data);
alert(datas.msg);
location.reload();
}
});
});
or you can use $.getJSON in place of $.ajax
$("#transfer").click(function() {
$.getJSON("transferProduct.php",function (data){
alert(data.msg);
location.reload();
});
});
I think you should format the return to correctly identify in the background:
{"success":true,"message":"---------"}
then in JavaScript: data.message
I am trying simple login form with username, password fields in jquery mobile. Username and password should validate from ajax page. In my system i am able to get response perfectly. When convert my code to .apk uging phonegap, my mobile unable to receive response from ajax page. Any code inside success function is not working, Directly it goes to error function. What am i doing wrong?
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() {
if($('#username').val().length > 0 && $('#password').val().length > 0){
$.ajax({
url : 'liveurl/check.php',
data: {action : 'login', formData : $('#check-user').serialize()},
type: 'post',
beforeSend: function() {
$.mobile.loading(true); },
complete: function() {
$.mobile.loading(false);
},
success: function (result) {
if(result.status == "success"){
resultObject.formSubmitionResult = result.uname;
localStorage["login_details"] = window.JSON.stringify(result);
$.mobile.changePage("#second");
}else{
$.mobile.changePage("#login");
alert("incorrect login");
}
},
error: function (request,error) {
alert(error);
}
});
} else {
alert('Fill all nececery fields');
}
return false;
});
});
Two points:
Your APK is not running on your server. That means, that your url is wrong it needs to be something like:
url: "http://www.your_server.com/liveurl/check.php"
You have to whitelisten every external url, please read the docs for that:
http://cordova.apache.org/docs/en/dev/guide/appdev/whitelist/index.html