Skip to content
Advertisement

how to determine if the ajax response is an array of key value pair or a simple string response

I have a simple ajax function that sends data to the server and prints the response. the problem is some functions from PHP send the response as an array while some functions send the response as a simple string. For example, if the function was a success then the response is received as a key of response and a simple string if the response is a success while if any unauthorized error is found then an error key with possible error response is returned. I have different functions to perform according to the response type received. Till now I am able to check if a key exists in the response and this can determine whether the response has key-value pair. But this check fails when the response is a simple string instead of an array.

here is my PHP code in the server

JavaScript

However, my middleware checks the request and sends a response as an array

JavaScript

Here is my jquery code for ajax

JavaScript

I get the following error when a simple string message is received instead of an object or key-value pair

JavaScript

Advertisement

Answer

you can check for the type of data return by the ajax response by using the function typeof and perform necesssary action.

JavaScript
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement