I have one php file and inside this I echo a file_get_content. The file content I am including is HTML with JS.
Later in the script I echo a JSON array back to an AJAX call.
Why is the HTML content also showing in the result and not just the JSON array. How can I only get the JSON result echoed to the AJAX call…and not the HTML on the page. I have also tried print_r instead of echo but same result.
This code will display everything that is returned from that URL. You could assign it to a variable and then parse the DOM that is returned to extract what you need, or you could pass in a parameter that would tell the php to only return what you need.
I need everything in that code to execute since the code is doing a security check for me. The only way for me to make it work is when I use echo file_get_contents…
Here is the structure of the main php giving the issue:
//This contains HTML and JS
echo file_get_contents ('https://www.mysite.com/jwt/admin_check_access.php');
<?php
....
$new_data = json_encode($chart1, JSON_PRETTY_PRINT);
echo $new_data;
?>
The above code echo’s everything and I only want $new_data to echo back to the original AJAX call.
How would I do this. I have no idea
You either need to put the code that produces the json output in its own file, then use the URL of that file/page in the AJAX call or you need to organize the code on your page so that the html document is at the end, so that you can add conditional logic to detect if the code on that page is responding to an AJAX call and can output just the json data, then exit/die without outputting any of the html document.
Next, your code making a https request to the admin_check_access.php file is executing the …access.php code in a separate instance of the web server, so any result/session variable created in that code is not available in your main code. It is producing the expected output, at the expense of an extra https connection and web server process. This takes 100’s of times longer than requiring the file through the file system. If you want the result/session variable that is set in the code to be available in your calling php code, you need to ‘require’ the file through the file system, not through a URL.