Accessing PHP output within Jquery

Even though I know PHP is a server-side script and JavaScript is client-side, I encountered an issue.

I struggled to bypass browser security when making an AJAX request to another domain. Feeling lost, I decided to turn to PHP for help.

The challenge I faced was that I could only use JS and CSS to manipulate my tracking system!

My goal was to incorporate a newsfeed.csv, so I crafted this PHP code to retrieve the CSV file, convert it, and store it in the variable $json.


<?php
$file="http://www.jonar.com/portal/partner/js/newsroomcustomer.csv";
$csv= file_get_contents($file);
$checkit = utf8_encode($csv);
$array = array_map("str_getcsv", explode("\n", $checkit));
$json = json_encode($array);
?>

I am wondering if there's a way to perform an AJAX GET request to receive the output variables—basically the JSON format of my CSV.

This method would allow my PHP script on the webserver to access links from any domain.

Thank you all for your help :)

Answer â„–1

As Julio mentioned in his comment:

To display the generated JSON string, simply use echo. It's as simple as typing echo $json.


Once your PHP script successfully outputs the desired JSON string, you can make an AJAX request to your script using the code below (assuming you are utilizing jQuery for convenience):

$.get('script.php', function (data) {
   console.log('Received data: ', data);
});

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

Utilize Javascript and JQuery to implement sending a custom header in an OPTIONS preflight API request

Snippet: $.ajax({ type: 'GET', dataType: 'json', url: api, xhrFields: { withCredentials: true }, beforeSend: function (xhr) { xhr.setRequestHeader('Authorization', "Basic [my auth token]"); }, ...

What causes an asynchronous function to exhibit different behavior when utilized in conjunction with addEventListener versus when manually invoked?

I was delving into the concepts of async and await keywords and decided to create a basic demonstration using an HTML file and a corresponding JS file. In my example, I defined two promises - promise1 and promise2. The handlePromises function uses async/ ...

Navigating Through Grid and Card Content in React

My goal was to minimize the amount of code by incorporating a reusable component into my application. I am facing an issue on how to iterate through the columns and rows in Grid, Card, and Table. What would be the optimal solution for this problem? Please ...

Issue with dynamically adjusting flex box width using JavaScript

Currently, I am developing a user interface that heavily relies on flexbox. The layout consists of a content area and a sidebar that can be toggled by adding or removing a specific class. Whenever the sidebar is toggled, the content area needs to be manua ...

Combining Two Models in Sails.js

I'm facing an issue with linking two models in sails. I have two models: 'Singer' and 'Country'. In the 'Singer' model, I have an attribute 'singer_country' which represents the id of the 'Country' mod ...

After closing the box, make sure to hold it securely

After clicking the button and closing my box with jQuery (Toggle), I want the state of the box to be remembered after refreshing the page. If the box was closed, it should remain closed upon refresh, and if it was open, it should stay open. I am looking ...

Troubleshooting Ajax Errors with MailChimp

Currently, I have been using a method by @skube to submit a Mailchimp form. It has been working successfully so far, but I would like to be able to display any error messages from Mailchimp on my website. For example, if someone is already subscribed, pro ...

Guide on sorting an array within a specific range and extracting a sample on each side of the outcome

I need a simple solution for the following scenario: let rangeOfInterest = [25 , 44]; let input = [10, 20, 30, 40, 50, 60]; I want to extract values that fall between 25 and 44 (inclusive) from the given input. The range may be within or outside the inpu ...

What is the best way to interpret a nested JSON object?

Recently I've crafted an object that looks like this. myObj = { "name":"John", "age":30, "cars": [ "car1":"Ford", "car2":"BMW", "car3":"Fiat" ] } While it's pretty straightforward to read the name and age properties, I find ...

Strategies for managing the result of findElements?

Snippet A resultsBoard.findElements(By.css(mySelector)).then(function(elements) { elements.forEach(function(val, idx) { elements[idx].getText().then(function(text) { console.log(text); }); }); }); Snippet B resultsBoard.findElements( ...

"Learn how to deactivate the submit button while the form is being processed and reactivate it once the process is

I have been searching for solutions to this issue, but none seem to address my specific concern. Here is the HTML in question: <form action=".."> <input type="submit" value="download" /> </form> After submitting the form, it takes a ...

Modulus % will replace a 0 with a 2

When using PHP, the Modulus operator % calculates the remainder when $x is divided by $y. I attempted to use this code: <?php print(100000000165 % 5); The result should have been 0 but it showed up as 2. ...

Steps to Export Several Fusion Charts into Individual Image Files

My webpage contains multiple charts created using the Fusion Chart library. There are three different charts on the page, and I want to export each chart as a separate PNG file. However, when I click the export button, it generates separate images of the ...

Using Svelte to effectively connect to a specified object within an array

Check out this code snippet: <script> let data = [ {id: 1, first: "x"}, {id: 2, second: "y"} ]; </script> <input type="text" bind:value={data.first}/> If you modify the value in the input field and ...

The error occurring in the React app is a result of the page rendering prior to the API data being fetched

Utilizing the following component for my Nav, I aim to showcase the current weather based on the user's location. However, an issue arises as the page is being rendered before retrieving data from the openWeather API. import React, { useState, useEffe ...

Avoid using the jQuery.get() function

$.get('./mods/webim_offline_email.php', {name: $('#webim_name').val(), email_address: $('#webim_email_address').val(), msg: $('#webim_msg').val()}, function (data){ alert(1); $('#webim_offline_form' ...

I'm having trouble accessing the data stored in req.user within the user controller, despite having integrated it into the user isLoggedIn middleware

I am encountering an issue where I cannot access my req.user in the usercontroller, even though I have implemented it in the usermiddleware. Both storing data in req.user and retrieving data using req.user from the middleware to my controller are not work ...

Retrieve the initial entry from a Container for every row in the Table

I'm facing an issue with a table I have on my website. Here is the structure: <table id="fieldContainer"> <tr><td><input id="input1"></td><td><input id="input2"></td></tr> <tr><td>< ...

Is there an IDE that can effectively rename classes in Zend Framework 2 during refactoring?

In a zf2 application, the classname is spread out across different config/autoload strings, use statements, template_map keys, and more. Is there a tool or plugin that can consistently index these occurrences and effectively refactor (specifically rename) ...

Tips for enhancing the performance of this PHP script

Our server provider recently informed us about the excessive creation of temporary tables by Mysql on disk, leading to Disk I/O abuse. This issue seems to be caused by the following code: $features = db_get_array("SELECT DISTINCT(a.description), b.parent_ ...