You can't retrieve a JSON object using Javascript

Every time I execute the javascript/php code below, I encounter an issue where I keep receiving "undefined" when trying to alert the 'userid' property of the json object. However, if I turn the json object into a string using stringify(), it correctly returns "[{'userid':'1'}]".

Why am I facing this problem when attempting to access the correct field of the json object?

Below is the ajax script I am utilizing to retrieve the object:

$.ajax({
  type: 'POST',
  url: 'WebPHP/check_login.php',
  contentType: "application/json; charset=utf-8",
  data: finalObject,
  async: false,
  dataType: 'json',
  success: function(data) {
    if (data["result"] === false) {
      alert("Invalid Email or Password");
    } else {
      var userID = data["result"];
      alert(userID["userid"]);
      var url = "AMessage.html";
      alert(JSON.stringify(data["result"]));
    }
  }
});

And here is the php code that interacts with the database:

$json = file_get_contents('php://input');

$jsondata = json_decode($json);

$email = $jsondata - > email;
$password = $jsondata - > password;

$sql1 = " SELECT user_id as userid
FROM users
WHERE email = '$email'
AND password = '$password';
";

$result = mysqli_query($Thesisdb, $sql1) or die(mysqli_error($Thesisdb));

$rows = $result - > num_rows;


while ($row = $result - > fetch_assoc()) {
  $response[] = $row;
}

$post_data = array();

if ($rows == 1) {
  $post_data = array('result' => $response);
} else {
  $post_data = array('result' => false);
}

echo json_encode($post_data);

mysqli_close($Thesisdb);

Answer №1

The reason you can't access the userid property is because your variable userID contains an array - indicated by the square brackets in the JSON response: [{'userid':'1'}]. To access it correctly, try this code: alert(userID[0]["userid"]);.

A better approach would be to avoid returning an array altogether, especially since you're checking if $rows == 1.

Answer №2

Acknowledging the information provided by #Jack, it is important to note that you are unable to access the userid property directly in your json response as shown: [{'userid':'1'}]. Since the data is in array form, you will need to utilize the correct syntax like this: alert(userId[0].userid)

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Adjusting the waterlevel model attribute to its standard value

In my Sails.js project, I am looking to reset a model attribute back to its original default value. By default value, I mean the value specified using defaultsTo in the model file. I have attempted methods such as: model.update({id:exampleId}, {myAttrib ...

Could it be a glitch or a special functionality when JSON objects return "@" along with the field name?

My REST web service is built using Jersey version 11 (1.11). When I make a JSON request, the response I receive looks like this: { "course_name": "test1", "cid": "testMike", "start_date": "2012-03-13T00:00:00.000-04:00", "end_date": "2012- ...

In PHP, you can create a script that checks a specific value in a CSV column and then loops through

I'm currently facing challenges in finding the optimal solution to make this work efficiently. From an outdated system, I have a large CSV file as output and my goal is to convert it into a JSON file. The CSV contains several columns, with the ' ...

Material-UI: Creating Radio Button Groups

I have been working on a project using React and Bootstrap. I decided to switch to material-ui, which went smoothly except for the radio buttons. Below is the original code that worked well: <label> <input type={that.props.questionType} name ...

Image conceals secretive PHP script

I currently have a webpage featuring various images, each of which has a button allowing users to favorite the image. Upon clicking this button, a PHP script is triggered in order to add the image to their list of favorites. My objective is to initiate th ...

Updating embedded documents with new information in mongodb

After searching on SO, I couldn't find a satisfactory answer to my question related to working with mongodb and php for the past couple of weeks. So here I am seeking help. I have a database where I need to add new data to one of the embedded/nested d ...

Implementing the decrement functionality within an onclick event handler for a variable

Can someone assist me with this issue? I am trying to use a variable ID in HTML to call a function on a JavaScript page. For example: (Minus button not functioning) <button class="minus-button quantity-button button" type="button" name="subtract" onc ...

Can you explain the purpose of the equals sign in ngRepeat?

Can you explain the significance of the equals sign in the ng-repeat attribute value? <li ng-repeat="person in people = (people | orderBy: firstname)"> rather than using: <li ng-repeat="person in people | orderBy: firstname"> I coul ...

Utilizing Django Ajax to specify a URL with two dynamic URL paths (e.g. <str: 'first_variable'>/<str: 'second_variable'>/fetch/)

I've created a Django ajax template to retrieve all the Players from a players model: <body> <h1>List of Players:</h1> <ul id="display-data"> </ul> </body> <script> $(document).ready(fun ...

Is it possible for me to retrieve data in object using double v-for?

I am attempting to create a dynamic table using the following objects: <tr v-for="product in allPosts" :key="product.id"> <td v-for='(item, i) in checked' :key='`item${i}`'>{{product.item}}</td> </tr> In th ...

I'm looking for the location of the console.log output while running nodejs/npm start. Where

Just started working with react/node and using npm start to launch a server. The server is up and running, displaying my react code as expected. However, I'm facing an issue with debugging - my console.logs are not showing up in the browser console. I ...

Choose a specific name from the object

Currently, I am in the process of learning and would appreciate your patience. I have a json response from which I need to extract specific elements. My goal is to identify particular elements within an object by their name, such as "length" or "width", an ...

Experiencing an "isTrusted" error while working with the GLTFLoader

QUERY: All was running smoothly: I successfully transformed my FBX files to GLTF in the /GLTF/ directory. Unfortunately, after noticing missing geometry in some converted files, I attempted another conversion of the FBX files, this time to /TEST/. Unexp ...

Does using AJAX with jQuery and PHP guarantee that the response will always be in JSON format?

While working on PHP validation with AJAX requests for user-submitted information, I encountered an issue. The problem arises when attempting to convert the JSON response from PHP to a Javascript object, as it throws the following error: "Uncaught SyntaxE ...

Exclude the UL hierarchy from removing a class in jQuery

Check out this fiddle to see the code snippet: http://jsfiddle.net/3mpire/yTzGA/1/ I am using jQuery and I need to figure out how to remove the "active" class from all LIs except for the one that is deepest within the hierarchy. <div class="navpole"&g ...

"Bringing in" ES6 for Node

I am interested in utilizing import from ES6 instead of require from common.js in Node. Surprisingly, I initially assumed that import would function automatically in Node. However, it appears that it does not. Is there a specific npm package that needs t ...

What is the best way to secure the installation of python packages for long-term use while executing my code within a python shell on NodeJS?

I have been encountering difficulties while attempting to install modules such as cv2 and numpy. Although I have come across a few solutions, each time the shell is used the installation process occurs again, resulting in increased response times. Below i ...

What is the method to obtain the content height of individual pages in Android, with or without the use of JavaScript?

I am facing an issue while trying to retrieve the content height of each webpage consecutively. When I load pages separately, I can successfully get the height of each page. However, when I attempt to fetch the content height continuously for webpages in a ...

Experiencing difficulties when trying to upload images using multer in an Express application with Node.js

I have been using multer to successfully upload images into a folder within my project. Despite not encountering any errors while using multer, I am facing an issue where the upload is not functioning as expected in my project, although it works perfectly ...

How can the Flickr API be utilized with JavaScript functions?

In preparation for a project, we are required to utilize the Flickr API in order to display a collection of photos when a specific category is selected. I have successfully set up my categories on the left side of a flexbox container. However, I am struggl ...