What is the method for retrieving this data using Javascript?

I received this JSON-encoded data:

{
    "error": {
        "msg":"Concurrent verifications to the same number are not allowed",
        "code":10
    }
}

and I tried to access the 'msg' value using JavaScript as follows:

$("#buttonPhoneSubmit").click(function(e) {
    $("#verifyForm").show();
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: './process.php',
        data: $('form').serialize(),
        datatype:'json', 
        success: function (data) {
             $('#error_message').html(data.error.msg);
        }
    });

However, I encountered an issue where it reported that the 'data' is undefined. Can someone identify what's causing this problem in the code?

Thank you!

Answer №1

In agreement with Roy's statement, the issue lies in having datatype: 'json' instead of dataType: 'json'. This leads me to believe that jQuery is not properly parsing the JSON data for you.

Rather than simply changing it to dataType: 'json', a more effective solution would be to modify the PHP file to include the Content-Type: application/json header in the response:

// Add this line in the PHP file before sending the response body
header('Content-Type: application/json');

By doing so, you can omit datatype: 'json' from your ajax call. jQuery will automatically recognize the content type and handle the parsing accordingly, allowing your code to function as intended (assuming the JSON returned matches your expectations).

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

I attempted to verify the login through postman, but encountered an error in the process

I created the login route on the backend and tested it in Postman, but encountered this error message: https://i.stack.imgur.com/PdyCo.png Below is the code for the login route: router.post("/login", async (req, res) => { try { const user = await ...

I'm receiving a 403 Forbidden error while attempting to use @csrf_exempt with an AJAX request. Why is this happening?

I've been attempting to create a simple AJAX request in Django, but I keep encountering the 403 forbidden error in both the Chrome Dev and Django consoles. Despite trying various proposed solutions like @csrf_exempt (to eliminate any potential csrf is ...

The failure of jQuery AJAX error callback to execute

I'm currently facing an issue with an AJAX call that I have in my code. Here's the code snippet: $.ajax({ type: "get", url: "xxx.xxx.xxx/xxx.js", dataType: 'jsonp', success: function(data) { ...

The operation of "grunt build" results in a Lexer Error, causing the ng-include

After deploying my unminified code successfully, I proceed to run grunt build and deploy from the dist folder. However, upon checking one of the pages, I encounter a breakage with an error in the console: Error: [$parse:lexerr] Lexer Error: Unexpected nex ...

Is there a neat method in React and Material UI for de-structuring the props that I am passing to useStyles?

When passing props to useStyles based on the Material docs, our code looks like this: const useStyles = makeStyles({ // style rule foo: props => ({ backgroundColor: props.backgroundColor, }), bar: { // CSS property color: props => ...

What is the best way to utilize Jackson for transforming a Java Map into a complex POJO object?

Recently, I've been exploring more robust methods to parse inputs from a Conductor workflow. In pursuit of this, I devised a structured class setup involving individuals and their respective vehicles. Person.java public class Person { protected ...

Tips for combining enable and disable properties in flatpickr.js?

I'm facing a challenge with using both the enable and disable properties in flatpickr.js. The enable property returns a range of dates that should be enabled, but I specifically want to disable certain days within that range, like weekends. datePicker ...

Vite deciding to generate its own node_modules directory within the workspace rather than depending on a monorepo

I have organized a monorepo for a fullstack webapp with the directory structure outlined below: . ├── client │ ├── index.html │ ├── package.json │ ├── src │ └── vite.config.ts ├── node_modules ├── p ...

Issue with Refreshing onRowAdd in React Material Table

I am currently using Material Table to display my table data. However, when I use the onRowAdd function to add a new row, the page does not refresh properly. Instead, it reloads and gets stuck, requiring me to manually refresh again. newData => ...

Creating keys for my console.log data and appending it to html in order to display console log results in textboxes

I am currently developing a matching system for Player vs. Player battles and I need to ensure that the keys are appended correctly to my div element. Previously, I have successfully used append with keys before. Below is the code snippet: ...

How can HTML5 geolocation be utilized to provide real-time latitude and longitude coordinates for integration with the Google Maps API?

I am currently working on a project where I need to dynamically fetch longitude and latitude values from the browser geolocation and then include them in the options array for the Google Maps API. Here is the code snippet I am using: function initMap(){ ...

How to drop several pins on Google Maps with JavaScript

I am working on incorporating multiple markers into a Google map using ajax, javascript, and php. Although there are no errors in my code, the markers are not appearing as expected. I would greatly appreciate any assistance with this issue. Please refer to ...

nodejs express routing issue resulting in not found error

I recently started a new node project and wanted to enhance my route adding capabilities. In the past, I only went one level deep with folders, but this time I wanted to go further. To achieve this, I created a recursive function that adds routes and navig ...

Unable to change the filename when utilizing Angular.js ng-file-upload

After uploading a file using Angular.js ng-file-upload, I am attempting to rename the file. However, when I remove the properties ngf-min-height="400" ngf-resize="{width: 400, height:400}", I encounter an issue. Below is my code: <input type="file" dat ...

Having trouble with npm debounce in ReactJS?

When using the npm debounce package in ReactJS, I encountered an error with the code below: Javascript - Uncaught TypeError: Object(...) is not a function The error occurs when passing the function into the debounce() method. import React, { Component ...

Is there a way to reset useQuery cache from a different component?

I am facing an issue with my parent component attempting to invalidate the query cache of a child component: const Child = () => { const { data } = useQuery('queryKey', () => fetch('something')) return <Text>{data}& ...

Is the parsing of JSON data from AJAX requests vulnerable to a man-in-the-middle attack when using eval

After writing some AJAX code, I noticed that the server returns JSON data that I created myself and is therefore secure. In this case, it seems that using eval is perfectly fine. However, I am concerned about the possibility of a man-in-the-middle attack w ...

Ways to display the hidden element using AngularJS

I want to show the information of "[6] Peter who is 95 years old" in a hidden text box, which should only appear when the button <button ng-click="show_id(friend.id)">get my id</button> is clicked. The name should be displayed using the ng-mode ...

Hide the div element once the timer runs out

Struggling to make a timer disappear when it reaches 00:00, every attempt results in the div being hidden immediately. Check out the code snippet I've been working with: $(document).ready(function(e) { var $worked = $("#worked"); function upd ...

Unable to access the 'fn' property of undefined in Handlebars causing a TypeError

I encountered an issue with my custom handlebars helper. When I fail to define values for the parameters, I receive the following error message. module.exports = function(src, color, classatr, options) { if (typeof src === 'undefined') src ...