Provide the Ajax caller with a JSON object exclusively

Is there a way to retrieve only the array in my success callback instead of the entire HTML page?

$.ajax({
  'URL': 'getData.php',
  success:function(data){
    alert(data); //I'm currently getting the whole html file
  }
})  

getData.php

<?php
 //Populate the array with database content

 echo json_encode( $columns );

?>  

How can I access only the contents of $columns without the additional markup?

Note: My PHP file consists solely of PHP code.

This is what appears when using the alert function:

https://i.sstatic.net/XqNQL.jpg

Answer №1

Ensure that your script returns a JSON string, as the HTML in it cannot be parsed.

I understand what you're saying - you can use JSON.parse(string) in JavaScript to parse the JSON sent by PHP.

Make sure that your PHP code only returns encoded JSON and no other strings or HTML.

Here is the updated JS code that should work correctly. You can check the desired output in the browser console.

$.ajax({
  'URL': 'getData.php',
  success:function(data){
    data = JSON.parse(data);
    console.log(data);
    alert(data); //Entire HTML file
  }
})

Answer №2

Setting the dataType and URL without single quotes is essential for the code to function correctly.

Here is an example of how you can implement this:

 $.ajax({ 
    type: 'GET', 
    url: 'fetchData.php', 
    dataType: 'json',
    success: function (data) { 
        $.each(data, function(index, element) {
            /* Perform operations on each array element */
        });
    }
});

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

Adapter is failing to show the accurate information

Currently, I am working on an application where I need to retrieve a large JSON data from the server and display it in a list view. However, I am facing an issue where the same value is being repeated in all the list items, even though the number of items ...

Persisting jQuery UI position in database and showing it on the screen

i am currently working on a project using jquery ui for resizing and drag and drop features. i need to figure out how to save these changes in a database. here is the progress i have made so far: http://plnkr.co/edit/rAwEs6eUS2JPmFMxqQ?p=preview i am look ...

Ensure that the div automatically scrolls to the bottom when it is loaded, and also when new data is added - using angular

My goal is to replicate the functionality of the iPhone's "Messages" app on a web application using AngularJS or any other JavaScript framework. Each message will be contained in a div element within a larger container. When a new message is added, I ...

Why is it that Object.getOwnPropertyDescriptors does not function on HTMLElements?

Upon traversing the prototype chain, one would expect to find Object.prototype at the bottom (or top?), leading to the assumption that they would function like typical objects. However, when using Object.getOwnPropertyDescriptors, the properties obtained d ...

What is the best method to pass a JavaScript file array to a Node.js server?

Is it possible to transfer data from a Javascript file linked to an HTML page to a Node.js file on a post route without displaying it on the HTML page? If so, what is the best way to accomplish this? ...

Setting Metadata Dynamically in Vue Router

Currently, I have a Single Page Application (SPA) built with Vue and Vue Router. The setup mimics an iOS app where the title in the navigation bar changes as you navigate deeper into the views. Right now, the titles are hardcoded in the routes.js file, but ...

What's the best way to test a simple Bearer Strategy implementation in Passport.js using Postman?

Currently, I am diving into the realm of passport authentication specifically how to authenticate a Restful API. I am feeling a bit uncertain about testing what I have. Here is the BearerStrategy code snippet: var BearerStrategy = new Bearer({ }, fun ...

Step-by-step guide on adding a new array to a JSON file within an Android application

In my app's data folder, there is a JSON file that contains information. { "user": [ { "identifier": "1", "name": "xyz", "contact": [ { "contact": "123" }, { "contact": "456" ...

Error: Unable to convert undefined or null values to an object - encountered while attempting to run a MySQL query within the router

I have a situation where I am running multiple MySQL queries in a route. The final query is a SELECT statement using the 'email' value retrieved from a previous query as a condition. When testing these 'email' values in MySQL Workbench, ...

My PHP script is not functioning correctly with Ajax

I am currently working with HTML5, PHP, and JavaScript. My goal is to implement Ajax in order to display the sizes of a selected product when an option is chosen from #productoSeleccionado. However, I believe that there may be an issue with my code as the ...

Issue with AJAX POST request not retrieving data from PHP MySQL database using AJAX

I am facing an issue where the post data is not passing to get-data.php while trying to retrieve data from the database using ajax to insert it into another element. Any thoughts on what might be causing this problem and possible solutions? https://i.stack ...

Fetching real-time Twitter search feeds through dynamic AJAX requests

Previously, I successfully used JSON to retrieve hash tag feeds from Twitter and Facebook. However, currently the feeds are not updating dynamically, indicating a need for Ajax implementation. Unfortunately, my lack of knowledge in Ajax is hindering this ...

Comparing various object fields to a single input value in JavaScript

I have a challenge with filtering a large dataset of products based on user input values. Here is an example of my product dataset: const products = [ {id: 0, name: "Product1", brand: "Theraflu", itemCode: "THE110", price: 5 ...

What is the best way to overlay a 2D text layer on top of a Three.js scene?

I have successfully created a basic 3D scene using JavaScript. The scene features a THREE.SphereGeometry paired with a THREE.MeshNormalMaterial. However, I am now faced with the challenge of adding a text layer on top of the Three.js scene. Query: What is ...

How to effectively test a form submission with an external API using React, Jest, and Enzyme?

I have integrated a geocoding API to verify address submissions on a form. Upon submitting the form, the geocoding API is called first, followed by validation of the remaining form fields. class Form extends React.Component { geocode = (streetAddress, cit ...

Guide to customizing the Autocomplete jQuery plugin to mimic Google's result replacement feature

I have implemented the jQuery plugin Autocomplete like Google for two form fields - foo and bar (which is dependent on the value of foo): $(function() { $("#foo").autocomplete({ minLength: 3, limit: 5, source : [{ u ...

Looping through a JSON object in Highcharts to populate data series

I'm brand new to Java Script and I'm on a mission to loop through my JSON object and populate the Highcharts data series. You can take a look at my static demonstration of what I'm trying to achieve on JS Fiddle. Check out JsFiddle here Any ...

Problems with radio button serialization in jQuery form plugin

I've created a basic form: <form class="dataform" method="post" id="settings" action="/"> <input type="radio" name="shareSetting" value="n"/> <input type="radio" name="shareSetting" value="y"/> <input type="button" na ...

The data extracted from JSON is not directly displayed on the user interface

In this scenario, I utilize the JSON API from OpenWeather to extract weather data. I have a class called Weather with various properties. Within the Weather entity, there is a function named downloadWeather that parses the API data and saves the values in ...

Having trouble receiving a response from the server?

I am in the process of developing an application that stores data on a database and retrieves it when needed. On the server side, I am utilizing PHP, while on the client side, I have a file that gathers input and transmits it to the PHP file. new AsyncTas ...