How to define a variable after process in ajax? - javascript

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

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 refresh the page with updated data when click update button

function update(){
var name= document.getElementById("TextBox").value;
$.ajax({
url: '....',
type: 'post',
data: {....//many data include// 'name' : name, ....},
success: function(data) {
var replacevalue=data.replace(/[\[\]']/g,'' );
alert(replacevalue);
var stringstatus=replacevalue.replace(/['"]+/g, '');
alert(stringstatus);
if(stringstatus == "success"){
alert ("Successfully Update ")
}
else{
alert("Failed!");
return ;
}
returnToDisplayPage();
},
error: function(xhr, desc, err) {
console.log(xhr);
console.log("Details: " + desc + "\nError:" + err);
}
});
}
function returnToDisplayPage(){
var id = document.getElementById("TextBox").text;
window.location = './DisplayPage.php?Name='+id;
}
Please suggest me. How should I do to get the updated data when click update button and refresh or reload page ? In function returnToDisplayPage() methods. I got only the name of update data and other related fields data didn't get back.
Try something like this:
$.post('url', {params}, function(response){
//Here you check if you got response from url
// And then you can do whatever you like to do with received data
if(response == 'ok'){
//do your stuff
//then
window.location.reload();
}
}
When we will get result in response then After 5 seconds page will be refresh..
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}

When submitting an ajax request, how can you "put the original request on hold" temporarily until a condition is met?

I am wanting to implement a recaptcha process that captures all ajax requests before they go through - the desired process would be as follows:
User completes an action which is going to cause an ajax request of some sort.
If the user has already completed the recaptcha process, the ajax request proceeds without further delay
If the user has not completed the recaptcha process, put the ajax request "on hold" temporarily until the recaptcha process is completed, then continue the ajax request.
I have got things to a state where I intercept the call, however I don't know how to put it on hold temporarily. Here's the relevant code:
<script>
var captchaValidated = null;
var currentRequests = [];
$.ajaxPrefilter(function (options, originalOptions, jqXHR) {
if (options.url != "/ValidateCaptcha") {
if (captchaValidated == null || captchaValidated == false) {
if (captchaValidated == null){
openRecaptcha();
} else {
verifyCaptcha(); //see async question in method
}
if (!captchaValidated) {
jqXHR.abort();
} else {
//let the original request proceed now - but how?!
}
}
}
});
function verifyCaptcha() {
var grecaptcha = $("g-recaptcha-response");
var encodedResponse;
if (grecaptcha != null) {
encodedResponse = grecaptcha.val();
$.ajax({
async: false, //set to false so that the calling method completes rather than async - what do you think?
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
//parse the data - did we get back true?
captchaValidated = data;
},
error: function (raw, textStatus, errorThrown) { captchaValidated = null; alert("Validate ReCaptcha Error: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": encodedResponse })
});
}
}
function invalidateCaptcha(){
captchaValidated = null;
}
function openRecaptcha() {
grecaptcha.render('recaptcha', {
'sitekey': "thekey",
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
$("#recaptchaModal").modal('show');
}
</script>
Any suggestions of how to proceed would be appreciated, thanks in advance!
Thank you #Loading and #guest271314 for your help in pointing me in the right direction that helped me get things figured out. I've pasted how I accomplished it below - perhaps it will be of help to someone else. Of course if anyone would like to weigh in on my implementation please do.
<script src="https://www.google.com/recaptcha/api.js?onload=onloadCaptcha&render=explicit&hl=en" async defer></script>
<script>
var captchaValidated = null;
var currentRequests = [];
var captchaPrompted = false;
var captchaReady = false;
var resetCaptcha = false;
function onloadCaptcha() {
captchaReady = true;
captcha = grecaptcha.render('recaptcha', {
'sitekey': '<yoursitekey>',
'callback': verifyCaptcha,
'expired-callback': invalidateCaptcha,
'type': 'audio image'
});
}
var deferredCaptcha = null;
var promiseCaptcha = null;
var captcha = null;
function openRecaptcha() {
if (!captchaReady) {
setTimeout(openRecaptcha, 50);
}
if (captchaPrompted) {
return;
}
captchaPrompted = true;
var captchaTimer = setInterval(function () {
if (captchaValidated != null) {
if (captchaValidated) {
deferredCaptcha.resolve();
} else {
deferredCaptcha.reject();
captchaValidated = null;
}
}
}, 100);
if (resetCaptcha) {
captcha.reset();
}
deferredCaptcha = $.Deferred();
promiseCaptcha = deferredCaptcha.promise();
promiseCaptcha.done(function () {
//captcha was successful
clearInterval(captchaTimer);
//process the queue if there's items to go through
if (currentRequests.length > 0) {
for (var i = 0; i < currentRequests.length; i++) {
//re-request the item
$.ajax(currentRequests[i]);
}
}
});
promiseCaptcha.fail(function () {
//captcha failed
clearInterval(captchaTimer);
currentRequests = []; //clear the queue
});
$("#recaptchaModal").modal('show');
}
function verifyCaptcha() {
resetCaptcha = true;
var response = $("#g-recaptcha-response").val();
var encodedResponse;
// confirm its validity at the server end
$.ajax({
headers: headers,
cache: false,
url: "/ValidateCaptcha",
type: 'POST',
contentType: 'application/json',
success: function (data) {
captchaValidated = data;
if (!data) {
captchaPrompted = false;
}
},
error: function (raw, textStatus, errorThrown) { captchaValidated = false; captchaPrompted = false; alert("WTF Validate ReCaptcha Error?!: " + JSON.stringify(raw)); },
data: JSON.stringify({ "encodedResponse": response })
});
}
function invalidateCaptcha(){
deferredCaptcha.reject();
captchaValidated = null;
resetCaptcha = true;
}
$.ajaxSetup({
beforeSend: function (xhr, settings) {
if (settings.url == '/ValidateCaptcha' || captchaValidated) {
// we're validating the captcha server side now or it's already been validated - let it through
} else {
if (typeof settings.nested === 'undefined'){
settings.nested = true; //this flag is to determine whether it's already in the queue
currentRequests.push(settings); //add the request to the queue to be resubmitted
//prompt them with the captcha
openRecaptcha();
}
return false; // cancel this request
}
}
});
</script>
At $.ajaxPrefilter() use .then() chained to openCaptcha to call verifyCaptcha
if (captchaValidated == null){
openRecaptcha().then(verifyCaptcha);
}
at verifyCaptcha use .is() with parameter "*" to check if an element exists in document
if (grecaptcha.is("*")) {
at openRecaptcha(), if grecaptcha.render does not return asynchronous result return jQuery promise object using .promise(); else chain to grecaptcha.render and $("#recaptchaModal").modal('show'); using $.when()
return $("#recaptchaModal").modal('show').promise()
or
return $.when(grecaptcha.render(/* parameters */)
, $("#recaptchaModal").modal('show').promise())
Something like this? (pseudo-code)
verified = false;
$('#myButton').click(function(){
if (!verified) verify_by_captcha();
if (verified){
$.ajax(function(){
type: 'post',
url: 'path/to/ajax.php',
data: your_data
})
.done(function(recd){
//ajax completed, do what you need to do next
alert(recd);
});
}
});//end myButton.click

Issue with post callback in 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
});

How can I handle errors in AJAX in jquery

How can I handle errors in AJAX?
In my code, the else condition containing console.log is not executed even when the departments.json file is not loaded. I checked it by deleting the departments.json file from where it is loaded into the code.
My code is:
$.getJSON("departments.json?" + new Date().getTime(), {}, function(departments, status, xhr) {
if (xhr.status == 200) {
var numericDepts = [];
var nonNumericDepts = [];
for(dept in departments) {
$("#kss-spinner").css({'display':'none'});
if (isNaN(departments[dept].depNo)) {
if (isNaN(parseInt(departments[dept].depNo,10)))
nonNumericDepts[nonNumericDepts.length] = departments[dept];
else
numericDepts[numericDepts.length] = departments[dept];
}
else
numericDepts[numericDepts.length] = departments[dept];
}
numericDepts.sort(cmp_dept);
nonNumericDepts.sort(function(dept1,dept2) {
return dept1.depNo.toLowerCase() - dept2.depNo.toLowerCase();
});
departments.sort(cmp_dept);
var k = 0;
$.each(numericDepts.concat(nonNumericDepts), function() {
if (k % 2 == 0) {
$('<p class="odd" onClick="selectTag(this,\'' + this.id + '\', 1)">' + this.depNo + '</p>').appendTo($(".scroller", $("#br1")));
}
else {
$('<p class="even" onClick="selectTag(this,\'' + this.id + '\', 1)">' + this.depNo + '</p>').appendTo($(".scroller", $("#br1")));
}
k++;
});
$("#kss-spinner").css({'display':'none'});
}
else {
console.log(xhr.status);
console.log(xhr.response);
console.log(xhr.responseText)
console.log(xhr.statusText);
console.log('json not loaded');
}
});
You could just use the generic ajax() function:
$.ajax({
url: url,
dataType: 'json',
data: data,
success: successCallback,
error: errorCallback
});
You will need to use the fail() method in order to accomplish that.
Example:
$.get("test.php")
.done(function(){ alert("$.get succeeded"); })
.fail(function(){ alert("$.get failed!"); });
if you need a generic error handler use
$.ajaxSetup({
error: function(xhr, status, error) {
// your handling code goes here
}
});
JQuery's getJSON function is an abstraction over the regular .ajax() method - but it excludes the error callback.
Basically, the function you define is only called if the call is successful (that's why it never gets to the else part).
To handle errors, set an error handler before like this:
$.ajaxError(function(event, jqXHR, ajaxSettings, thrownError) { alert("error");});
Whenever an AJAX request completes with an error, the function will be called.
You can also append the .error at the end of your getJSON call:
$.getJSON("example.json", function() {
(...)
}).error(function() { (...) });
The $.getJSON() function is just a special purpose version of the more general .ajax() function.
.ajax() function will give you the extra functionality you desire (such as an error function). You can read more documentation here http://api.jquery.com/jQuery.ajax/
$.ajax({
url: "departments.json?" + new Date().getTime(),
dataType: 'json',
success: function(departments){
var numericDepts = [];
var nonNumericDepts = [];
for(dept in departments)
{
$("#kss-spinner").css({'display':'none'});
if(isNaN(departments[dept].depNo))
{
if(isNaN(parseInt(departments[dept].depNo,10)))
nonNumericDepts[nonNumericDepts.length]=departments[dept];
else
numericDepts[numericDepts.length]=departments[dept];
}
else
numericDepts[numericDepts.length]=departments[dept];
}
numericDepts.sort(cmp_dept);
nonNumericDepts.sort(function(dept1,dept2) {
return dept1.depNo.toLowerCase() - dept2.depNo.toLowerCase();
});
departments.sort(cmp_dept);
var k=0;
$.each(numericDepts.concat(nonNumericDepts),function(){
if(k%2==0){
$('<p class="odd" onClick="selectTag(this,\''+this.id+'\',1)">'+this.depNo+'</p>').appendTo($(".scroller",$("#br1")));
} else {
$('<p class="even" onClick="selectTag(this,\''+this.id+'\',1)">'+this.depNo+'</p>').appendTo($(".scroller",$("#br1")));
}
k++;
});
$("#kss-spinner").css({'display':'none'});
},
error: function(xhr, textStatus, errorThrown) {
console.log(xhr.status);
console.log(xhr.response);
console.log(xhr.responseText)
console.log(xhr.statusText);
console.log('json not loaded');
}
});​

Categories

Resources