I having written a php script which makes an SQL query and fetches a list of unique names from the database.
I am making an AJAX GET request using jQuery to the php script. When I check resources in the console I see that the php script is being called, and when I check the response it contains a list of unique names.
However, the jquery GET request is failing, and is displaying an error message in the console.
It may be easier and clearer to look at my code, as I have no idea what is the issue here. Please see code below.
php
<?php
header('Content-Type: application/json');
$servername = "****";
$username = "****";
$password = "****";
$dbname = "****";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT DISTINCT(name) FROM customer";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo json_encode(array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
$conn->close();
?>
JS
$.ajax({
type: 'GET',
url: 'getcustomers.php',
success: function(data){
console.log(data);
},
error: function() {
console.log('error');
}
});
In the console it simply says error, meaning it has executed the error function.
When I load the php file in the browser it displays the following.
{"name":"Peter"}{"name":"Alan"}{"name":"Mike"}
Your JSON response is not a valid one. You are printing each data row on each iteration. So replace the while statement with this one,
if ($result->num_rows > 0) {
$return = array();
while($row = $result->fetch_assoc()) {
$return[] = array('customer' => $row["name"]);
}
echo json_encode($return);
} else {
echo "0 results";
}
Considering your script returns any result (I hope you've tried running it in broswer) then you can use something like this:
$.get('path/to/file/filename.php').done(function(response) {
$('#exampleDiv').html(response);
});
Although, common errors because you must specify the directory path if the php file you're requesting is outside the current working directory.
change your error handler function header to the following:
error: function (jqXHR, textStatus, errorThrown) {
then print that and see what the error is
you are echoing json_encode string in side while loop, instead of that you will have to push row in an array and at the end you can echo json string only once.
$outputArr = array();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
array_push(outputArr ,array('customer' => $row["name"]));
}
} else {
echo "0 results";
}
echo json_encode($outputArr);
Related
I have a simple AJAX function bound to a button that should execute a PostgreSQL query. However, when I click the button that I bound the ajax query to, all I get is the confirmation that the database connection was successful. Nothing seems to happen withe the ajax result (should be printing to console in the handleAjax() function. What am I doing wrong?
This is the javascript code (with jquery):
$(document).ready(function() {
function sendAjax() {
$.ajax({
url: "db/database.php",
success: function (result) {
handleAjax(result);
}
});
}
function handleAjax(result) {
console.log(result);
}
$("#submit-button").on("click", sendAjax);
});
And this it the contents of database.php:
<?php
function dbconn(){
ini_set('display_errors', 1); // Displays errors
//database login info
$host = 'localhost';
$port = 5432;
$dbname = 'sms';
$user = 'postgres';
$password = 'postgres';
// establish connection
$conn = pg_connect("host=$host port=$port dbname=$dbname user=$user password=$password");
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
}
}
$conn = dbconn();
$sql = "SELECT * FROM numbers;";
$result = pg_query( $sql ) or die('Query Failed: ' .pg_last_error());
$count = 0;
$text = 'error';
while( $row = pg_fetch_array( $result, null, PGSQL_ASSOC ) ) {
$text = $row['message'];
//echo $text;
}
pg_free_result( $result );
?>
The problem is in the database.php file, all you get is "Connected." because you don't print your result at the end. Ajax only receive the output of the php file.
So at the end of your php file you should add :
echo $text;
And you also should remove the echo "Connected.";
AJAX is not a magic wand that in magic way reads PHP code. Let's say AJAX is a user. So what does user do.
Open web page
Wait until PHP execute code and display data
Tells you what he sees
If you don't display anything, ajax can't tell you what he saw.
In thi's place is worth to say that the best way to communicate between PHP and AJAX is using JSON format.
Your code generally is good. All you have to do is to display your data. All your data is in your $text var. So let's convert your array ($text) to JSON.
header('Content-Type: application/json');
echo json_encode($text);
First you set content-type to json, so ajax knows that he reads json. Then you encode (convert) your PHP array to js-friendly format (JSON). Also delete unnecessary echoes like 'Conntected' because as I said, AJAX reads everything what he sees.
You should return $conn from dbconn()
if (!$conn) {
echo "Not connected : " . pg_error();
exit;
} else {
echo "Connected.";
return $conn;
}
I've been at this for hours trying to figure out why this will not work. I am trying to read data from my mysql database using php and jquery. In my php file it loops through a table and should echo the results of that table. I am using the jquery .get method to try and retrieve it but i get a 404 error file not found. The 404 error goes away and everything works fine if i change my php file to something simple like:
<?php echo 'Hello'; ?>
I believe the problem is in my php file because when i create a new file with just echoing a string and nothing else it returns everything fine.
$(document).ready(function() {
$.get("php/listtasks.php", function(data){
alert("Data: " + data);
})
});
My php file where i think there is a problem contains:
<?php // sqltest.php
require_once 'session.php';
require_once 'login.php';
$conn = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($conn->connect_error) die($conn->connect_error);
$query = "SELECT * FROM list";
$result = $conn->query($query);
if (!$result) die ("Database access failed: " . $conn->error);
$rows = $result->num_rows;
for ($j = 0 ; $j < $rows ; ++$j)
{
$result->data_seek($j);
$row = $result->fetch_array(MYSQLI_NUM);
echo $row[2];
}
$result->close();
$conn->close();
?>
I've been at this for quite a while now, and I have pretty much no experience with PHP and I've only begun with JavaScript.
I'm attempting to run a PHP script that I have on my server from the JavaScript on the webpage using AJAX. To be honest, I don't really have much of an idea of what I'm doing.
My current code:
JS:
function Write() {
$.ajax({
type: "POST",
url: "Write.php",
data: {
'GUID': "12345678987654321",
'IP': "127.0.0.2",
'USERNAME': "George",
'BAN_REASON': "Broke my pencil."
},
success: function(data) {
console.log(data);
}
});
}
PHP:
<?php
exec("java -jar Database.jar '.$_POST['GUID']' '.$_POST['IP']' '.$_POST['USERNAME']' '.$_POST['BAN_REASON']'");
?>
(I'm also not too entirely sure that I did that String correctly, so help on that would be appreciated)
Basically, that PHP code is using a Java program I made to write to a MySQL database using the arguments that are being sent by the PHP "exec()." It's not writing to the database at all, so I'm assuming it's something with the AJAX going to the PHP function.
When "Write()" is ran, all it does is print out the PHP code to the console...
NEW CODE
<?php
//Server
$servername = "localhost";
$dbusername = $_POST['DB_USERNAME'];
$password = $_POST['DB_PASSWORD'];
$dbname = "bansdb";
$username = $_POST['USERNAME'];
$guid = $_POST['GUID'];
$ip = $_POST['IP'];
$ban_reason = $_POST['BAN_REASON'];
$connection = new mysqli($servername, $dbusername, $password, $dbname);
if ($connection->connect_error) {
die("Connection Failed: " . $connection->connect_error);
}
$sql = "INSERT INTO bans (GUID, IP, USERNAME, BAN_REASON)
VALUES ('$guid', '$ip', '$username', '$ban_reason')";
if (mysqli_query($connection, $sql)) {
echo "Ban successfully added.";
} else {
echo "Error: " . $sql . mysqli_error($connection);
}
mysqli_close($connection);
?>
I would not pass your DB user/password over the network. Just make a simple application password and store the password statically in the PHP with the db user/password (in HTML modify form to have APP_PASSWORD input). With parameterized queries aside from closing SQL injection you also can have single quotes in your value and don't have to worry about the query breaking (the driver handles the quoting).
<?php
//Server
$servername = "localhost";
$dbusername = 'static_db_user';//$_POST['DB_USERNAME'];
$password = 'staticpassword';//$_POST['DB_PASSWORD'];
$dbname = "bansdb";
if($_POST['APP_PASSWORD'] != 'Some generic password') {
die('Invalid Credentials');
}
$username = $_POST['USERNAME'];
$guid = $_POST['GUID'];
$ip = $_POST['IP']; // I would store IP as an unsigned int, ip2long
$ban_reason = $_POST['BAN_REASON'];
$connection = new mysqli($servername, $dbusername, $password, $dbname);
if ($connection->connect_error) {
die("Connection Failed: " . $connection->connect_error);
}
$sql = "INSERT INTO bans (GUID, IP, USERNAME, BAN_REASON)
VALUES (?,?,?,?)";
if ($stmt = mysqli_prepare($connection, $sql)) {
mysqli_stmt_bind_param($stmt, , 'ssss', $guid, $ip, $username, $ban_reason;
if(mysqli_stmt_execute($stmt)) {
echo "Ban successfully added.";
} else {
echo "Execute Error: " . $sql . mysqli_error($connection);
}
} else {
echo "Prepare Error: " . $sql . mysqli_error($connection);
}
mysqli_close($connection);
?>
all it does is print out the PHP code to the console...
Do you have a web server that's configured to execute PHP code? You must realize that you cannot just run a plain php file in your browser opened from the filesystem on your "server".
Make a new file called info.php and save it to your web server. Inside it should only be this:
<?php
phpinfo();
If you see that code when you browse to it, then you do not have PHP enabled. Otherwise, you will see a lot of information about your configuration.
not too entirely sure that I did that String correctly
pretty close, but you should read up about some quotes
this might work for you:
<?php
exec("java -jar Database.jar $_POST[GUID] $_POST[IP] $_POST[USERNAME] $_POST[BAN_REASON]");
I'm trying to insert a JSON array of objects passed via a jquery $.ajax POST into a MySQL database via PHP. I've seemingly tried everything but for some reason I can't get it to work. Any suggestions would be much appreciated.
PHP
<?php
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$data = json_decode($_POST, true);
foreach ($data as $item) {
$worker_id = $item['worker_id'];
$response_time = $item['time'];
$video_id = $item['video_id'];
$submission = $item['response'];
$test_answer = $item['test_answer'];
$sql = "INSERT INTO nristudy (worker_id, response_time, video_id, submission, test_answer)
VALUES ('$worker_id', '$response_time', '$video_id', '$submission', '$test_answer')";
if (!($conn->query($sql))) {
die($conn->error);
}
}
if (!$conn->commit()) {
echo "Transaction commit failed";
exit();
}
$conn->close();
?>
Javascript
var json = JSON.stringify(submissions);
$.ajax({
type: "POST",
url: "http://hci.cs.wisc.edu/nri/store_data.php",
data: json,
success: function(data){
console.log("Success: " + data);
},
error: function(jqXHR, textStatus, errorThrown) {
alert('An error occurred... look at the console for more information!');
console.log('jqXHR:');
console.log(jqXHR);
console.log('textStatus:');
console.log(textStatus);
console.log('errorThrown:');
console.log(errorThrown);
}
});
The solution to your problem depends heavily on what the error is. However, one thing that is pretty clear is that you should be escaping the strings you are trying to put into the query.
I recommend that you switch to using PDO and prepared statements as you will not have to worry about escaping anything and can rely on PDO to take care of it when you prepare the statement.
You might also want to try serialize instead of json_encode but if it works there is a chance that SQL injection is still a real big possibility for you.
I'm having trouble getting data from my database. My goal is to get all groups from my database and return them in JSON (in an alert box or whatever).
Now it won't convert to JSON and I am getting weird response text from the ajax call. If you need anything else to solve this problem, please do not hesitate to ask.
Here is what I did.
PHP
$servername = "redacted";
$username = "redacted";
$password = "redacted";
$dbname = "redacted";
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case 'getGroups' : getAllGroups();break;
}
}
function getAllGroups() {
$mysqli = new mysqli($servername, $username, $password, $dbname);
$query = $mysqli->query("SELECT * FROM groups");
while($row = $query->fetch_object()) {
$result[] = $row;
}
echo "{\"results\":";
echo json_encode($result);
echo "}";
$mysqli->close();
}
JS
function getPosts() {
$.ajax({
url: 'functions.php',
data: {action: 'getGroups'},
type: 'post',
success: function(output) {
var result = JSON.parse(output);
result = result.resultaten;
alert(result);
}
});
}
getPosts();
Thanks in advance,
Mistergrave.
No need for that extra echos. Try with -
echo json_encode(array('results' => $result));
Instead of -
echo "{\"results\":";
echo json_encode($result);
echo "}";
No need for - if(isset($_POST['action']) && !empty($_POST['action'])) {
if(!empty($_POST['action'])) { - do the all.
Define $result first.
$result = array();
while($row = $query->fetch_object()) {
$result[] = $row;
}
Okay guys, I managed to solve everything. Apparently the php function couldn't find my credentials to log in to the database server because I defined them on top of the php file (and since javascript only executed the function, these credentials were undefined).
Solution:
I just copy-pasted the credentials at the start of each function so these were defined. And tadaah! It worked :).
Now I realize why the responseText was full of tables, because it started to return error tables about the connection.
I hope my explanation will help other people who have this issue as well.
Cheers, and thanks for all the helpfull answers,
Mistergrave.
use
echo json_encode(array('result'=>$result));
As it takes array as parameter. Check here
Just a note :
If are sure you will return json data, use dataType:json , so you wont need JSON.parse(output).