0

I have an AJAX request in my page and the .php page echoes an integer or string based on the event in the page. But, when the variable reaches to my actual javascript file , it becomes string. For example 4 changes to "4". And that is making my program problematic because my program has to run according to the responseText. I have a XMLHTTPRequestObject.onload function that works like:

    if(typeof XMLHTTPRequest.responseText === "number"){
// do something
}

My php script provides a result either integer or string and if the result is string, then I can perform the function but it is not happening like so. I tried changing the variable using parseInt() and Number() but then, everything gets changed to number either it was s string. So, how do I tackle this problem? Please do help!

2 Answers2

0

You can try converting the string to number using Number. If you receive NaN you know the string wasn't a valid number say 123notANumber for example, see here for more information.

if (isNaN(Number('123test')) {
  // This is a string
}
else {
  // It's a number
}
0

As mentioned in the comments XMLHttpRequest.responseText will always be a string. The easiest solution is likely to use the Number constructor to convert that string to a number. If the string doesn't represent an integer, Number will return NaN. So instead of what you have currently, you could do somthing like this:

const parsed = Number(XMLHTTPRequest.responseText);
if(isNaN(parsed)){
    //handle case where response is a string
} else {
    //handle case where response is a number
}
schu34
  • 965
  • 7
  • 25