jQuery and Ajax request data issue - javascript

I have a problem with this code:
setInterval(function() {
var timed = $("#chMsgCont").find(".chatMsg:last-child");
var timee = timed.attr("data");
$.ajax({
url: "./ajax/checknew.php",
data: {timestamp: timee},
success: function(data) {
$("#chMsgCont").append(data);
if(data != null) {
var div = $('#chMsgCont');
var o = div.offset().top;
div.scrollTop( o + 12302012 );
}
}
});
},1000);
Even if data is null, $("#chMsgCont) scrolls down, why?

Try it this way:
if(data)
Or this way:
if(data != null && data != "")
Basically, if(data) is considered as data is false in these cases:
data is "" or '' => empty string
data is false
data is null
data is undefined

data is just empty and not null (undefined) so it will pass, try returning something extra in your PHP file.
I prefer doing the following at PHP side:
/* suppose that i am evaluating an insert to my DB */
print(1); //if success
print(0); //if error
then at javascript side, do this:
if(data == 1) //means success
or just do the following if you are not evaluating something at PHP side:
if(data != null && data != '')

Related

How to check if data returned from ajax as json is empty object or not

I have set this script for checking if the email address exists in the DB or not:
function checkemail(){
var e = document.getElementById("email").value;
if(e != ""){
document.getElementById("emailstatus").innerHTML = 'checking ...';
$.ajax({
type:'get',
url:'{!! URL::to('checkEmailExists') !!}',
data:{'email':e},
success:function(data){
// console.log(data);
if(Object.keys(data).length === 0)
{
document.getElementById("emailstatus").style.color = "red";
document.getElementById("emailstatus").innerHTML = e + " is NOT OK";
}else{
document.getElementById("emailstatus").style.color = "green";
document.getElementById("emailstatus").innerHTML = e + " is OK";
}
},
error:function(){
}
});
}
}
So the code works fine but the only problem is comes from this condition checking which always returns TRUE:
if(Object.keys(data).length === 0)
Basically, if I enter an email address that does not exist in the DB, this will be returned as data (results of console.log(data)):
{}
Otherwise, it will return this obj:
{
"id": 1,
"name": "Myname",
"email": "myemail#yahoo.com",
"email_verified_at": null,
"created_at": "2022-02-09T05:49:27.000000Z",
"updated_at": "2022-02-09T05:49:27.000000Z"
}
So I need to properly check if the returned object is empty or not.
But it looks like that if(Object.keys(data).length === 0) is not correctly checking that condition since it always TRUE & therefore the [email] is OK statement appears on page.
So how to properly check if the returned object is empty or not?
You can check for a specific property, if it's not there then it will be undefined, meaning you didn't get a success response.
Combine undefined with || to get a "value if not set", gives:
success:function(data) {
var success = (data.id || 0) > 0;
You could just check for if (data.id == undefined) but there are a number of caveats when comparing with undefined
Object.keys should work:
I suggest you double-check the params sent to the success function.
See below solution that have worked for me:
$.ajax({
url: url,
type: 'POST',
data: { par1: value1,
par2: value2 },
dataType: 'JSON',
contentType: 'application/x-www-form-urlencoded; charset=utf-8',
success: function(response)
{
if(Object.keys(response).length > 0)
{
//there is valid returned response
}
else
{
//no response keys returned
}
},
error: function (x, h, r) {
//deal with errors....
}
})

javascript if statement returns an error when json value is null

I have the javascript below, it works only when there is no null value in the json data output, however when there is a null json output as in
{"id":30,"name":"John Don","email":"abcd#gmail.com","latest_payment":null}
i get an error.
Uncaught TypeError: value.latest_payment is null
JQuery.ajax({
type:"GET",
url : '/list',
data:{tenantSelected:tenantSelected},
dataType : "json",
success:function(data)
{
jQuery.each(data, function(key,value){
if(tenantSelected == value.id){
var x=value.latest_payment;
if(x !== null) { //conditional statement to check if null
console.log(value.latest_payment);
} else {
console.log("No Data");
}
}
});
}
});
Here is sample json output.
[{{"id":29,"name":"Jane Doe","email":"xyz#gmail.com","latest_payment":{"id":44,"amount":120000,"rent_from":"2020-01-01","rent_to":"2020-03-01","tenant_id":29},},//This returns correct output
{"id":30,"name":"John Don","email":"abcd#gmail.com","latest_payment":null}] //returns an error Uncaught TypeError: value.latest_payment is null
And ideas?
Inside the if statement try this
if(value && value.latest_payment)
try like this
if(value && value.latest_payment) {
console.log(value.latest_payment);
} else {
console.log("No Data");
}

AngularJS: HTTP request is not responding after page is fully loaded

I have an invoice page all values are based on AngularJS ng-models (variables) so they are dynamic.
When I change text field DISCOUNT, all values change according to discount value (also call function abc repeatedly). This was working fine.
But now I have created a new function loadadditionalvalues inside function abc and request an HTTP call. First time this function work properly. However, when I type something in discount field, it requests, but never responds and gets hanged at my new function loadadditionalvalues.
function abc(){
$scope.loadadditionalvalues = function (n,o,scope)
{
arr=[];
$scope.isAppInitialized = false;
var requestUrl = 'page_test.php?do=action_netvalues&action=ID' ;
$http({
url: requestUrl,
method: 'GET'
}).then(function(response){
if(typeof response.data.ERROR_MSG !== 'undefined' || typeof response.data !== 'object' || typeof response.data.message !== 'undefined' || (typeof response.data.success !== 'undefined' && !response.data.success))
{
console.log("error ");
}
else
{
$scope.staffel_liste =response["data"];
}
});
};
$scope.loadadditionalvalues(null,null,scope);
}

Retrieve data from ajax query

So I've got a website where I want to click a button, check to see if the user has certain permissions, and if so popup a window to a new web page. On the java script I've got something like this:
function sendAjax(methodName, dataArray, success, error, category) {
var error2 = error || function () { };
$.ajax({
type: 'POST',
url: '/PermissionChecker' + methodName,
data: JSON.stringify(dataArray),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (r, s, x) { if (!success || success(r, s, x) != false) if (typeof (window.ChangeLogAdd) == 'function') { ChangeLogAdd(category); } },
error: error2
});
}
function CheckPermissions() {
sendAjax("CheckPermission", null, function (data) { var permission = eval('(' + data + ')'); if (permission == true) { alert('yay'); } else { alert('nay'); } }, null, 'Check Permission');
}
And the C# side is a simple function that does an if check and returns a bool. The function call goes through fine, but when it returns the bool I get a javascript error "Expected ']'". I assume this has something to do with my success function:
function (data) {
var permission = eval('(' + data + ')');
if (permission == true) {
alert('yay');
}
else {
alert('nay');
}
}
seeing as I didn't get this error before I tried what I'm doing there, so I was wondering how I would go about getting the data back from the ajax call to make pass the permission == true if/else check
Don't use eval for this purpose. It's unsafe and the source of many bugs. Just make the server respond with JSON and use $.getJSON.

Javascript global variable not being set from ajax call [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Return Value from inside of $.ajax() function
I'm working on a CakePHP app that makes use of widespread AJAX calls to controllers. I'm stuck with one particular AJAX call in which I'm trying to assign the response from the controller to a JS global variable. Here is the code:
window.errors = "";
function setErrors(err) {
window.errors = err;
}
function ajaxCall(u, t, d, dt) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
var success = false;
var err = "";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
console.log(err); //<=== displays correct value
setErrors(err); //<=== but somehow this seems to be failing??
}
else {
if(d.success === "1") {
success = true;
}
}
}
});
return success; //<=== I suspect this might be the culprit
}
And this is how ajaxCall() is used:
function register() {
var data = {};
var $inputs = $("#regForm :input");
$inputs.each(function(){
data[this.name] = $(this).val();
});
data = {"User" : data }; //CakePHP compatible object
data = JSON.stringify(data);
//Here's the AJAX call
if(ajaxCall('https://localhost/users/add', 'post', data, 'json')) {
alert("Registered!");
}
else {
alert(window.errors); // <=== empty string
console.log("window.errors is: " + window.errors); // <=== empty string
}
}
But on the Chrome JS console, window.errors returns the correct value (non-empty, validation error string).
I found a similar question that possibly might be addressing my issue (the return success immediately following the $.ajax() is being executed before the success: callback). How can I fix this without drastically changing the code (also, I don't want to make this a synchronous call)?
Yes, you are right that the return statement runs before the success callback. You can't return the result from the function, as the function has to return before the success event can be handled.
Add a callback to the ajaxCall function, and call that instead of setting the success variable:
function ajaxCall(u, t, d, dt, callback) {
var type = typeof t !== 'undefined' ? t : "post";
var dataType = typeof dt !== 'undefined' ? dt : "json";
$.ajax({url: url, data: "data=" + d, type: type, dataType: dataType,
success: function(d){
if(d.hasOwnProperty('success') === false) { //json response
for(var i in d) { //fetch validation errors from object
for(var j in i) {
if(typeof d[i][j] === "undefined") {
continue;
}
err += d[i][j] + "<br/>";
}
}
callback(false, err);
} else {
callback(d.success === "1", "");
}
}
});
}
Send the code for handling the result into the ajaxCall function:
ajaxCall('https://localhost/users/add', 'post', data, 'json', function(success, err){
if (success) {
alert("Registered!");
} else {
alert(err);
}
});

Categories

Resources