Get data as response from php script on server - javascript

I'm sending some data(options) via POST with javascript to a php script that's on my server, which does a mysql query and should return data back to the current page.
This is the jquery code I'm using -
$.post( "contact.php", {min_age:"25"})
.done(function(data) {
console.log(data);
});
Now I've got the required data extracted from mysql and encoded it to json, and stored it in a variable in my php script in server. How do I post it back to the current page?

In order to 'send the data' from php, you need to echo it, after setting the correct header:
header('Content-Type: application/json');
echo json_encode($data);

Related

PHP and AJAX internal 500 error

I have a strange problem, when I send data in POST with AJAX in JQuery to query SQL in php and push the data in array, the server return 500 error.
This the php file :
require_once 'db_connect.php';
$objConn=new ConnectionDB();
$connection=$objConn->ConnecteDB();
header('Content-Type: text/plain');
$dataRetourn=$_POST["test"];
$debut=$_POST['debut'];
$fin=$_POST['fin'];
$proute=array();
$i=0;
$i=0;
foreach ($dataRetourn as $data){
$imei = $data["aniImei"];
$requete="SELECT latitude, longitude, dateHeure
FROM anilog
WHERE anilog.imei='$imei' and dateHeure BETWEEN '$debut' AND
'$fin'
ORDER BY dateHeure ASC";
$resultat1=mysqli_query($connection,$requete);
while($donnees=mysqli_fetch_assoc($resultat1)){
$dataRetourn[$i]["path"][]=$donnees;
}
$i=$i+1;
}
echo json_encode($dataRetourn);
mysql_close($connection);
My query AJAX :
var options = {
url: "js/controller/getParcours.php",
dataType: "text",
type: "POST",
data: { test: parcours, debut : datep.debut, fin: datep.fin}
};
$.ajax(options).done(function(data){console.log(JSON.parse(data));});
PS: the PHP version on the server is the 5.3
And the variable parcours in query AJAX is $dataretourn in php script and it's an array of object
A HTTP 500 error code always means there is something wrong with your serverside code, your case being your PHP script. This may either be a syntax error or a bug.
You should be able to find more information in your server log, if you are using nginx this would be /var/log/nginx/error.log and if you are using apache, this would be /var/log/apache2/error.log (unless otherwise specified in your VirtualHost/site configuration).
However it is highly discouraged to use PHP 5.3 since it is deprecated, more information here: PHP version lifetime

Why php json response does not send back the data array to ajax jquery request?

I have made an ajax request to the php server where I send a data from a form request and I would to get back the same data from the server just for testing requests and responses of the same data throwing between the client and the server.
$.ajax({
method: "POST",
url: "addRaces",
dataType: "json",
data : sending_data,
success : ...
})
sending_data is an array like {field_form_name : value}
The server responds to the request with the following code :
$data = [];
foreach ($request->Input() as $key => $value) {
$data[$key] = $value;
}
return json_encode($data);
The same data should come back to the client, but nothing happen with an alert(response) or a jquery showing debug data like $('#debug').html(response);
The strange thing coming up when I try to push the server answer like
return json_encode([
'debug' => $data['name']
]);
and showing results to client like
$('#debug').html(response.debug);
it is working for a single key-value response showing the properly value field I have send from the client.
Other wise whether I send the full data as an array nothing is shown in the debug area of the client.
return json_encode($data); wont work. as it is returning the json string to the calling method which is not your jQuery at front end. Don't confuse front end (html javascript, jQuery, etc...) with back end (PHP) the two of them are running in different machines. One at client end and another at your server.
you should use echo json_encode($data); this will output the json string and your web server will send it to the front end.
Make sure you are echoing the data not returning as #bansi said, if you are echoing it already then debug using var_dump(json_encode($data)) . If json_encode() found errors it will return False instead of the expected json array.
You should debug using the developer tools instead of using code $('#debug').html(response.debug);. The Network tab of developer tools is very useful to debug HTTP requests, it will show response header and body of your requests.
In your case, just change return to echo like #bansi's answer. The return command does not print the data so you did not get anything in the response.

saving json data to json file using ajax PHP

My json file looks like this:
count_click.json
[
{
"link": "google.com",
"count": 2
},
{
"link": "yahoo.com",
"count": 3
}
]
now I open this file using
$.getJSON('count_click.json',function(data){
// do something with data
var stringData = JSON.stringify(data);
$.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'http://127.0.0.x:3xx9/update.php',
data: {stringData: stringData},
success : function(d){
alert('done');}
})
}) // end of getJSON function
update.php
<?php
$a = file_get_contents("php://input");
file_put_contents('http://127.0.0.x:3xx9/count_click.json', json_encode($a));
?>
I get error in the browser console:
POST http://127.0.0.x:3xx9/update.php 404 (Not Found)
But the file is there. When I go to this http://127.0.0.x:3xx9/update.php in the browser, I see the contents of the php fine perfectly fine.
You could edit your PHP:
<?php
$a = $_POST['stringData'];
// you should check $a consists valid json - what you want it to be
file_put_contents('count_click.json', $a);
You really should check that posted data to be valid and not saving something unwanted. Also you could check that request really is POST -> $_SERVER['REQUEST_METHOD'].
Maybe you find some other methods to improve security (for example only allow post from own domain...).
A few problems.
file_get_contents("php://input"); Why? You are already sending a Post with data, no need to complicate things with a stream.
Also file_put_contents needs the path to the actual file on disk, not a URL!
data: {stringData: stringData} from your AJAX request means you can access it on your server with $data = $_POST['stringData'];.
Simply echo something out to see if you are actually getting anything.
echo json_encode( array("Payload" => $_POST['stringData']) );
If that doesn't work, try accessing the endpoint with your browser (not the file as that does not need PHP for the browser to read it).
Point your browser to http://127.0.0.x:3xx9/update.php and on your server, simply
echo "Request received!";
If you see that in your browser, your endpoint is working and you can continue troubleshooting. If you don't, then this is beyond JS and PHP and probably has to do with your server's settings. If you are using RStudio's Shiny Server, then that does not work for PHP
In any case, your endpoint should always return something when called. Not just save the file. It is just good practice.
header("HTTP/1.1 200 OK");

How to hide api key using php?

everyone. I'm trying to create league of legend api, but I need to hide the api key. I know there is no way to hide the key from the front-end, so this is how I did it, I'm not sure this is the best way to do it. Please help me!! Thanks!
HTML.file
var getID = function(playerName) {
$.ajax({
type: "POST",
url:"test.php",
dataType:'json',
data: {'url': "api/lol/na/v1.4/summoner/by-name/"+playerName+"?"},
success: function(data){
playerID = data[playerName].id;
console.log(playerID);
}
});
};
So every time I'm calling ajax, I'm making a ajax request to the test.php file, and pass the url to it, then the php code will use the url to get request from the game server and send back the result to front-end.
test.php
<?php
header('Content-Type: application/json');
$url = $_POST['url'];
$json = file_get_contents('https://na.api.pvp.net/'.$url.'api_key=key');
$obj = json_decode($json);
echo json_encode($obj, JSON_PRETTY_PRINT);
?>
As long as the Ajax request will only trigger for a valid, authenticated user with an established session this looks good. Otherwise, anyone could call it with arbitrary 'playerNames'.
It will definitely prevent your API key from being exposed.

Getting JSON data from a PHP script using AJAX

My PHP script, 'getNews.php', (which works when I run it in the terminal and returns the correct data) is as follows:
<?php
header('Content-Type: application/json');
$db = new PDO('mysql:host=hostname;dbname=table', 'name', 'password');
$sql = "SELECT * from `news` ORDER BY date";
$result = $db->query($sql);
echo json_encode($result->fetchAll(PDO::FETCH_ASSOC));
?>
In my Javascript (I have JQuery loaded), I am attempting to pull this data in the following manner:
$(document).ready(function() {
$.getJSON("getNews.php", function(data) {
console.log(data);
});
});
which does nothing. When I change it to:
$(document).ready(function() {
$.get("getNews.php", function(data) {
console.log(data);
});
});
It writes the entire text of the php script to the console. Basically, it doesn't seem to be executing the php script or retrieving the json object at all. Thoughts?
Do you have a web server (like apache or nginx) installed? "It writes the entire text of the php script to the console." = You aren't invoking a PHP processor. Are you loading it like file:///something, or via http://something?
If you are using HTTP, make sure your web server knows to process PHP files. This usually involves editing a .ini or .cfg file; I can't tell which, because you don't mention what web server you are using.
It writes the entire text of the php script to the console
It could be that your server doesnt have php installed/configured. If thats not the case then see if this works for you
function prsJSN() {
$.ajax({
type: "get",
url: "getNews.php",
success: function(json) {
var dataArray = jQuery.parseJSON(json);
},
error: function(request, status, error) {
alert(request.responseText);
}
});
}

Categories

Resources