Employing the JSON return code

I am attempting to implement ajax with php. Here is the PHP script I have:

<?php

// This file retrieves the POST information sent by an AJAX request and returns the values if successful.

$price['name'] = "Called";
$price['Wheel']  = 75.25;
$price['Tire']   = 50.00;

echo json_encode($price);
?>

and I am calling this code from my main page like this :

        $.post("ajax/profileMod.php", {
            'lname':lname,
            'fname':fname,
            'mname':mname,
            'language':language,
            'title':title,
            'ptype':ptype,
            'vip':vip,
            'vreason':vreason
        })
        // Retrieve the data from the php script
        .done(function(data) {
         // php code : echo json_encode(array("name"=>"Called!"));
            alert(data);
        }, "json");

        // Prevent default behavior
        return false;
    });

The returned result from the alert looks like this: {"name":"Called","Wheel":75.25,"Tire":50}

Is there a way to format this result so it can be used in javascript like this EX:

alert(myresult['Name']) ; Would give me "Called".

I would like to use an associative array in JavaScript, but I read somewhere that you can only have objects in JavaScript, not associative arrays...

Please provide help!

Answer №1

To ensure jQuery parses the response as JSON, pass "json" as the final parameter to .post().
(Alternatively, ensure your server returns the correct Content-Type of application/json, which should trigger jQuery to parse it automatically)

This will provide you with a JavaScript object, allowing you to execute

alert(result.name);

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

Issue with Django query not being successfully transferred to AJAX in JSON structure

Trying to populate a textfield with its corresponding database value using Django and AJAX. The objective is for the textfield to automatically update when the dropdown value changes. However, encountering an error in console: SyntaxError: Unexpected to ...

Is there a way to add pins to separate entity layers, and then remove them from a specific entity layer using Bing Maps AJAX Control, Version 7.0?

Currently, I am utilizing Bing Maps to display store locations on a map. The information about the stores is coming from a dynamic JSON response. When the page loads, the map shows local stores with pushpins and infoboxes. As the map pans, my goal is to re ...

Leveraging the power of MySQL and PHP to handle nested JSON data in AngularJs with ng-options

Can someone please guide me on how to generate nested JSON data using MySQL and PHP in Codeigniter? I am looking to structure my data in the specific format shown below. $data = { 'India': { 'Andhra Pradesh': ['Vijay ...

Python code for performing a surgical replacement of a JSON field with another in a file

Currently, I am dealing with a large collection of JSON files structured like this: File00, timestamp T1: { "AAA": { "BBB": { "000": "value0" }, "CCC": { "111": "value1", "222": "value2", "333": "value3" }, " ...

Transferring parameters from a jQuery post function to a controller

I am facing an issue where the controller is not receiving the "name" parameter that I want to send as a parameter. $(document).ready(function () { $("#btn1").click(function () { var name = $("#search").val(); //name = "ali"; alert(name); ...

Is it possible to use both the .load function and fadeIn in jQuery simultaneously?

Currently, I am utilizing the .load method to bring in another page using jQuery. Below is the code snippet: $('#page1').click(function(){ $("#content").load("page1.html"); }); While this code works well, I am inte ...

Using default JavaScriptSerializer to bind DateTime to knockout view model

Recently, I started using knockout and encountered a problem with DateTime Serialization and Deserialization when using the JavaScriptSerializer. I modified the gifts model in Steve's koListEditor example from his blog to include a new field for Modi ...

AngularJS: Ensuring Controller Functions are Executed Post AJAX Call Completion via Service

Here's the code snippet I have in my service. this.loginUser = function(checkUser) { Parse.User.logIn(checkUser.username, checkUser.password, { success: function(user) { $rootScope.$apply(function (){ $rootScop ...

Steps to modify the servletRequest's content length within a filter

My main objective is to secure the POST body requests sent from my web application to my service by encrypting them. This encryption process takes place within a filter in my system. However, I've encountered an issue related to content length. When ...

iOS: Retrieving null data from a dictionary

When trying to display data using JSON parsing in my project, I encountered an issue where the second NSDictionary returns a Null value. Below is the code snippet for reference: -(void)hdata { NSString *post = [NSString stringWithFormat:@"data[User ...

Using Ajax (Jquery) to send data to a PHP script

Currently, I am working on an application where users can click a checkmark to complete a task. When this action is taken, a popup window appears (created using bootstrap), prompting the user to enter their hours worked on the task. After entering the hour ...

using variables as identifiers in nested JSON objects

Within my code, there is a JSON object named arrayToSubmit. Below is the provided snippet: location = "Johannesburg, South Africa"; type = "bench"; qty = 1; assetNumber = 15; arrayToSubmit = { location : { type : { 'qty' ...

Step-by-step guide on using Ajax to accurately delete selected records with multiple checkboxes

When I utilize a loop to generate rows of data, each row is assigned a unique value for data-host-id as confirmed by the Chrome Developer Tool. However, when clicking on any record, it consistently updates the initial record instead of the intended one. Th ...

Using Jquery Mobile to make an AJAX POST request with XML

Is it possible to use this code for XML parsing? I have successfully parsed using JSON, but there is no response from the web service. This is the status of the webservice: http/1.1 405 method not allowed 113ms $j.ajax({ type: "GET", async: false, ...

The server struggles to handle numerous simultaneous requests

Currently, I am facing an issue while trying to track the progress of a controller method. My approach involves using the setInterval method to continuously call the progress method within the controller. However, I have noticed that the ajax call inside t ...

What is the best way to send multiple id values with the same classname as an array to the database via AJAX in Codeigniter?

Hey everyone, I'm facing an issue where I need to send multiple IDs with the same class name but different ID values to the database using AJAX. However, when I try to do this, only the first value is being picked up and not all of them. How can I suc ...

Exploring the World of GiantBomb APIs

I have successfully created an account and obtained my API key. I am looking to implement a basic search functionality on my webpage, where users can enter a search query and click a button to display the game title and image. You can find more informatio ...

Should GIT be utilized for managing version control of HTML pages?

Currently, I am developing an application that automatically generates blog pages in HTML format using JSON files. In addition to this functionality, the app also needs to support versioning for each blog created. The process involves converting JSON dat ...

Extracting content from a concealed frame and displaying it on a visible frame via javascript

Is there a method to extract a specific DIV element from an HTML frame and display it in a visible frame using JavaScript? For instance, if I create a hidden frame containing Google search results, is there a way to show only the search results on the vis ...

Transforming API Response into a structured format to showcase a well-organized list

When I make an API call for a list of properties, the data comes back unorganized. Here is how the data from the API looks when stored in vuex: posts:[ { id: 1; title: "Place", acf: { address: { state: "Arkansas", ...