Tips for returning JSON data using AJAX

When working with native JS, I am familiar with using AJAX to display the output from PHP/mySql that is not Json Encoded in the element "some_id" like this:

<script>
function addItem(value) {
      xmlhttp = new XMLHttpRequest();
      xmlhttp.onreadystatechange = function() {
          if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
            document.getElementById("some_id").innerHTML = xmlhttp.responseText;
          }
      }
      xmlhttp.open("GET","some_php.php?q="+value,true);
      xmlhttp.send();
}
</script>

However, when dealing with JSON encoded results from PHP/mySQL, how can I display it in "some_id" using AJAX?

Answer №1

To extract the JSON data, start by using JSON.parse():

If your data is structured like this:

{
    "result": "Example response"
}

You can follow a procedure similar to this one:

<script>
function fetchData(data) {
    let request = new XMLHttpRequest();
    request.onreadystatechange = function() {
        if (request.readyState == 4 && request.status == 200) {
            //Convert string to object
            let json = JSON.parse(request.responseText);
            document.getElementById("some_id").innerHTML = json.result;
        }
    }
    request.open("GET", "example.php?q=" + data, true);
    request.send();
}
</script>

Answer №2

//sample_php.php
$input = $_POST['input'];
echo json_encode($input);   //Transform input into JSON data


<script>
function addData(input) {
    $.ajax({
        type: "POST",
        url: "sample_php.php",
        dataType: 'json',
        data: {input: input},
        success: function(response) {
            console.log(response);   //response is already in JSON format
        }
    });
}
</script>

Answer №3

If you have retrieved your data from a MySQL database, let me illustrate with an example involving multiple fields.

yourdata.php

// After fetching data from MySQL
$data = new stdClass();
$data->email = $row['email'];
$data->phone = $row['phone_number'];
$data->age = $row['age'];
echo json_encode($data);

Now, in the file where you have implemented Ajax,

var xhttp = new XMLHttpRequest();
// Add the remaining code specific to your implementation
// Upon receiving response.text, perform the following
var data = xhttp.responseText;
var myData = data.toString();
var jsonObject = JSON.parse(myData);
// Extract each value from the JSON object
document.getElementById('divEmail').innerHTML = jsonObject.email;
document.getElementById('divPhone').innerHTML = jsonObject.phone;

The reason for stringifying data before parsing it in JavaScript is that JavaScript may struggle to interpret JSON data encoded in PHP. It is advisable to handle it this way to avoid errors.

var myData = JSON.Parse(xhttp.responseText);

I'm addressing this query while on the move, hence the presence of numerous comments. I hope this explanation proves beneficial.

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

Challenges with handling Ajax responses in Ruby on Rails

I'm currently facing an issue with the Ajax response in my Rails application, and I'm unsure of how to troubleshoot it. Here is the code that is functioning correctly: View <div id="<%= dom_id(comment) %>_count"> <%= Like.wh ...

What could be the reason these two functions yield different outcomes?

I am currently in the process of optimizing a function to enhance performance. Previously, the old function took approximately 32 seconds, while the new one now only takes around 350 milliseconds for the same call. However, there seems to be an issue as th ...

Validation of forms in Angular using a pseudo submission method

On a webpage, there is a form with two buttons: one to calculate a price and the other to submit the form. Below is a basic example: <form novalidate name="formStep1"> <select ng-model="address" required> <option></option> ...

How to style TextInput to display dollar amounts when using onChangeText and Redux in React Native

Struggling to format number input in a TextInput using the onChangeText function in React Native with Redux. Tried using .toFixed(2) function, but encountering an issue where it interprets the next digit as the first decimal and rounds back to 0 due to Re ...

How to add JSON data into a specific column of a table using

While exploring options for inserting arrays into single database columns, I came across an article that discussed inserting JSON strings. Unfortunately, the article did not provide detailed instructions on how to do this. Despite conducting further resear ...

The capability to scroll within a stationary container

Whenever you click a button, a div slides out from the left by 100%. This div contains the menu for my website. The problem I'm encountering is that on smaller browser sizes, some of the links are hidden because they get covered up. The #slidingMenu ...

Incapable of modifying the text within a div container

I am currently working on a script that translates a Russian forum word by word using TreeWalker. However, there is a specific type of div element that I have been unable to change the text for. That leads to my question: How can I go about changing it? Un ...

Alter the functionality of the input element that has a tag of 'multiple'

I am encountering an issue with a form that allows users to upload multiple photos. When selecting multiple files at once, everything works as expected. However, if a user wants to add images one by one, each new addition deletes the previous file due to t ...

Incorrect input

Let's consider this scenario: We have a workspace website similar to Google Drive. (Remember that) There is a Delete .icon on my files list to delete a file. When I request the delete file WebMethod using Ajax, I also want to retrieve the updated ...

Is it possible to manipulate CSS on a webpage using javascript?

I have incorporated this piece of JavaScript to integrate a chat box onto my website: window.HFCHAT_CONFIG = { EMBED_TOKEN: "XXXXX", ACCESS_TOKEN: "XXXXX", HOST_URL: "https://happyfoxchat.com", ASSETS_URL: "https://XXXXX.cloudfront.ne ...

"Error in Visual Studio: Identical global identifier found in Typescript code

I'm in the process of setting up a visual studio solution using angular 2. Initially, I'm creating the basic program outlined in this tutorial: https://angular.io/docs/ts/latest/guide/setup.html These are the three TS files that have been genera ...

Struggling to construct a project using parcel, continually encountering issues with unsupported file types

My attempt at creating a project using parcel has hit a snag. Despite diligently following the guidelines provided in my assignment, an error message consistently appears in my terminal each time I initiate the command: parcel src/index.html The error mes ...

AJAX forms and snippets

I have successfully integrated comments into public activity following a tutorial on public activity #406 Public Activity. However, I am facing issues with submitting the comments via ajax. I have gone through several tutorials but haven't been able t ...

I am sorry, but it seems like there is an issue with the definition of global in

I have a requirement to transform an XML String into JSON in order to retrieve user details. The approach I am taking involves utilizing the xml2js library. Here is my TypeScript code: typescript.ts sendXML(){ console.log("Inside sendXML method") ...

A JavaScript function that smoothly scrolls an element into view while considering any scrollable or positioned parent elements

I needed a function that could smoothly scroll a specific element into view with some intelligent behavior: If the element is a descendant of a scrollable element, I wanted the ancestor to be scrolled instead of the body. If the element is within a posit ...

App crash on IOS only occurs when running on a physical device, but not when running on the simulator

Following a successful build in Xcode, my app runs smoothly on the simulator and my iPhone. However, when I distribute it for testing, it crashes whenever test users attempt to perform a search. If I hardcode the URL elements, everything works perfectly b ...

JQ: Transforming data with a PigLatin-inspired FLATTEN operation

I've been on the hunt for a specific feature that might not exist in jq. If you happen to know it's missing, I would greatly appreciate a gentle heads-up along with some suggestions on how to tackle this issue. I'm currently working with a ...

Sending both old and new data through a submission function

$("#new-medical-center-form").submit(function(e){ e.preventDefault(); let parent; let _token = $("input[name=_token]").val(); let name=$("#name_create_medical_center").val(); ...

Experiencing a missing handlebars helper error when utilizing a helper within partials in express-handlebars

I have set up custom helpers using express-handlebars like this: const { create } = require("express-handlebars"); // Configuring the handlebars engine const hbs = create({ helpers: require("./config/handlebars-helpers"), }); app.engi ...

The issue of execution order in JavaScript Recursion with promises

In the process of developing a method for creating markup to be used in a web app's off-canvas navigation. One of the challenges I am facing is making an asynchronous callback to another service that provides children nodes for the parent menu node (r ...