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

While working in Next.js, I utilized an `<Image />` tag with a link to an image, only to encounter an unexpected error

I've attempted it numerous times, but the error persists. I even went ahead and created the next.config.js file. module.exports = { images: { domains: ['link.papareact.com', ], }, }; Error: The src prop (https://links.pap ...

What is the best way to trigger an event function again once a specific condition has been satisfied?

I'm currently working on a project where I need a sidebar to scroll at a slower rate until it reaches a specific point, and then stop scrolling once that point is reached. Below is the jQuery code I've been using: $(window).on("scroll", function ...

JavaScript Bingo Game - Create Interactive Cell Selection

Below is the HTML code that I am using to create a Bingo card: ... <th class="orange">B</th> <th class="orange">I</th> <th class="orange">N</th> ...

What is the syntax for implementing an if-else statement?

Just starting with algolia and looking for a hit template. Please take a look at the script below for the text/html template needed: <script type="text/html" id="hit-template"> <div class="hit"> <div class="hit-image"> <i ...

Combine children by grouping them using Rails' group_by method, then map

My current method implementation is as follows: def categorised_templates template_categories.all_parents.map do |cat| cat.templates.by_brand(id).group_by(&:category) end end The output of this method is in the format shown below: [{"Communi ...

Creating an interactive online dashboard with real-time updates

I am looking to integrate a Kafka stream into MySQL using Python, and then create a real-time web-based dashboard that will automatically refresh (using ajax) upon each new data insert in the database. Although I came across a suggestion stating that ajax ...

Error occurs when attempting to execute JSON.parse within the backend of a Wordpress

My goal is to have a dropdown list of WordPress pages with the class of 'page_id' that can be repeated and added dynamically. Whenever a page is selected from the dropdown list, I want to send an AJAX request to fetch the title, excerpt, and thum ...

Filtering data based on dates in AngularJS

I need to implement a data filter based on event date. The options for filtering include the current day, current month, and current year. Below is the current implementation: function filterDate($scope) { var d = new Date(); var curr_date = d.get ...

Guide to creating a delayed response that does not block in Node and Express

I want to implement a delayed response to the browser after 500ms has elapsed. app.post('/api/login', function(req, res) { setTimeout(function() { res.json({message: "Delayed for half a second"}); }, 500); }); The code snippet a ...

What is the best way to add a "load more" button in a React application?

After writing this code, I am receiving a list of 12 objects that are being mapped. class PokemonList extends React.Component{ constructor(props){ super(props); this.state = { pokemonList: [], apiTemplateUrl: "h ...

What is the best way to utilize Python in order to transform a large amount of unicode into characters to create a string-like appearance?

In JavaScript, I've managed to do this: eval(String.fromCharCode(102,117,110,99,116,105,111,110,32,99,104,101,99,107,40,41,123,13,10,09,118,97,114,32,97,32,61,32,39,100,52,103,39,59,13,10,09,105,102,40,100,111,99,117,109,101,110,116,46,103,101,116,69 ...

Encountering the 415 Unsupported Media Type error while using Spring 3.2

My current task involves inserting and/or updating data in the database utilizing the PUT method with JSON through jQuery 1.6 (Jackson 2.1.1, and Spring 3.2.0). Below is the JavaScript code snippet: var itemsArray=[]; var id; function insertOrUpdate() ...

Crafting 3 intertwined combinations using the power of jQuery AJAX and PHP

Here's what I've been working on so far: The first page retrieves data and populates the first combobox, which is all good. Then, when users select a value from combo1, a second combobox is created with filtered data using AJAX - also working fin ...

Optimizing jQuery scripts by consolidating them to reduce file size

I've created a jQuery script that performs the same task but triggers on different events, including: Page load Dropdown selection change Clicking the swap button Typing in a text field However, I had to write separate scripts for each of these eve ...

Unable to detect hover (etc) events after generating div elements with innerHTML method

After using the code below to generate some divs document.getElementById('container').innerHTML += '<div class="colorBox" id="box'+i+'"></div>'; I am encountering an issue with capturing hover events: $(".colorB ...

Prevent scale animation for a specific section of the icon using CSS

I need help in preventing the scale animation of the :before part of the icon class from occurring when the button is hovered. The current behavior is causing the arrow to look distorted on hover... Link to the code on Codepen HTML <div class="se ...

Navigate to a PDF file from an HTML5 application using PhoneGap by accessing an external link

Can anyone help me figure out what I'm doing wrong here? Essentially, I am trying to open a PDF in Google Viewer: <a id="pdflink" href="https://docs.google.com/viewer?url=http://pdpdpd.pdf" target="_blank">Pdf</a> When it opens in the vi ...

The Jquery .remove() function will only take effect after the second click

I am currently working on implementing a notifications feature using bootstrap popover. The issue I am facing is that after a user clicks on a notification, it should be removed. However, for some reason, it requires two clicks to actually remove the notif ...

Adding multiple images from URLs to a ListView in a Java Android app is a common task that

When I look at my app, I notice that the list view with uploaded videos is being populated from JSON data. The JSON response also includes the URL to the video image. However, when I try to display this image in an ImageView within my XML layout for the Li ...

Utilizing Async/Await with an Unassigned Object

I'm facing a puzzling issue with an async/await function that refuses to assign to an object. Despite displaying the expected results in the console, when it comes to actually assigning to the object, it fails to do so. Let me elaborate below: Here&a ...