I have a page that, upon loading, fills 3 drop down menus for uses to select from. On my localhost, this works fine, but on my live server I get the error in Developer Tools "POST (my site's name) 500 (Internal Server Error) jquery.js:8630.
Here is the jquery:
$(function() {
//after load, populate lists
Update_List_ProcedureAreas_Schedule();
Update_List_Patients_Cancel();
Update_List_Cancel_Reasons();
});
Here's one of the functions, but the other two are nearly identical, but all 3 fail. I send to a generic functions php file the function that I want to run, and if there are any parameters with the function as well. Maybe be a bit weird, but it helps me organize my code:
function Update_List_Patients_Cancel() {
$.ajax({
url: 'php/functions.php',
type: 'POST',
dataType: 'json',
cache: false,
data: {Function_ID: 'pull_patient_list_cancel'},
success: function(data){
var dropDown = document.getElementById("selectedpatient_cancel");
dropDown.options.length=0;
dropDown[dropDown.length] = new Option('', '')
for (i = 0; i < data.length; i++) {
dropDown[dropDown.length] = new Option(data[i].Patient_Name, data[i].Patient_UID)
}
},
error: function() {
}
});
}
Here is the PHP in 'php/functions.php' which takes the Function_ID and then uses a switch to verify the input and then call the function with any appropriate variables:
<?php
session_start();
//Make sure a funciton was sent
if(isset($_POST['Function_ID']) == true) {$tempFunction = $_POST['Function_ID'];}
else {echo "No fuction selected";}
//switch to functions
switch($tempFunction) {
case 'pull_patient_list_cancel':
pull_patient_list_cancel();
break;
}
//Pull patient list for cancel drop down
function pull_patient_list_cancel() {
require $_SESSION['db_connect']; //code to connect to the database, which is successful, btw
$returnArray = array();
$sql = "
SELECT Patient_UID, Patient_Name
FROM tbl_patients
WHERE Active = 1
";
if($result = $conn->query($sql)) {
$conn->close();
foreach($result->fetch_all(MYSQLI_ASSOC) as $row) {
$returnArray[] = $row;
}
echo json_encode($returnArray);
} else {
$conn->close();
echo "Failed - pull patient lists cancel";
}
}
It looks like for some reason, I'm not able to execute in the foreach loop. I've put in bogus echos to see where the function stops running, and it won't output any echo within the for each loop or after it, but it will up until that loop starts. I've check the response log in Development Tools and see the bogus echos coming through until the foreach loop, and then nothing.
Any ideas?
------------Solution-----------------
The problem was that I had mysqlnd installed on my localhost xampp setup, but it did not install on my digitalocean lampp server that I set up today. So that made the fetch_all(MYSQLI) not work. However, I could stick with the mysql installation and use fetch_assoc() and it worked fine.
But, I ended up installing mysqlnd on my digitalocean droplet by using:
apt-get install php5-mysqlnd
and then restarting the server with
service apache2 restart
and now all of my fetch_all(MYSQLI) functions work. Thanks everyone for your help.
You cannot close the connection before you fetch the results for the foreach. Move the connection close after the loop.
Better still, remove both connection close statements, and put a single one after the else block.
if($result = $conn->query($sql)) {
foreach($result->fetch_all(MYSQLI_ASSOC) as $row) {
$returnArray[] = $row;
}
echo json_encode($returnArray);
} else {
echo "Failed - pull patient lists cancel";
}
$conn->close();
There is syntax error on your PHP function page....
You cannot use isset like this
change your code from
if(isset($_POST['Function_ID']) == true) //which is wrong
To
if(isset($_POST['Function_ID']) && $_POST['Function_ID'])==true)
// this is the right way
Connection should be closed after all the program has executed and
else{}
$conn->close();
Related
Requesting JSON from php script :
var channelList;
$(document).ready(function() {
$.ajax({
url: 'channellookup.php',
dataType: 'json',
error: function(){console.log(arguments)},
success: function(data) {
console.log(data.success);
channelList = data;
}
});
});
Now to the interesting part: The error message in the console reads like this:
Arguments { 0: XMLHttpRequest, 1: "parsererror", 2: "Invalid JSON: <?php
header('Content-type: application/json'); // To ensure output json type.
class MyDB extends SQLite3
{
And so on. My whole PHP code is in that message. Something must go completely wrong here.
Here is my PHP in full
<?php
header('Content-type: application/json'); // To ensure output json type.
class MyDB extends SQLite3
{
function __construct()
{
$this->open('database_sqlite3.db');
}
}
$db = new MyDB();
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
$sql =<<<EOF
SELECT * from channels;
EOF;
$ret = $db->query($sql);
$channelList = array();
while($row = $ret->fetchArray(SQLITE3_ASSOC) ){
$channelList[] = $row;
}
echo json_encode($channelList);
$db->close();
?>
as you can see I do encode as json. As I said this works in the terminal.
Please keep in mind that I do not want to use the json in my html yet so the page generating before the asynchronous request is completed isn't an issue yet.
Is the problem maybe that I am not doing this on a remote server but on local files? As I understand the Browser should be able to handle this case.
After you send the header, you are echoing the connection status from the db.
Remove this lines:
if(!$db){
echo $db->lastErrorMsg();
} else {
echo "Opened database successfully\n";
}
And put the header above the JSON output:
header('Content-type: application/json');
echo json_encode($channelList);
$db->close();
I'm quite sure that your PHP didn't compile at all. This is because the result that was returned, is in fact the body of your php file, indicating that no translation took place.
You can check if your PHP instance is running by creating a file with the code:
<?php phpinfo() ?>
And use your browser to navigate to that page and see if there are any output. You want to check your PHP/Apache installation until the output is correct.
As to why your webtool work, I cannot phantom any reason. It should fail in the same way.
I have an Ajax script that makes a call to a php file on my server every twenty seconds.
The server then runs a simple mysql query to return the contents of a particular field.
If that field is blank I want the php file to echo the word "pending", which when caught by the success handler will recall the initial function. However if that field is not blank, it will contain a URL to which I want to redirect the user to. That field will update any where between 5 seconds and 5 minutes from the start of the first call and that time cannot be changed.
I think the main issue may be with my php file, in that I dont think it is echoing the data in a way that the success handler recognises. However I have detailed both parts of my code as whilst the success handler seems to be constructed correctly I am not 100% sure.
Very new to this, so apologies if I have not explained myself correctly but if anyone could assist that would be great:
UPDATE - for clarity what I am looking to achieve is as follows:
Ajax call to my php file.
PHP file queries database
If field queried contains no data echo the word "pending" to the ajax success handler (IF) which in turn recalls the original function / ajax call.
If field queried contains data (will be a URL) echo this result to the ajax success handler (ELSE)in a format that will redirect the user via window.location.assign(data).
FURTHER UPDATE
I managed to solve this question with using a combination of the advice from #mamdouhalramadan and #martijn
I also have changed setInterval to setTimeout as the poll function was causing responses to stack up should the server be running slowly and as such cause errors. I also added in cache: false and a further option in the success handler to take into account slightly different behaviour in IE:
AJAX
function poll() {
$.ajax({
url: 'processthree.php?lead_id='+lead_id,
type: "GET",
cache: false,
async: false,
success: function(data3) {
//alert("pending called " + data3)
if(data3.indexOf("pending") >-1 ){
setTimeout(poll, 20000);
}
else if ( (navigator.userAgent.indexOf('MSIE') != -1) ) {
//alert("Submit success - MSIE: " + data3);
parent.window.location.replace(data3);
}
else{
//alert("process three called " + data3)
window.top.location.assign(data3);
}
},
error: function(xhr, error){
//alert("Error");
//alert("Error: " + error + ", XHR status: " + xhr.status);
},
});
}
setTimeout(poll, 20000);
PHP
$query = ("SELECT column FROM table WHERE id = '$lead_id'") or die(mysql_error());
$result = mysql_query($query);
$return = array();
while($row = mysql_fetch_assoc($result))
{
$return = 'pending';
if($row['column'] != '')
{
$return = $row['column'];
}
}
echo $return;
I believe using json might help you out here, not to mention it is safer, like so:
function poll() {
$.ajax({
url: 'processthree.php?lead_id='+lead_id,
type: "GET",
dataType: 'json',//specify data type
success: function(data3) {
if(data3.res.indexOf("pending") >-1 ){
//rest of the code.....
then in your php:
$return = array();
while($row = mysql_fetch_assoc($result))
{
$return['res'] = 'pending';
if($row['column'] != '')
{
$return['res'] = $row['column'];
}
}
echo json_encode($return);
Note: use PDO or MYSQLI instead of mysql as it is deprecated.
First off, I apologise since this is my first time working with JSON.
My website has a client script that requests person data from the server. The server first queries the database (using mysql and mysqli) and then returns the data (names, ages, etc.) to the client side.
Specifically, I want to pass an associative array from the PhP side to the client side.
After doing some research, I decided to do this with AJAX JSON calls.
The client side call is done like this:
var person_id = $('#my_text_box').val();
$.ajax({
url: 'php/upload/my_server_script.php',
method: 'POST',
data: {id: person_id},
dataType: 'json',
cache: false,
success: function(response_data)
{
alert(response_data['name']); //The server should return an associative array
console.log(response_data);
},
error: function(jqXHR, textStatus, errorThrown)
{
console.log(arguments);
console.log(jqXHR.responseText);
console.log('Error: ' + errorThrown + ' ' + textStatus + ' ' + jqXHR);
}
});
The server side calls a method that will query the database and give the details of the person with the requested ID.
$id = $_POST['id'];
function getPersonData($id)
{
$personData = array();
(1 - Connect and SELECT name FROM Persons WHERE id = {$id}
2 - Fill the $personData array with result row
3 - Name will be saved in $personData['name'])
return json_encode($personData);
The AJAX call fails with the error 500 - Internal Server Error. When I check the contents of the server response on the browser (On Chrome, Network tab), it says there is no response (This request has no response data available).
The thing is, this code works perfect locally. But when I upload it to my cloud web server, the only AJAX calls in my website that fail are the ones that use JSON as the format for the data being transferred. The other ones work fine.
A couple of things I've tried:
First, checking if the array on the PhP side is empty or built with errors. It's not, all the correct values are there;
Second, including application/json to the cloud web server mime.type file (It's Apache);
Then, including a header('Content-Type: application/json'); in my server-side script.
Also, adding "contentType: 'application/json' " to the client-side $.ajax.
None of these four worked. What could I be forgetting?
Note: The browser's log reads as follows:
Arguments[3]
0: Object
1: "error"
2: "Internal Server Error"
callee: function (jqXHR, textStatus, errorThrown)
length: 3
__proto__: Object
*(url of my script file)*
Error: Internal Server Error error [object Object] ^
Note #2: Full PhP code:
//Fetch persondata for a specific ID, and encode the data in an array in JSON format
function JSONSelectPersonDataFromID($ID)
{
$personData = array(); //Array or array with results
//If querysuccess, commit. Else, rollback
$querySuccess = True;
//This method opens connection with root user
$conn = OpenDBConn();
$conn->autocommit(False);
try
{
if($videoID > 0)
{
$sql = "SELECT name FROM Persons WHERE id={$id}";
//Debugging
//echo $sql . "<br>";
$persons = mysqli_query($conn, $sql);
if(mysqli_connect_errno($conn))
{
$querySuccess = False;
}
if(isset($persons ) && (count($persons ) > 0))
{
//Loop through every scene
$personData = $persons ->fetch_array(MYSQLI_ASSOC);
}
else
{
return null;
}
}
else
{
$querySuccess = False;
}
}
catch(Exception $e)
{
$querySuccess = False;
}
if(!$querySuccess)
{
//Rollback
$conn->rollback();
die("Transaction failed");
}
else
{
//Commit
$conn->commit();
}
//Close the connection
DBClose($conn);
return json_encode($personData );
}
"Internal server error" means the server crashed somewhere but for security reasons the client only get that 500 error. Check the server's error log file, there should be the real origin of the error (some real error, file and line number). You should start there.
Does the PHP script that uses AJAX have permissions to read the other PHP Script?
I'm trying to learn some javascript and i'm having trouble figuring out why my code is incorrect (i'm sure i'm doing something wrong lol), but anyways I am trying to create a login page so that when the form is submitted javascript will call a function that checks if the login is in a mysql database and then checks the validity of the password for the user if they exist. however I am getting an error (Illegally Formed XML Syntax) i cannot resolve. I'm really confused, mostly because netbeans is saying it is a xml syntax error and i'm not using xml. here is the code in question:
function validateLogin(login){
login.addEventListener("input", function() {
$value = login.value;
if (<?php
//connect to mysql
mysql_connect(host, user, pass) or die(mysql_error());
echo("<script type='text/javascript'>");
echo("alert('MYSQL Connected.');");
echo("</script>");
//select db
mysql_select_db() or die(mysql_error());
echo("<script type='text/javascript'>");
echo("alert('MYSQL Database Selected.');");
echo("</script>");
//query
$result = mysql_query("SELECT * FROM logins") or die(mysql_error());
//check results against given login
while($row = mysql_fetch_array($result)){
if($row[login] == $value){
echo("true");
exit(0);
}
}
echo("false");
exit(0);
?>) {
login.setCustomValidity("Invalid Login. Please Click 'Register' Below.")
} else {
login.setCustomValidity("")
}
});
}
the code is in an external js file and the error throws on the last line. Also from reading i understand best practices is to not mix js and php so how would i got about separating them but maintaining the functionality i need?
thanks!
You can't mix PHP and JavaScript in this way as all of your PHP has already executed on the server before any of your JavaScript executes on the client.
The error is because the client is receiving and failing to execute this as JavaScript:
function validateLogin(login){
login.addEventListener("input", function() {
$value = login.value;
if (<script type='text/javascript'>alert('MYSQL Connected.');</script>...
// etc.
To interact with PHP from the client, you'll have to make another HTTP request -- either by <a> click, <form> submit, or Ajax request (using jQuery.post for brevity; see Using XMLHttpRequest for further details):
function validateLogin(login){
login.addEventListener("input", function() {
$.post('/validateLogin.php', { login: login }, function (result) {
if (result === "true") {
login.setCustomValidity("Invalid Login. Please Click 'Register' Below.")
} else {
login.setCustomValidity("")
}
});
});
}
Adjust the URL, /validateLogin.php, as needed; but create a PHP file for this URL similar to:
<?php
$value = $_POST['login'];
mysql_connect(host, user, pass) or die(mysql_error());
mysql_select_db() or die(mysql_error());
$result = mysql_query("SELECT * FROM logins") or die(mysql_error());
while($row = mysql_fetch_array($result)){
if($row[login] == $value){
echo("true");
exit(0);
}
}
echo("false");
exit(0);
?>
What is wrong? You simply break your JavaScript by inserting <script> parts to your if condition. So you get if (<script type='text/javascript'>alert('MYSQL Connected.');</script>... and so on... Next thing: you're trying to match $value, which is JavaScript variable, with $row[login] in PHP loop - you don't have $value there! These are separated codes. It's all wrong.
Jonathan Lonowski explained it very good how you should do this.
I want to populate a jQWidgets listbox control on my webpage(when page finished loading and rendering) with values from an actual MySQL database table.
PARTIAL SOLUTION: Here
NEW PROBLEM:
I've updated the source code and if I hardcode the SQL string - the listbox gets populated. But I want to make a small JS function - popList(field, table) - which can be called when you want to generate a jQWidgets listbox with values from a MySQL database on a page.
Problem is - for some reason the $field and $table are empty when the PHP script is being executed, and I receive You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM' at line 1 error. What gives?
The page:
<div id="ListBox">
<script type="text/javascript">
popList("name", "categories");
</script>
</div>
popList(field, value):
function popList(field, table) {
$.ajax({
type: "GET",
url: 'getListOfValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: 'json',
success: function(response) {
var source = $.parseJSON(response);
$("#ListBox").jqxListBox({ source: source, checkboxes: true, width: '400px', height: '150px', theme: 'summer'});
},
error: function() {
alert('sources unavailable');
}
});
}
getListOfValues.php:
<?php
require "dbinfo.php";
// Opens a connection to a MySQL server
$connection=mysql_connect($host, $username, $password);
if (!$connection) {
die('Not connected : ' . mysql_error());
}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
$field = $_GET["field"];
$table = $_GET["table"];
$field = mysql_real_escape_string($field);
$table = mysql_real_escape_string($table);
$qryString = "SELECT " . $field . " FROM " . $table;
$qryResult = mysql_query($qryString) or die(mysql_error());
$source = array();
while ($row = mysql_fetch_array($qryResult)){
array_push($source, $row[$field]);
}
mysql_close($connection);
echo json_encode($source);
?>
Ok, you have a few things here. First off you need a callback function when you do the ajaxRequest. (I'll explain why in a bit.) So add the following line BEFORE your ajaxReqest.send(null);
ajaxRequest.onreadystatechange = processAjaxResponse;
Then you need to add the processAjaxResponse function which will be called.
function processAjaxResponse() {
if (ajaxRequest.readySTate == 4) {
var response = ajaxRequest.responseText;
//do something with the response
//if you want to decode the JSON returned from PHP use this line
var arr = eval(response);
}
}
Ok, now the problem on your PHP side is you are using the return method. Instead you want PHP to print or echo output. Think about it this way. Each ajax call you do is like an invisible browser. Your PHP script needs to print something to the screen for the invisible browser to grab and work with.
In this specific case you are trying to pass an array from PHP back to JS so json_encode is your friend. Change your return line to the following:
print json_encode($listOfReturnedValues);
Let me know if you have any questions or need any help beyond this point. As an aside, I would really recommend using something like jQuery to do the ajax call and parse the response. Not only will it make sure the ajax call is compliant in every browser, it can automatically parse the JSON response into an array/object/whatever for you. Here's what your popList function would look like in jQuery (NOTE: you wouldn't need the processAjaxResponse function above)
function popList(field,table) {
$.ajax({
type: "GET",
url: 'getListofValues.php',
data: 'field='+escape(field)+'&table='+escape(table),
dataType: "json",
success: function(response) {
//the response variable here would have your array automatically decoded
}
});
}
It's just a lot cleaner and easier to maintain. I had to go back to some old code to remember how I did it before ;)
Good luck!