How to receive echoed data from a php file via URL? [duplicate] - javascript

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 3 years ago.
I'm trying to get some basic Javascript and PHP working for a coding challenge I'm taking part in and I need to receive a JSON object from a PHP file to use in my Javascript that displays the current date on a HTML page. I've tried a few different methods and can't seem to get any to work, is there something I'm missing here?
I've tried using jQuery getJSON as well as running the PHP in the same HTML file as the Javascript.
This is the PHP file and its output:
echo json_encode([
"date" => getthedate()
]);
function getthedate() {
return date("Y/m/d");
}
{"date":"2019\/07\/04"}
This is what I've most recently been trying in Javascript:
function getDate() {
var theDate = $.getJSON(
"http://localhost/coding-challenge/get-date.php",
function(data)
);
JSON.parse(theDate);
document.getElementsByClassName("date")[0].innerHTML = theDate;
}
I was expecting this Javascript to retrieve the JSON object that the PHP file echoes and then display it in the HTML file's "date" class, an empty paragraph. However this just results in a blank space where the date paragraph is.

$.getJSON is asynchronous, so you should set the data inside it's success callback:
function getDate() {
$.getJSON("http://localhost/coding-challenge/get-date.php", data => {
document.getElementsByClassName("date")[0].innerHTML = data;
});
}

Try to send the correct HTTP resonse header for JSON. Then jQuery will parse the response for you.
header('Content-Type: application/json');
echo json_encode([
'date' => getthedate()
]);
function getthedate() {
return date("Y/m/d");
}
JS
$.getJSON("http://localhost/coding-challenge/get-date.php", function( data ) {
console.log(data);
alert(data.date);
});

Related

How to show new line in the alert popup from json_encode? [duplicate]

This question already has answers here:
What is the difference between single-quoted and double-quoted strings in PHP?
(7 answers)
Closed 2 years ago.
I am showing a popup window using ajax after calling my php file whenever I am able to write successfully in a file.
I am showing popup using below code where I use alert.
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<script>
$(function() {
$('form').submit(function(e) {
e.preventDefault();
$.post({
url: 'savefile.php',
data: $(this).serialize(),
}).done(response => {
console.log(response);
response = JSON.parse(response);
if(response.message) {
alert(response.message);
}
});
});
});
</script>
The json I am returning is this:
echo json_encode([
'success' => true,
'message' => $ret . ' bytes saved to file. \n All data saved.',
]);
I wanted to show on popup as shown below where All data saved. goes in new line instead of getting shown in the same line. But when I try above code it is just escaping it instead of showing in new line. Is there any clean way to do this?
10 bytes saved to file.
All data saved.
PHP interprets backslashes literally when expressed in single quotes.
Instead, use doubles and the newline will be parsed and honoured.
'message' => $ret . " bytes saved to file. \n All data saved."

Ajax $.getJSON method to return html and json together [duplicate]

This question already has answers here:
jQuery Ajax return html AND json data
(4 answers)
Closed 5 years ago.
Is there a way to fetch html data and json data together from the server using ajax getjson or any other method.
For example,
Fetch.php contains following:
$count=$conn->rowCount();
while($fetch=$query->fetch()) {
echo "This is data";
}
$array=array("itemcount" => $count);
echo json_encode($array);
What I want from above fetch.php file is to return html data as well as $count value.
$.getJSON( 'fetch.php', {'id': uid}, function(data){
$('#results').append(data);
$('#offset').(data.itemcount);
}
But this is not working. It seems getjson method is not designed to display html data. Then at the same time I could not display json with $.POST method either. What is the solution to this problem then?
Thanks
Nikhil
$count=$conn->rowCount();
while($fetch=$query->fetch()) {
$msg = "This is data";
}
$array=array("msg" => $msg , "itemcount" => $count);
echo json_encode($array);

JSON response at ajax request to JS variables

I am trying to upload files with dynamic names and get those dynamic names back.
In detail, I have 2 page form.php and upload.php. When upload button is pressed on form.php then request sent to upload.php, where 2 files (DLpath and PhotoIDPath) are uploaded to server with dynamically names e.g :
DLpath=documents/20161130232311i8hGn0HzJT276415832.png
And
PhotoIDPath=documents/20161130232311SSRqCyIbKKalock.png.
It is working fine. Then on upload.php, I am encoding those file names as JSON array i.e.
$response = array ('DLpath'=>$Dlpath ,'PhotoIDPath'=>$PhotoIDPath);
echo json_encode($response);
And firebug snapshot is :
I want to get DLpath in var jsDlpath and PhotoIDPath in var jsPhotoIDPath
And my code ( Not working) to get response is :
complete: function(response)
{
var jsDlpath=response.DLpath;
var jsPhotoIDPath=response.PhotoIDPath;
alert(jsDlpath+" - "+jsPhotoIDPath)
}
And alert show :
undefined - undefine
If you can help me to gwt those values in js variables, I will be very thankful to you.
Since you're encoding you response in server side you should parse it in the js side, you could use $.parsejson() :
success: function(response)
{
var response = $.parseJson(response);
//if $.parseJson dont work, use JSON.parse
var jsDlpath=response.DLpath;
var jsPhotoIDPath=response.PhotoIDPath;
alert(jsDlpath+" - "+jsPhotoIDPath)
}
NOTE : Use success/done callback instead of complete.
Hope this helps.
If running in pure javascript you will find that there are two response attributes: responseText and responseXML. You probably want:
var data = JSON.parse(response.responseText);
A complete example, using curl from https://gist.github.com/bitdivine/7ddd943387a4350336dd (but jquery will do fine as well) to get open issues on Github:
curl('https://api.github.com/repos/gchq/CyberChef/issues?state=open')
.then((res) => JSON.parse(res.responseText))
.then((data) => console.log(data))

Return JSON object from php script

I am making an AJAX GET request using jQuery to a PHP file. I want the PHP script to return a JSON object, however, currently it is returning a JSON string. I realise I can use JSON.parse in the jQuery code, however, any experience I have in making an AJAX call to an API a JSON object is returned. I am trying to do the same with the php script however, it is returning a string as opposed to an object.
Does anyone know what the best practice is here, and if the best practise is to return a JSON object how I would do this using PHP?
Please see the code below:
js
$.get('test.php', function(data){
console.log((data));
});
php
<?php
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
In your PHP file, change the content type to application/json.
JS
$.get('/process.php', function(data) {
console.log(data);
} );
PHP
<?php
header( "Content-type: application/json" );
$jsonAnswer = array('test' => 'true');
echo json_encode($jsonAnswer);
Then your console should read Object {test: "true"} rather than just the JSON string.
Add json to the end of your get function to return json
$.get('test.php', function(data){
console.log((data));
},'json');//here
and/or add this header in php
header('Content-Type: application/json');
more info here
Without modifying PHP script you can do:
$.get( "test.php", function( data ) {
var arr = $.parseJSON(data);
console.log(arr);
alert(arr.test);
});

How to receive data in php sent from javascript [duplicate]

This question already has answers here:
Reference - What does this error mean in PHP?
(38 answers)
Closed 8 years ago.
I am sending some data from my pain page to app.php using javascript
$(document).on('click', '.app' , function(){
var data=$(this).attr("id");
window.location="application/app.php?data="+data; //data send in this statement
});
my php code is this :
<?php
if($_GET['data'])
{
echo $app_id=$_GET["data"]; receiving data
}
?>
It works sometime but now it is giving Notice in an alert box: Undefined index data in app.php. But it is showing the echo.
I want to know how I can receive the data I need using $_POST or $_GET. like we receive by making an Ajax call. But I haven't specified something like this in Javascript. is there any way to this?
I want to clarify that the data exists and it is non empty because echo is successfully printing that on the page
Try this:
<?php
if(!empty($_GET['data']))
{
$app_id = $_GET['data']; // receiving data
}
?>
Please be aware that passing data without validation is not secure. Reccomended reading: https://www.owasp.org/index.php/Category:OWASP_Top_Ten_Project
use isset() to first check if the key exists. data won't exist in $_GET when it's not passed via a parameter in the url
you probably want some logic that looks like this:
if (isset($_GET['data'])) {
if (!empty($_GET['data'])) {
$appId = $_GET['data'];
}
else {
// data exists, but it's empty
}
}
else {
// data does not exist
}
and maybe you even want to check if it's a valid id, like being numeric or something

Categories

Resources