How to fulfill the condition correctly "If" in javascript - javascript

function UserCheckId() {
$.ajax({
type: "POST",
dataType: "json",
url: "/Home/SomeAction",
data: { qrcode: scannedQR[txt] },
dataType: 'json',
success: function (data) {
if (data = "Storekeeper") {
document.location.replace("/Storekeeper.aspx");
}
else {
alert("Error");
}
}
});
There is a UserCheckId function in which I call the SomeAction function from C # (it returns a string value) and pass the result to Javascript. After that, I want to check what the value of the result is. If "Storekeeper", then go to the site, otherwise an error pops up. The problem is that whatever the value is (for example, C # will return the value "Collector"), the condition for the Storekeeper is met in any case. I checked data with alert, it outputs the string value correctly. What to do? Help me please!

To check equality in javascript use strict equality operator === which will check both type and value. Also always normalize (like trim, toLowerCase etc) before any comparison operation
if (data?.trim().toLowerCase() === "storekeeper") {

Related

I need to return value from ajax

I need to return value from ajax but it filled 0 every time and didn't wait for ajax process finished
var itemId=0; as global value
getitemIDbyProductID(productId,getitemIDbyProductID_success);
alert(itemID + "itemgeted")
I did this
function getitemIDbyProductID(productId, callback) {
$.ajax({
type: "POST",
url: "Cot.aspx/getitemIDbyProductID",
data: JSON.stringify({ productId: productId }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var value = 0;
value = JSON.parse(result.d);
itemID=callback(value)
callback(value);
},
error: function (msg) { }
});
}
function getitemIDbyProductID_success(total_percentage) {
alert(total_percentage +"fds"+itemID);
}
but it didn't wait the ajax finished and gives me the itemId = undefiend
You're successfully setting the value here:
function getitemIDbyProductID_success(total_percentage) {
itemID = total_percentage;
alert(total_percentage +"fds"+itemID);
}
But then, in the code which calls this, you're successfully setting it again:
itemID=callback(value)
Since your getitemIDbyProductID_success doesn't return anything, the return value is undefined. So basically you're unsetting itemID immediately after setting it.
Just invoke the callback, don't use its (non-extant) return value:
callback(value);
Additionally, this isn't going to do what you think:
getitemIDbyProductID(productId,getitemIDbyProductID_success);
alert(itemID + "itemgeted");
Because getitemIDbyProductID performs an asynchronous operation. Even once the above errors are corrected, this error still remains. And this one is a duplicate of a very popular question (with answers far better than I can provide) here.
You can do something like this:
getitemIDbyProductID(productId,function(val){
itemID = val;
alert(itemID + "itemgeted");
});
Basically, you have to wait before the itemID gets assigned right value.

JavaScript: search user input in number of arrays

I am working with D3js library. On the web page, there is a search box which user can input their parameter. I receive arrays of data via Ajax post to my database. Following is the code:
..........
var aa;
var bb;
$(function(){
$.ajax({
type: "POST",
url: "http://localhost:7474/db/data/transaction/commit",
accepts: {json: "application/json"},
dataType: "json",
contentType: "application/json",
data: JSON.stringify(query), //query is somewhere above the code
//pass a callback to success to do something with the data
success: function (data) {
aa = data.results[0].data;
aa.forEach(function (entry) {
passVar(entry.row[0].name)
});}}
);
});
function passVar(smth){
bb =[smth];
console.log (bb);
//Should search the user input..........
}
//if the user input matches, filter function should run.........
function filterData() {
var value = d3.select("#constraint")[0][0].value;
inputValue = value;
............
}
As the result of console.log(bb)I receive the following on console:
["Direct Digital Control System"]
["Fire Protection"]
["HVAC Cooling- Waterside"]
["HVAC Heating- Waterside"]
["HVAC System"]
["HVAC-01"]
["HVAC-02"]
What I want to do:
If the user input match with one of the results in var bb, then program should run function filterdata() {....for querying. If not, don't do anything.
How should I write the code to make the search and run the other function? Thanks for the any help/suggestion.
You can loop through the array and find whether the user input is equals to the current index value of the array. if equals you can call your function and break the loop since no need to loop further more.
for(int i=0; i<bb.length; i++){
if(bb[i] == userInput){
filterdata();
break;
}
}

To get value from Json Object

In the below code i am passing json object it is in the format {"Table":[{"FAMin":0,"FAMax":40,"FAGrade":"C"}]}.How to get the value from it i tried the below code it results undefined .Pls help me to overcome this issue.
function UpdateGrade(GradeID) {
alert(GradeID);
$.ajax({
type: "POST", //HTTP method
url: "MarkorGradeSettings.aspx/GetGrade", //page/method name
data: "{'GradeID':'" + GradeID + "'}", //json to represent argument
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
alert(msg.d);// I get values
var parsedJson = jQuery.parseJSON(msg.d);
alert(parsedJson.Table.FAMin);//undefined
//handle the callback to handle response
if (msg != 'error') {
//$('#messages').addClass('alert alert-success').text(response);
// OP requested to close the modal
$('#myModal').modal('hide');
} else {
$('#messages').addClass('alert alert-danger').text(response);
}
//Now add the new items to the dropdown.
}
});
}
Table is an array but you are treating as an object
Try:
alert(msg.d.Table[0].FAMin)
Also as noted in comments there is no need to call jQuery.parseJSON when dataType:'json' is set. jQuery will parse the response internally and return object/array in callback
It looks like you missed that the data under Table is an array.
This should at least fix this particular case:
alert(parsedJson.Table[0].FAMin);

Questions in Ajax success function

$.ajax({
type: "GET",
dataType: "jsonp",
jsonp: "jsoncallback",
data: {
//some data
},
url: "http://mydomain.com/checkRequest.php?jsoncallback=?",
success: function (result) {
if (result[0].data.NameB == "") {
alert("123");
} else {
alert("456");
}
},
error: function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
}
}); // end of ajax
I have the above code, it works successfully if and only if there are somethings return.
However, if the PHP does not return anything, the string becomes: jQuery191025216468679718673_1364086240540([]);
and I expected it to go to else's part, which alert 456. But, it skips the whole success function. So, how should I modify the coding?
It works if I change the if clause to if (result!="")
Have a look at the console. I'm sure you get an error like
Cannot read property "data" of undefined.
If the array is empty, result[0] will return undefined and the subsequent property access will cause a run time error, which terminates the script immediately. Check first whether the arrays is empty or not:
if (result.length > 0 && result[0].data.NameB == "")
You might have to test the existence of result[0].data as well, depending on the data.

Javascript value is returned from webservice but will not show unless a breakpoint is used

I have a javascript function that calls a web service. The data comeback (I see the Jason return in FireBug) the value is blank when I attempt to use it unless I set a break point. With a break point set the value can be used, without it is not available.
Here is a snippet of the offending call.
function getTheNote(noteCode){
var _myNote = "";
var theID = $('#CustNo').val();
var myDTO = { 'theID': theID, 'noteCode': noteCode, };
var toPass = JSON.stringify(myDTO);
$.ajax({
type: 'POST',
contentType: "application/json; charset=utf-8",
dataType: "json",
url: "AR_Cust_Mgt.aspx/getNote",
data: toPass,
success: function (data) {
_myNote = data.d;
}
});
//setTimeout(_myNote += _myNote, 120000);
//for(var x = 0; x < 200000; x++){}
//return _myNote;
alert(_myNote);
}
Originally I was sending the value back to a calling function the return statement is where I would set my break point and the data would be returned, without nothing. Now you can see I attempted to use an alert inside the function with the same results.
With a break point I get a value without I get nothing, I have even attempted to use some delays.
Please help.
The ajax call is asynchronous. Anything you want to do with the result needs to be in your anonymous function success: function(data) { ... or the anonymous function needs to call other functions to do stuff.
As it is coded now, $.ajax will be called, the script execution continues on before the ajax call returns.
small change, big difference: you are not calling alert IN the succes function
success: function (data) {
_myNote = data.d;
alert(_myNote);
}

Categories

Resources