I'm trying to create a JSON callback. I got two files, json.html and json.php. Also, I've a database with like this:
Type: MySQL
DB Name: user_table
Table name: customers
Fields: id, name, product, supplier
Codes of my json.html is:
<html>
<head>
</head>
<body>
<div id="demo" style="font-size: 20px;"></div>
<script>
obj = { "table":"customers", "limit":10 };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
myObj = JSON.parse(this.responseText);
for (x in myObj) {
txt += myObj[x] + "<br>";
}
document.getElementById("demo").innerHTML = txt;
}
};
xmlhttp.open("POST", "json.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("x=" + dbParam);
</script>
</body>
</html>
And here is the codes of json.php:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_POST["x"], false);
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
echo json_encode($outp);
?>
Here is the error log reports:
PHP Notice: Undefined variable: table in /home/user/public_html/json/json.php on line 7
PHP Fatal error: Cannot access empty property in /home/user/public_html/json/json.php on line 7
PHP Notice: Undefined index: x in /home/user/public_html/json/json.php on line 4
PHP Notice: Undefined variable: table in /home/user/public_html/json/json.php on line 7
PHP Notice: Trying to get property of non-object in /home/user/public_html/json/json.php on line 7
PHP Notice: Undefined variable: limit in /home/user/public_html/json/json.php on line 7
PHP Notice: Trying to get property of non-object in /home/user/public_html/json/json.php on line 7
PHP Fatal error: Call to a member function fetch_all() on a non-object in /home/user/public_html/json/json.php on line 9
How can I make it work?
As mentioned in a comment to David, the problem was with fetch_all(). I guess what was making the problem is the server resources because the page returned 500 on call.
In any case I retrieved the required array using this method instead:
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT * FROM customers LIMIT 10");
$outp = array();
while ($row = $result->fetch_array(MYSQLI_ASSOC)) {
$outp[] = $result->fetch_array(MYSQLI_ASSOC);
}
echo json_encode($outp);
And it worked.
Now, I'm going to make it work with my JSON callback.
Try replacing
$result = $conn->query("SELECT name FROM ".$obj->$table." LIMIT ".$obj->$limit);
with
$result = $conn->query("SELECT name FROM ".$obj->{'table'}." LIMIT ".$obj->{'limit'});
Try like this...
In your javascript send object..
xmlhttp.send(obj);
In PHP:
<?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";
header("Content-Type: application/json; charset=UTF-8");
extract($_POST); //Extracting
$conn = new mysqli($servername, $username, $password, $dbname);
$result = $conn->query("SELECT name FROM ".$table." LIMIT ".$limit);
$outp = array();
$outp = $result->fetch_all(MYSQLI_ASSOC);
print_r($outp);
echo json_encode($outp);
?>
Looks like the JSON you are trying to send is not making it to the PHP script.
Some things I would do are:
Change the request header content type to application/json (see this https://stackoverflow.com/a/9880122/2315558)
Check that x has a value before trying to use it
Related
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 1 year ago.
I was trying to reload a div in a PHP function but it does not work.
Everything work but not the div reload:
function refresh() {
$servername = "localhost";
$username = "root";
$password = "";
$db = "wp_4lous";
$conn = new mysqli($servername, $username, $password, $db);
$checklog = mysqli_fetch_row(mysqli_query($conn, 'SELECT numero_voti FROM voti WHERE candidato="LOG"'));
if ($checklog[0] == '10') {
mysqli_query($conn, 'UPDATE voti SET numero_voti="0" WHERE candidato="LOG" AND numero_voti="10"');
echo '<script> updateDiv(); </script>';
}
};
?>
<script type="text/javascript">
function updateDiv()
{
$("#here").load(window.location.href + " #here" );
}
</script>
You can try a different approach, the way you are doing will not work. Use a php variable and assign something usefull to understand that your SQL update is done, and use that variable inside the script to do the work.
Sample code below - I have used a variable $recUpdated, and modified your code, take a look.
$recUpdated = "NO";
function refresh() {
$servername = "localhost";
$username = "root";
$password = "";
$db = "wp_4lous";
$conn = new mysqli($servername, $username, $password, $db);
$checklog = mysqli_fetch_row(mysqli_query($conn, 'SELECT numero_voti FROM voti WHERE candidato="LOG"'));
if ($checklog[0] == '10') {
mysqli_query($conn, 'UPDATE voti SET numero_voti="0" WHERE candidato="LOG" AND numero_voti="10"');
$recUpdated = "YES";
}
};
?>
<script type="text/javascript">
<?php if($recUpdated == "YES") { ?>
$("#here").load(window.location.href + " #here" );
<?php } ?>
</script>
I have some code that supports pagination, but I can't make my buttons work. Can anyone help?
function setData() {
var flexContainer = document.getElementById("flex");
flexContainer.innerHTML = "<?php
foreach ($articlesarray as $seperated) {
$contentsContent = file_get_contents("../" . "$seperated[contentsname]");
echo "<div class='card'><img src='$seperated[img]'' alt='uh oh photo not found' style='width:100%''><div class='container'><h4><b>$seperated[title]</b></h4><p>$contentsContent</p></div></div>";
}
?>";
document.getElementById("back").disabled = "<?php
if ($_SERVER['REQUEST_URI'] == "/list/index.php?page=1") {
echo "true";
} else {
echo "false";
}
?>";
document.getElementById("back").style = "<?php
if ($_SERVER['REQUEST_URI'] == "/list/index.php?page=1") {
echo "display: none;";
} else {
echo "display: inline-block;";
}
?>";
}
and the php is:
$servername = "localhost";
$username = "root";
$password = "You can't have my server password";
$dbname = "myDB";
$badurl = "/list/index.php";
$newURL = "/list/index.php?page=1";
if ($_SERVER['REQUEST_URI']==$badurl) {
print "uh oh spaghettios";
header('Location: ' . $newURL);
die();
}
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$offsetAmount = $_GET["page"] * 9 - 9;
$sql = "SELECT id, title, contentsname, img FROM articles LIMIT 9 OFFSET $offsetAmount";
$result = $conn->query($sql);
$articlesarray = array();
while($row = mysqli_fetch_assoc($result)){
$articlesarray[] = $row;
}
//echo "<br><br><br> If you are reading this, you have found the debug screen. This website is under maintanence.";
mysqli_close($conn);
I can't work out how to add pagination using this system. Can anyone help? I have tried shifting the url but that only returned a 0 for some reason.
It's a GET request so in PHP I can just use
$_GET["page"] and then add or subtract 1 accordingly.
I am using this code right here:
HTML code (jsonexamplecss.html):
<!DOCTYPE html>
<html>
<body>
<div id="id01"></div>
<script>
var xmlhttp = new XMLHttpRequest();
var url = "adomaniname/phpselectdatawhere.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
myFunction(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(response) {
var s = 256;
var hr = new XMLHttpRequest();
hr.open("POST", "adomainname/phpselectdatawhere.php", true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.send("limit="+s);
var arr = JSON.parse(response);
var i;
var i = 0;
for(i = 0; i < arr.length; i++) {
out = arr[i].name
if (out = "0 results") {
alert("0 results");
}
}
document.getElementById("id01").innerHTML = out;
alert(out);
}
</script>
</body>
</html>
PHP code(phpselectdatawhere.php):
<?php
if(isset($_POST['limit'])){
$limit = preg_replace('#[^0-9]#', '', $_POST['limit']);
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT id, name FROM testget WHERE id='$limit'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo $row["name"];
}
} else {
echo "0 results";
}
$conn->close();
?>
I have a table named testget with id, name fields both VARCHAR. I wrote a script in order to do these things:
The HTML script sends data to the php script via http request and in this example it sends limit=256.
The PHP script gets the limit=256, puts away the number from the limit and stores $limit =256.
After that the PHP script searches if there is a name in the table whose id='$limit' and prints the name if it exists, else it echoes 0 results. The table testget has a row where id=256 and name=JohnDoe so it can't echo 0 results.
After all this procedure the HTML scripts gets the echoed stuff and alerts them with JavaScript.
So in this case I want to have JohnDoe alerted in my HTML page but unfortunately nothing shows up. Could you please help me?
Note that the url and the database connection info are correct but as you can understand I don't want to show them.
So following my last question I want to use the value that is submitted in the input tag to get the matching id in my database. I have created two files for it but I can't figure out how to link them. Also note I made a database with a few values(id, firstname, etc.) and when the user fills in 1 I want it to display id 1 & the firstname.
This code is from the last question & I've added xmlhttp:
Input code
Choose a number between 1 and 5
Your info shall be shown here
Click me!
var myButton = document.getElementById('btn');
myButton.onclick = function(){
alert(document.getElementById('myid').value);
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if( xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
var dbText = xmlhttp.responseText;
document.getElementById('dbinfo').innerHTML = dbText;
}
}
xmlhttp.open("POST", "LinkToDataFile", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
}
That is what the user sees and the number is displayed correctly however I now need to link it to my file data.php which I have tried but it cannot get the value.
Data Code
<?php
require_once('input_code');
//Get the data from the database and echo them here
$servername = "localhost";
$username = "root";
$password = "";
$databasename = "db_name";
try
{
$connection = new PDO("mysql:host=".$servername.";dbname=".$databasename, $username, $password);
$connection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$statement = $connection->prepare("SELECT `id`, `firstname`, FROM `db_name` WHERE `id` = :myid"); //Here it needs to grab the value but it does not work.
$statement->bindParam(':id', $id);
$id = $_POST['id'];
$statement->execute();
$result = $statement->setFetchMode(PDO::FETCH_ASSOC);
$data = "";
foreach($statement->fetchAll() as $key => $value)
{
$data .= $value['id']." | ".$value['firstname'];
}
}
catch(PDOException $e)
{
echo "The following error occurred : ".$e->getMessage();
}
echo $data;
?>
So what am I doing wrong? am I missing something obvious like the $id again or is it a series of errors, the only thing it does now is giving me an alert with the number.
By adding a line and moving $id before $statement it is all fix thanks to Dante Javier
Input code
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //Under this add the following lines:
var id = document.getElementById('myid').value;
xmlhttp.send("id="+id);
Data Code
$id = $_POST['id']; //Move this above the $statement = $connection->prepare.
I have created this page to get data from the database, with links to print the shown data and delete it afterwards.
One of the problems is that the JavaScript print function window.print(); wont work.
Another problem is that after printing the page, I would like to update the database, so people can see that it has been printed before.
Alternatively, the function could also print the page and then immediately deletes data, so people won't need to see if it has been printed before or not.
This is the code for getting the data from the database:
<html>
<header>
<script>
function print_table(id)
{
//print your document
window.print();
//send your data
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET","http://localhost/Stage/printed_table.php" + id;
xmlhttp.send();
}
</script>
</header>
<body>
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query("SELECT * FROM orders");
// Count the returned rows
if($resultSet->num_rows != 0){
// Turn the results into an Array
while($rows = $resultSet->fetch_assoc())
{
$id = $rows['id'];
$naam = $rows['naam'];
$achternaam = $rows['achternaam'];
$email = $rows['email'];
$telefoon = $rows['telefoon'];
$bestelling = $rows['bestelling'];
echo "<p>Name: $naam $achternaam<br />Email: $email<br />Telefoon: $telefoon<br /> Bestelling: $bestelling<br /> <a href='delete.php?del=$id'>Delete</a> <input type='button' onclick='print_table($id)' value='Print Table' /> </p>";
}
// Display the results
}else{
echo "Geen bestellingen";
}
?>
</body>
</html>
and these are the pages for the two server-side functions:
delete.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Get ID
$id = $_GET['del'];
$sql= "DELETE FROM orders WHERE id=" . $id . "";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$resultSet = $conn->query($sql) or die("Failed".mysql_error());
echo "<meta http-equiv='refresh' content='0;url=http://localhost/Stage%201/bestellingen.php'>";
?>
print_table.php
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "depits";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Query the database
$id = $_GET['id'];
$resultSet = $conn->query("UPDATE `orders` SET `printed` = 1 WHERE `id` = `$id`");
?>
You should really check your browser console (F12) to see if there are any JavaScript errors.
One really glaring error I could spot is this line, where the brackets aren't closed. These type of errors could be easily fixed just by checking the console first.
Another error is the variable in the string, it should be sent as a ?key=value pair.
xmlhttp.open("GET","http://localhost/Stage/printed_table.php" + id;
should be:
xmlhttp.open("GET","http://localhost/Stage/printed_table.php?id=" + id, true);
Another problem would be the URL the above line is calling. I notice you mentioned that your PHP file name is called print_table.php instead of printed_table.php.