PHP and AJAX internal 500 error - javascript

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

Related

Why are my PHP/AJAX with JSONP scripts returning HTML, JSON, and invalid JSON?

I am having some trouble with communication between my php script and my javascript file. It seems the javascript is receiving html, json, and "invalid json" from the php script that I have written.
In the Javascript code, the data variable evaluates to:
{"readyState":4,"status":200,"statusText":"success"}
This is not of the JSON format that I echo below (in either spot in the code where I do so). Based on my research, this is because the JSON echo in the PHP code is returning invalid JSON (which causes the PHP to return this as a result instead). However, when I check the console, I find the following:
<br />
<b>Warning</b>: mysqli::mysqli() [<a href='mysqli.mysqli'>mysqli.mysqli</a>]: (28000/1045): Access denied for ... in <b>..../.php</b> on line <b>xx</b><br />
{"status":"failure","message":"Access denied for ...."}
This is not printed because of any console.log statements I have in my code, this is printed as a result of Firefox's automatic console entry from the GET http://...../.php call.
The top line of code is the html that the PHP would return if this were not a JSON return, and the bottom line of the code above is the actual JSON object that I have created, and that I want to work with.
The reason I am posting here is because I cannot think of why the PHP would return html, my JSON, and JSON indicating invalid JSON.
I should also mention that I am receiving another error on the console:
SyntaxError: expected expression, got '<' --> file.php:1
This suggests to me that the browser is trying to interpret the php on the client end for some reason, but I'm not sure if that's accurate or not.
I think that I have an error somewhere that is the root of all of these symptoms, but after some time and research, I have not been able to find this error on my own.
The code I am using is shown below:
Javascript AJAX:
$.ajax({
url: "...url.../file.php",
crossDomain: true,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
data: {
name: email,
email: email
},
complete: function(data) {
console.log(JSON.stringify(data));
//this is where the {"readyState":4,"status":200,"statusText":"success"} appears
}
});
PHP (contents reduced to scope of this problem):
<?php
header("Content-type: application/json");
header("Content-Disposition: attachment;Filename=\"gamesUser.json\"");
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
.........
$data = array();
$conn = #new mysqli($servername, $username, $password, $dbname, $port);
//check the connection
if ($conn->connect_error) {
$data['status'] = 'failure';
$data['message'] = $conn->connect_error;
echo json_encode($data);
} else {
.........
$data['status'] = 'success';
$data['message'] = 'operations complete';
$data['fileURL'] = $fileURL;
echo json_encode($data);
.........
}
.........
?>
SOLVED!
The code:
echo $_GET['callback'].'('.json_encode($data).')';
along with changing ajax parameters:
type: "GET",
dataType: 'jsonp',
jsonpCallback: 'handleResponse',
data: data
Have fixed the problems. Thanks to everyone who assisted in the discussion.
I think , what you need is the callback function from jsonp , please go through the below example , you will get the idea
function myfunc(json) {
alert(json);
}
$.ajax({
type: "GET",
url: "http://example.com?keyword=r&callback=jsonp",
dataType: 'jsonp',
jsonpCallback: 'myfunc', // the function to call
jsonp: 'callback', // name of the var specifying the callback in the request
})
;
When an error happens in PHP, it displays the error information using HTML so you can see it properly in the browser. That's why you get the unexpected HTML, so you should make sure the PHP script doesn't show errors
You can suppress warnings for mysqli constructor (which I think is the one causing the problem) by prepending the at (#) sign:
...
#mysqli(...)
...
There are other ways of avoid showing errors, check http://php.net/manual/es/errorfunc.configuration.php#ini.display-errors
http://php.net/manual/es/errorfunc.configuration.php#ini.error-reporting

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");

Get data as response from php script on server

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);

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