Ajax response not appears inside success function - jquery mobile - javascript

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

Related

Ajax not working for login check

Hello I am not good with ajax.I want to check my login info and return either 'success' or 'fail'.Buy my ajax seems to have an error.
var user = $('.username').value();
var pass = $('.password').value();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username': user,
'password': pass
},
beforeSend: function() {
$("#Loading").show();
},
success : function(response) {
if(response=="success" && response!=="fail") {
$('.status').html("Success! Now logging in ......");
setTimeout(' window.location.href = "index.php"; ',4000);
} else {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(' window.location.href = "login.php"; ',4000);
}
}
});
Can anyone points me out?
The reason you are getting error is because your javascript is getting break(giving error) at $('.username').value(); as there is no value() function. If you open console you get this error. So because of this rest of script is not working. So change $('.username').value(); to this $('.username').val(); and same for the var pass = $('.password').value(); change to var pass = $('.password').val(); and also you don't need if condition as mention in comment. Your final code will be something like this.
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type: 'POST',
url: //some url
data: {
'username': user,
'password': pass,
},
beforeSend: function() {
//some code
},
success: function(response) {
// some code which you want to excute on success of api
},
error: function(xhr, status, error) {
// some code which you want to excute on failure of api
}
});
I dont have the whole code for your app but when it come to your ajax request your code should look like this , for a more accurate answer please show the error that you are getting
var user = $('.username').val();
var pass = $('.password').val();
$.ajax({
type : 'POST',
url : 'login_check.php',
data : {
'username':user,
'password':pass,
},
beforeSend: function()
{
$("#Loading").show();
},
success : function(response)
{
$('.status').html("Success! Now logging in ......");
setTimeout(()=>{ window.location.href = "index.php"; },4000);
},
error: function(xhr, status, error) {
$('#Loading i').hide();
$('.status').html("Login fail! Please use correct credentials....");
setTimeout(()=>{ window.location.href = "login.php"},4000);
}
});
Your response needs to be a PHP echo that returns a string with a value of either ”success” or ”fail”.
Your PHP response after successful login:
echo(‘success’);
Your PHP response after failed login:
echo(‘fail’);

Submit form after successful ajax call using jQuery in asp.net mvc 5

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.

Ajax call function on success return false not working

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

JQuery confirmation dialog after AJAX request

I need to validate, on server side, if a person with a given registration number is already on the database. If this person is already registered, then I proceed with the program flow normally. But, if the number is not already registered, then I'd like to show a confirmation dialog asking if the operator wants to register a new person with the number entered and, if the operator answers yes, then the person will be registered with the number informed on the form on it's submission.
I've tried
Server side(PHP):
if (!$exists_person) {
$resp['success'] = false;
$resp['msg'] = 'Do you want to register a new person?';
echo json_encode($resp);
}
Client side:
function submit(){
var data = $('#myForm').serialize();
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
return false;
}
I can't even see the alert, that's where I wanted to put my confirmation dialog, with the message written on server side. Other problem, how do I resubmit the entire form appended with the operator's answer, so the server can check if the answer was yes to register this new person?
EDIT
I was able to solve the problem this way:
Server side(PHP):
$person = find($_POST['regNo']);
if ($_POST['register_new'] === 'false' && !$person) {
$resp['exists'] = false;
$resp['msg'] = 'Do you want to register a new person?';
die(json_encode($resp)); //send response to AJAX request on the client side
} else if ($_POST['register_new'] === 'true' && !$person) {
//register new person
$person = find($_POST['regNo']);
}
if($person){
//proceed normal program flow
}
Client side:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
var ajax1 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function (response) {
if (!response.exists && confirm(response.msg)) {
document.getElementById('register_new').value = 'true'; //hidden input
dados = $('#myForm').serialize(); //reserialize with new data
var ajax2 = $.ajax({
type: 'POST'
, dataType: 'json'
, async: 'true'
, url: 'myPHP.php'
, data: data
, success: function () {
document.getElementById('register_new').value = 'false';
$('#myForm').unbind('submit').submit();
}
});
} else if (response.success) {
alert(response.msg);
$('#myForm').unbind('submit').submit();
}
}
});
}
There doesn't appear to be anything wrong with your PHP.
The problem is (1) You are doing the alert inside of an error callback, and your request isn't failing, so you don't see the alert. (2) You are alerting the string 'response' instead of the variable response.
It is also worth noting that you should be using the .done() and .fail() promise methods (http://api.jquery.com/jquery.ajax/#jqXHR).
Here is the fixed JS:
function submit() {
var data = $('#myForm').serialize();
// Same as before, with the error callback removed
var myAjaxRequest = $.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
});
// The request was successful (200)
myAjaxRequest.done(function(data, textStatus, jqXHR) {
// The data variable will contain your JSON from the server
console.log(data);
// Use a confirmation dialog to ask the user your question
// sent from the server
if (confirm(data.msg)) {
// Perform another AJAX request
}
});
// The request failed (40X)
myAjaxRequest.fail(function(jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
});
return false;
}
Also, you are setting a 'status' in PHP and checking that in the JS (I presume). What you want to be doing is setting a HTTP status code from the server, as below:
if (!$exists_person)
{
$resp['msg'] = 'Do you want to register a new person?';
// 400 - Bad Request
http_response_code(400);
echo json_enconde($resp);
}
Then, jQuery will determine whether the request failed based on the status code you respond with. 200 is a successful request, and 400 numbers are fail.
Check out this page for a full list: https://httpstatuses.com/
Okay so this is a two part question; I'll try my best to answer both parts:
Part 1: How to detect if success is false and trigger the confirmation popup?
In jQuery.ajax the error handler is triggered based on response code. This is probably not what you want. You can use your success handler and test the value res.success to see if it's true or false. It would be something along the lines of:
function submit(e) {
e.preventDefault();
var data = $('#myForm').serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
}).done(function(res) {
if (!res.success) {
alert(res.msg);
}
});
}
Part 2: How do I resubmit with a confirmation?
Working off of our previous code we will make some changes that allow for submit() to be passed an argument registerNew. If registerNew is true we will pass it as a param to the ajax handler in the PHP so it knows we want to register a new person. The Javascript will look something like this:
function submit(e, registerNew) {
if (e) e.preventDefault();
var data = $('#myForm').serialize();
var ajax_options = {
type: 'POST',
dataType: 'json',
url: 'myPHP.php',
async: 'true',
data: data
};
ajax_options.data.register_new = !!registerNew;
$.ajax(ajax_options).done(function(res) {
if (!res.success && confirm(res.msg)) {
submit(null, true);
}
});
}
As you can see here, we are passing a new register_new param in the data in our ajax options. Now we need to detect this on the PHP side, which is easy enough and looks like this (this goes in your php ajax handler):
if ($_POST["register_new"]) {
// new user registration code goes here
} else {
// your existing ajax handler code
}
Add confirm inside submit function
function submit(){
var data = $('#myForm').serialize();
if (confirm('Are you ready?')) {
$.ajax({
type: 'POST'
,dataType: 'json'
,url: 'myPHP.php'
,async: 'true'
,data: data
,error: function(response){
alert('response');
}
});
}
return false;
}

Checking existing user in database with jquery and servlet

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");
}
}
});
}

Categories