Unable to retrieve PHP object using AJAX

I am having trouble fetching the PHP file from Ajax. In the PHP file, an object is created and then converted into JSON using the json_encode() function. However, when I try to request that PHP file from Ajax, nothing is displayed as output ('Smith' should be the output).

Below is my PHP file: 1.php

 <?php 
    $myObj->name = "Smith";
    $myObj->age = 20;
    $myObj->Address = "Yangon";

    $myJSON = json_encode($myObj);

    echo "$myJSON"; 
  ?>

Here is the Ajax file: ajaxfile.php

<p id="demo"></p>
<script type="text/javascript">
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function(){
        if (this.readyState == 4 && this.status == 200) {
            var myObj = JSON.parse(this.responseText);
            document.getElementById("demo").innerHTML = myObj.name;
        }
    };
    xmlhttp.open("GET", "1.php", true);
    xmlhttp.send();
</script>

Answer №1

Experiment with

<?php
  $person['name'] = "Johnson";
  $person['age'] = 25;
  $person['Location'] = "Tokyo";
  $jsonData = json_encode($person);

  print_r("$jsonData");
 ?>

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

PHP Bootstrap Confirmation Dialog Tutorial

Is there a way to implement a delete confirmation dialog? When 'yes' is clicked, the message should be deleted, and when 'no' is clicked, the delete operation should be canceled. At present, this is how it looks in my view: <a href ...

The update query inadvertently modifies all entries in the database rather than targeting a specific one

Having recently started using the Zend framework, I am encountering an issue when trying to update data in the database and grid. Instead of updating a specific row, all rows are being updated. Can someone please assist me with this? Below is my controlle ...

"Embracing Progressive Enhancement through Node/Express routing and the innovative HIJAX Pattern. Exciting

There may be mixed reactions to this question, but I am curious about the compatibility of using progressive enhancement, specifically the HIJAX pattern (AJAX applied with P.E.), alongside Node routing middleware like Express. Is it feasible to incorporate ...

Select from a list to save

My goal is to create a feature where users can select a hotel name, number of days, guests, and peak time, the system will calculate them together and give a sum. Furthermore, I wish to store all user selections in the database, including the calculated to ...

A step-by-step guide on retrieving JSON information and saving it as a CSV file

Click here for JSON data on COVID-19 mobility trends. Here is a snippet of the JSON data: { "data": { "Albania": [ { "name": "driving", "title": "driving", "values": [ { "date": "2020-01-13", "value": "100" }, { "date": "2020-01-14", "value": "95.3" }, { ...

Looking for a JSON file in bash?

I have a JSON file that I need to extract a specific part from: { "expand": "names,schema", "issues": [ { "expand": "operations,versionedRepresentations,editmeta,changelog,renderedFields", "fields": { ...

Arranging a JSON array based on the numerical value within an object

I am interested in sorting an array from a json file based on distances calculated using the haversine library. The purpose is to find geolocations near a specified value and display the closest results first. function map(position){ var obj, ...

Unable to make an AJAX call to a Spring controller

I am currently attempting to make an ajax call to a Spring controller, but I am encountering an Error 405 stating "Request method 'POST' not supported." I have included my code below and would appreciate any suggestions on how to resolve this iss ...

Converting a Ruby hash to JSON using JSON.parse can sometimes lead to errors

Is there a way to convert JSON into a hash without encountering any errors? JSON.parse({"tag":"DownloadRequest","hash":"c8\u0006ùM]ÁaSßwÃ9\u0007Ãò\u0013Â4lÊ·|j\\ëç","part_number":0}) TypeError: exception class/object ex ...

Having trouble interpreting JSON attribute "null"

I encountered a problem while attempting to parse a JSON "null" property. Can someone help me understand what the issue might be? The JSON I used was as follows: { "properties" : { "null" : { "value" : false } } } I validated th ...

Gson: Omitting a field in a specific class without the use of annotations - Part 2

Currently I am working on serializing a Java object to JSON using Gson. My goal is to exclude a specific field in one class while keeping it in another. Here's a snippet of the code: Class A { var a; var b; } Class B { var a; var c; } Class C { ...

Combine and categorize into a unified object using groups as identifiers

My data includes the following: [ { "company.u_ats_region": "Region1", "hostname": "host1", "install_status": "1", "os": "Windows", "os_domain": ...

How can we efficiently retrieve newly submitted JSON data using AJAX?

Is there an efficient way for a user to input a number, submit it, and have it update a JSON page without refreshing the entire webpage? Can this be achieved using an ajax call? The code below retrieves game data, but I want it to update when the user su ...

Using get_json() in Flask server is not possible when JSON data is sent from an Android device using MultiPartEntityBuilder

My aim is to send a JSON formatted string from an Android device to a Flask server. To achieve this, I am utilizing Apache MultiPartEntityBuilder for sending, as I also need to include an image file in the same http post message. While I have successfully ...

Is there a way for me to retrieve a PHP variable and populate form fields with it?

In this PHP code snippet, the goal is to display a PHP variable in the value attribute of a form field textbox. <?php while($result=mysql_fetch_array($query)) { $title=$result["title"]; $date=$result["date"]; $body=$result["body ...

Tips on saving JSON response data to EditText in Android

Hey there! I am currently trying to retrieve the reg_no array value from the database and display it in an EditText without the need for any button clicks. I would appreciate some guidance on how to achieve this in my class file. String RegNo = Database ...

The Ajax form is failing to retrieve the expected PHP data

My login system uses a combination of ajax and php. The form validation is handled through javascript, with the form data then being sent to php for database checks. In the past, this method has worked well for me, but in this instance, it seems 'NOTH ...

JavaScript XML Serialization: Transforming Data into Strings

When trying to consume XML in an Express server using express-xml-bodyparser, the resulting object is not very useful. This is the XML: <SubClass code="A07.0"/> <SubClass code="A07.1"/> <SubClass code="A07.2"/> <SubClass code="A07.3" ...

Converting a text file to JSON in Python with element stripping and reordering techniques

I have a file with data separated by spaces like this: 2017-05-16 00:44:36.151724381 +43.8187 -104.7669 -004.4 00.6 00.2 00.2 090 C 2017-05-16 00:44:36.246672534 +41.6321 -104.7834 +004.3 00.6 00.3 00.2 130 C 2017-05-16 00:44:36.356132768 +46.4559 -104.5 ...

Deciphering complex JSON structures in PHP

I've come across a JSON structure that I need to parse. While I have managed to extract individual nested objects, it feels like there should be a simpler way to achieve this without having to search for each nested structure. Here is an example of t ...