Issue with post callback in Javascript - javascript

I'm having a strange behavior of the following code:
// Log in the user if credentials are correct
function login() {
$.post("http://localhost/auth/login", {
username : $("#modal-login-username").val(),
password : $("#modal-login-password").val(),
autoLogin : autoLogin,
_token : $("#modal-login-token").val()
},
function(result) {
console.log("1"); // This is not printed
if(result === "OK") {
window.location.href = "http://localhost/home";
} else {
console.log("2"); // This is not printed
$("#modal-login-message-error").removeClass("hidden");
}
});
console.log("3"); // This is printed
};
In this function I check if the PHP script that logs in the user returns 'OK' or not. If the authentication is successful the user is correctly redirected to http://localhost/home but if something goes wrong an ERROR string with 500 status is returned but the else statement is not executed.

That callback function only gets called on suucess. You can place your call in the .always() method of post:
var jqxhr = $.post( "example.php")
.always(function() {
console.log("1"); // This is not printed
if(result === "OK") {
window.location.href = "http://localhost/home";
} else {
console.log("2"); // This is not printed
$("#modal-login-message-error").removeClass("hidden");
}
});
for more details have a look at the jQuery page http://api.jquery.com/jQuery.post/
or even better:
var jqxhr = $.post( "example.php", function() {
window.location.href = "http://localhost/home";
}).fail(function() {
console.log("2"); // This is not printed
$("#modal-login-message-error").removeClass("hidden");
});

$.post(...).fail(function () {
//handle failure here
});

Related

Error part in jQuery is missing

I build following JavaScript part and everything works fine. But I'm not sure if the code is completely right. Because in my script I only use success: function() but I don't use error. Is it a MUST to have error in a jQuery AJAX call?
Currently I'm catching the errors in my php controller function and echo them in the success part.
$(document)
.ready(function() {
var groupName = '';
var groupid = '';
$(".grp")
.click(function() {
$('.text-danger')
.html('');
groupName = $(this)
.data('groupname');
groupid = $(this)
.attr('id');
$('.text')
.html(groupName);
$('#dataModal')
.modal({
show: true
});
});
jQuery(".grpval")
.click(function(e) {
e.preventDefault();
jQuery.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]')
.attr('content')
}
, });
jQuery.ajax({
url: "{{ route('request_group') }}"
, method: 'post'
, data: {
'Gruppe': groupid
}
, success: function(data) {
if (typeof data.successsuccess != 'undefined') {
jQuery('.alert-success')
.show();
jQuery('.alert-success')
.html('<p>' + data.successsuccess + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else if (typeof data.successdberror != 'undefined') {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + data.successdberror + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
} else {
jQuery.each(data.errors, function(key, value) {
jQuery('.alert-danger')
.show();
jQuery('.alert-danger')
.html('<p>' + value + '</p>');
$('#dataModal')
.modal('toggle');
window.scrollTo(500, 0);
});
}
}
});
});
});
EDIT: Here is the function from my Controller:
public function setGroupRequest(Request $request){
$validator = \Validator::make($request->all(), [
'Gruppe' => [new ValidRequest]
]);
$groupid = $request->input('Gruppe');
if ($validator->fails())
{
return response()->json(['errors'=>$validator->errors()->all()]);
}
try{
$groups_request = new GroupRequest();
$groups_request->idgroups = $groupid;
$groups_request->iduser = Auth::id();
$groups_request->request_active = 1;
$groups_request->save();
$db_status = 'success';
}catch(\Exception $e){
$db_status = 'error';
}
if($db_status == 'success'){
return response()->json(['successsuccess'=>'Record is successfully added']);
}else{
return response()->json(['successdberror'=>'DB Error! Values could not be saved.']);
}
}
Error handling is required as you never know different things on the internet might result in failure of request for example,
Network failure.
Lost database connection
Unauthorised access/access denied
Any variable being not defined
There is nothing wrong in your way of writing PHP error in success, but writing it in $ajax error callback function is preferred as it helps in separating error & success logic.
In fact you can add a jquery error callback function as well to your $ajax which will handle all the errors originating from above mentioned internet failures.
You can add error function, which will receive any type of error coming from backend.
jQuery.ajax({
url: "{{ route('request_group') }}",
method: 'data: {
'Gruppe': groupid
},
success: function(data) {
//code here
},
error: function (jqXHR, exception) {
//error handling
}
})
In your PHP file,
if ($query) {
echo "success"; //whatever you want to show on success.
} else {
die(header("HTTP/1.0 404 Not Found")); //Throw an error on failure
}
This way you can catch PHP error as well as any internet Network errors in your jquery ajax.

How to define a variable after process in ajax?

I use an ajax process to modify user's state on an index.php file.
It works but I would like to color my div function of the user's state
My code:
function recupstatut() {
$.post('recup.php', function(data) {
$('.cont2').html(data);
var content = document.querySelector('#cont2');
var status2 = content.innerHTML;
if (status2 == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
});
}
setInterval(recupstatut, 1000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<div class="cont2" id="cont2">
</div>
The condition always applies the else state:
content.style.backgroundColor = "#f44336";
I think the problem comes from var status2 =
How can I fix this?
HTML
<div class="cont2" id="cont2"></div>
SCRIPT
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
function recupstatut() {
$.post('recup.php', function(data) {
console.log(data);
var status2 = data.trim();
console.log(status2);
$('.cont2').html(status2);
if (status2 == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
});
}
setInterval(recupstatut, 1000);
</script>
what went wrong is that you imported jquery file after calling the function
so make the import in top of calling your function
your mistake was that you made the import after calling the function, that is why you got undefined error.
As you say you echo string in your page then you can check this one directly from the data as per below code.
Script:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<script>
$(function(){
function recupstatut() {
$.post('recup.php', function(data) {
$('#cont2').html(data); // If the data return from the php page as a string then you can compare it directly.
if (data == "En-ligne") {
$('#cont2').css("backgroundColor","#4CAF50");
} else {
$('#cont2').css("backgroundColor","#f44336");
}
});
}
setInterval(recupstatut, 1000);
});
</script>
HTML:
<div class="cont2" id="cont2"></div>
function recupstatut(){
$.post('recup.php',function(data){
console.log(data);
$('.cont2').html(data);
var status2 = data;
if (status2 == "En-ligne") {
$('#cont2').css("backgroundColor","#4CAF50");
} else {
$('#cont2').css("backgroundColor","#f44336");
}
});
}
setInterval(recupstatut,1000);
nothing appear in my div now with the console.log...
THere many ways to accomplish this. You can use the $.post() function by sending the $.post as a variable. Example:
// Fire off the request to /form.php
request = $.post({
url: "recup.php",
});
// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// Log a message to the console
console.log("Hooray, it worked!");
});
// Callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// Log the error to the console
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
// Callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// Reenable the inputs
$inputs.prop("disabled", false);
});
Or (i recommended) use the $.ajax({}) function as this way:
// Fire off the request to /form.php
$.ajax({
url: "recup.php",
type: "post",
data: { //specify data to be sent },
beforeSend:function(){
/* before sending the data to the other page
may be a loader to show waiting animation
*/
},
success:function(status){
/* this will check the response received from the previous page
and the determine the below conditions
*/
if (status == "En-ligne") {
content.style.backgroundColor = "#4CAF50";
} else {
content.style.backgroundColor = "#f44336";
}
}
});

Dynamically changed value in jQuery not seen in sent jsp form

I am submitting the form on click button, but whatever I have changed that data is not sent but the previous data is sent, is there a way in which I can commit the data of the field in forms then send??
$j("body").on('click', "#btn_snd",function(){
Retrieve_Property_name();
$j(this).closest("form").submit();
});
});
The changes are done using ajax
function Retrieve_Property_name()
{
$j(".class_cat").hide();
var property_name = $j("#property_name").val();
$j.ajax({
type : "POST",
url : "ShowCat.jsp",
data : "property_name=" + property_name ,
success : function(data) {
if(data.trim()=="No")
{
$j("#Cat_name_hidden").val("General");
alert("Inside No");
}
else if(data.trim()=="Yes")
{
alert("Inside yes");
if($j("#Cat_name").val()==null)
{
$j("#Cat_name_hidden").val(" NULL");
}
else
{
//
alert("Categories:-"+$j("#Cat_name").val());
$j("#Cat_name_hidden").val($j("#Cat_name").val());
//
arr1 = $j("#Cat_name").val();
}
$j(".class_cat").show();
}
alert();
}
});
}
This is the change function
Instead of calling the submit function from the on function:
$j(this).closest("form").submit();
can you do this after your ajax call completes within the success function:
$j("#btn_snd").closest("form").submit();
My guess is that the form gets submitted before the ajax request completes and hence the old values are posted. So ideally the change function would be:
function Retrieve_Property_name()
{
$j(".class_cat").hide();
var property_name=$j("#property_name").val();
$j.ajax({
type : "POST",
url : "ShowCat.jsp",
data : "property_name=" + property_name ,
success : function(data) {
if(data.trim()=="No")
{
$j("#Cat_name_hidden").val("General");
alert("Inside No");
}
else if(data.trim()=="Yes")
{
alert("Inside yes");
if($j("#Cat_name").val()==null)
{
$j("#Cat_name_hidden").val(" NULL");
}
else
{
//
alert("Categories:-"+$j("#Cat_name").val());
$j("#Cat_name_hidden").val($j("#Cat_name").val());
//
arr1 = $j("#Cat_name").val();
}
$j(".class_cat").show();
}
alert();
$j("#btn_snd").closest("form").submit();
}
});
}

Ajax just opens PHP file

I have a form I am trying to submit via ajax from PHPAcademy's tutorial found here
Basically the form needs to submit via ajax, simple enough. But when I try do that, it just opens the PHP file in the browser. PLEASE HELP!
here is the ajax code:
$('form.login_settings').submit(function(){
var that = $(this),
url = '../login_settings_submit.php',
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
I have tried using e.preventDefault(); but with no luck
I have also tried changing the initial function from
$('form.login_settings').submit(function(){
to
$('form.login_settings').on('submit', function(){
What am I doing wrong?
It's pretty easy friend:
Java Script Code:
$(function() {
$('form.login_settings').submit(function(e){
e.preventDefault();
var that = $(this),
type = that.attr('method'),
data = that.serialize()
$.ajax({
type: type,
url: '../login_settings_submit.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
});
use jQuery .serialize method to parametrize form data and write code inside
$(document).ready(function(){
//
}); or
$(function(){
//
});
and if you wanna check ajax error then you can use
,error : function(jqXHR, exception) {
if (jqXHR.status === 0) {
alert('Not connected.\nPlease verify your network connection.');
} else if (jqXHR.status === 404) {
alert('The requested page not found. [404]');
} else if (jqXHR.status === 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
after success method. It's good to check ajax error always when you are in production.

How to save var value outside ajax success function?

I am trying to make some form validation functions. Here is what I have:
<script>
$(document).ready(function() {
var myObj = {};
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
$.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
if (data.ok == true) {
$(myObj).data("username","ok");
} else {
$(myObj).data("username","no");
}
}
});
} // end validateusername function
$('#submit').click(function(){
if (myObj.username == "ok") {
alert("Username OK");
} else {
alert("Username BAD");
}
});
}); // end doc ready
So you can see, when a key is pressed in the textbox, it checks if it's valid. The "data.ok" comes back correctly. The problem is based on the response, I define $(myObj).username. For some reason, I can't get this value to work outside the validateusername function. When clicking the submit button, it has no idea what the value of $(myObj).username is.
I need to use something like this, because with multiple form fields on the page to validate, I can do something like:
if (myObj.username && myObj.password && myObj.email == "ok")
... to check all my form fields before submitting the form.
I know I must just be missing something basic.... any thoughts?
EDIT: SOLVED
All I had to do was change var myObj = {}; to myObj = {}; and it's working like a charm. I think I've been staring at this screen waaaaay too long!
You're not accessing the data that you stored properly. Access the username value this way:
$(myObj).data("username")
Resources:
Take a look at jQuery's .data() docs.
Very simple jsFiddle that shows how to properly set and retrieve data with jQuery's .data() method.
I would store the promise in that global variable and then bind an event to the done event within your submit button click.
$(document).ready(function() {
var myObj = false;
$('#username').keyup(function () {
id = $(this).attr('id');
validateUsername(id);
});
function validateUsername(id){
var username = $("#"+id).val();
myObj = $.ajax({
url : "validate.php",
dataType: 'json',
data: 'action=usr_id&id=' + username,
type: "POST",
success: function(data) {
$('#username').removeClass('valid invalid');
if (data.ok == true) {
$('#username').addClass('valid');
}
else {
$('#username').addClass('invalid');
}
}
});
} // end validateusername function
$('#submit').click(function(){
// if myObj is still equal to false, the username has
// not changed yet, therefore the ajax request hasn't
// been made
if (!myObj) {
alert("Username BAD");
}
// since a deferred object exists, add a callback to done
else {
myObj.done(function(data){
if (data.ok == true) {
alert("Username BAD");
}
else {
alert("Username OK");
}
});
}
});
}); // end doc ready
you may want to add some throttling to the keyup event though to prevent multiple ajax requests from being active at once.

Categories

Resources