Send array from php to js with ajax and json - javascript

I am trying to send an array from php (that I have taken from a mysql table to js). Although there a lot of examples out there I can't seem to make any of them work. The code that I have reached so far is:
php_side.php
<!DOCTYPE html>
<html>
<body>
<?php
//$q = intval($_GET['q']);
header("Content-type: text/javascript");
$con = mysqli_connect("localhost","root","","Tileiatriki");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
//mysqli_select_db($con,"users_in_calls");
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);
/*while($row = mysqli_fetch_array($result)) {
echo $row['User1_number'];
echo "<br/>";
echo $row['User2_number'];
echo "<br/>";
echo $row['canvas_channel'];
echo "<br/>";
}*/
echo json_encode($result);
mysqli_close($con);
?>
</body>
</html>
test_ajax.html
$(document).ready(function(){
$.getJSON('php_side.php', function(data) {
$(data).each(function(key, value) {
// Will alert 1, 2 and 3
alert(value);
});
});
});
This is my first app that I use something like this, so please be a little patient.

Right now you're sending the complete page markup mixed with your json response, which of course will not work.
For example imagine that you have the following php script which suppose to return a json response:
<div><?php print json_encode(array('domain' => 'example.com')); ?></div>
The response from this page would not be json since it also will return the wrapping div element.
You can move your php code to the top of the page or simply remove all the html:
<?php
// uncomment the following two lines to get see any errors
// ini_set('display_errors', 1);
// error_reporting(E_ALL);
// header can not be called after any output has been done
// notice that you also should use 'application/json' in this case
header("Content-type: application/json");
$con = mysqli_connect("localhost","root","","Tileiatriki");
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
$sql="SELECT * FROM users_in_calls";
$result = mysqli_query($con,$sql);
// fetch all rows from the result set
$data = array();
while($row = mysqli_fetch_array($result)) {
$data[] = $row;
}
mysqli_close($con);
echo json_encode($data);
// terminate the script
exit;
?>

Related

Trying to get results of a MySQL query into a JavaScript array

I've got a MySQL database of offices with geo data. I'm trying to get a list of the office cities into a JavaScript array. For now, I just wanted to set up a simple $.ajax() to log the list into the console, but it's returning null. I'm just running my JavaScript function "query()" in console after the page loads.
Here's my JavaScript.
function query() {
$.ajax({
url: "query.php",
method: "POST",
dataType: 'json',
success: function(data) {
let output = JSON.parse(data)
console.log(output)
}
})
}
Here's query.php
<?php
include 'database.php';
$sql="SELECT `Office City` FROM `offices`";
$result = $link->query($sql);
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>
Here's database.php. I'm able to write to MySQL using this PHP, so I assume it's correct.
<?php
$hostname = "hostus.mostus.com";
$username = "name";
$password = "pw";
$database = "db";
$link = mysqli_connect($hostname, $username, $password,$database);
if (mysqli_connect_errno()) {
die("Connect failed: %s\n" + mysqli_connect_error());
exit();
}
When I run query() in the console, it responds "undefined" then null.
Your sql is invalid.
I would also init the $result_array before. Currently if the result is empty, you are returning null.
<?php
include 'database.php';
$sql="SELECT `Office`, `City` FROM `offices`";
$result = $link->query($sql);
$result_array = [];
if ($result) {
while($row = $result->fetch_assoc()) {
array_push($result_array, $row);
}
}
header('Content-type: application/json');
echo json_encode($result_array);
$link->close();
?>

Retrieve data from database and save it in a variable to do some calculation and diplay it

I want to retrieve the last inserted id(id is in auto increment) from the database table named table facility and want to do some calculation(for example I am adding five now) and display the result on the screen. kindly help me I am not able to get this.
<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])==0)
{
header('location:index.php');
}
else{
$sql="SELECT MAX(facilityid) FROM tblfacility ";
$result=$dbh -> query($sql);
$row=$result->fetch(PDO::FETCH_ASSOC);
echo "<pre>", print_r($row),"</pre>";
echo $result ;
$code = $row->facilityid;
$sampleid= $code +5;
echo $sampleid;
}
?>
Because you did not alias max function to facilityid, so could not call $row->facilityid you should
SELECT MAX(facilityid) As facilityid FROM tblfacility
Also, let use PDO::FETCH_OBJ to get $row as object.
<?php
session_start();
error_reporting(0);
include('includes/config.php');
if(strlen($_SESSION['alogin'])==0)
{
header('location:index.php');
}
else{
$sql="SELECT MAX(facilityid) As facilityid FROM tblfacility ";
$result=$dbh -> query($sql);
$row=$result->fetch(PDO::FETCH_ASSOC);
$code=$row[facilityid];
$sampleid= $code +1;
echo $sampleid;
}
?>

Clicking button does nothing

I'm trying to make a program that takes 5 words from a database randomly and inserts them into an array. The page initially loads as desired, but nothing happens after the button is clicked. None of the alerts are ever triggered, so the function must never be entered, but why is beyond me. Also, I get an error saying name isn't a legitimate index (referencing line 13) the first time I try running it on a browser, so advice about that would be great too.
lingo.php:
<?php
session_start();
if (empty($_POST["name"])):
$_SESSION["error"] = "You did not enter a name.";
header("Location: entername.php");
else:
$name = $_POST["name"];
setcookie("name", "$name", time()+3600);
endif;
?>
<html>
<head>
<b>Welcome to Lingo, <?php echo $_COOKIE["name"]; ?></b><br />
<script src = "http://code.jquery.com/jquery-latest.js"></script>
<script type = "text/javascript" language = "javascript">
var arr = [];
function collectWords() {
$.post("getWord.php",
function(data) {
arr[word1] = $(data).find("Word1").text();
alert("function reached");
alert(arr[word1]);
arr[word2] = $(data).find("Word2").text();
alert(arr[word2]);
arr[word3] = $(data).find("Word3").text();
alert(arr[word3]);
arr[word4] = $(data).find("Word4").text();
alert(arr[word4]);
arr[word5] = $(data).find("Word5").text();
alert(arr[word5]);
});
}
</script>
</head>
<body>
<table id = "theTable" border = "1" class = "thetable"> </table>
<input type = "submit" value = "Start" onclick = "collectWords()">
</body>
</html>
getWord.php
<?php
$db = new mysqli('localhost', 'spj916', "cs4501", 'spj916');
if ($db->connect_error):
die ("Could not connect to db " . $db->connect_error);
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word1>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word1>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word2>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word2>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word3>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word3>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word4>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word4>";
else:
die ("DB Error");
endif;
$query = "select word from Words order by rand() limit 1";
$result = $db->query($query);
$rows = $result->num_rows;
if ($rows >= 1):
header('Content-type: text/xml');
echo "<?xml version='1.0' encoding='utf-8'?>";
echo "<Word5>";
$row = $result->fetch_array();
$ans = $row["word"];
echo "<value>$ans</value>";
echo "</Word5>";
else:
die ("DB Error");
endif;
?>
You get the error on $_COOKIE["name"]; because said cookie isn't set until you set it. You don't set the cookie until someone has entered their names, so on the first load it will give an error.
http://www.thesitewizard.com/php/set-cookies.shtml
"Note that you cannot set a cookie in PHP and hope to retrieve the cookie immediately in that same script session. Take the following non-working PHP code as an example:"
Found under the header: "How to get the contents of a cookie.
Fix this with a shorthand if statement, like so:
<b>Welcome to Lingo,
<?php isset($_COOKIE["name"]) ? $_COOKIE["name"] : $_POST["name"]; //Checks if the cookie is set. If not, uses the $_POST name ?>! </b><br />
I have another question:
Why are your words requested 1 at a time? Why not get all 5 words in 1 query? Also, why send them back as XML data? Since you seem to be handling the data yourself, I would personally recommend a simple loop on the PHP side, returning it as a handy pre-made JSON array.
edit: Also important, PHP does not echo any content automatically. An AJAX call can only receive printed data. You need to echo your results at the end of your php script or you will return nothing
Like so:
$query = "select word from Words order by rand() limit 5";
$result = $db->query($query);
$rows = $result->num_rows;
$array = array();
if ($rows >= 1):
$i = 0;//start the wordcount
//While there are results, loop. (Results are limited to 5, so it won't loop more than 5 times)
while($row = $result->fetch_row()){
$i++;//Put this on top so it starts with "1"
$array["word$i"] = $row[0]; //create the array
}
echo json_encode($array); //Turn array into json and echo it.
else:
die ("DB Error");
endif;
Now, you will also need to change your Javascriptside a tiny bit.
This is how you will access the new array (created by php)
<script type = "text/javascript" language = "javascript">
function collectWords() {
$.post("getWord.php",
function(data) {
alert(data); // show whether you get any data back in the first place. thanks #jDo
var arr = $.parseJSON(data);
alert(arr.word1);
alert(arr.word2);
alert(arr.word3);
alert(arr.word4);
alert(arr.word5);
});
}
</script>
As you can see, this way saves you quite a lot of code and saves you a lot of word replacements

Using json_encode without displaying it on my webpage via echo or print

basically I'm trying to pass an array from PHP to JavaScript, so far it is all working the methods I'm using are:
PHP:
echo json_encode($arrayname);
JavaScript:
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
Obviously this echo's the text onto my webpage but I do not want this text to be displayed, I'm just wondering if there is anyway for me to use this without having a chunky array at the top of my webpage. (I tried it without the echo and it doesn't work, I've also gone through countless tutorials on this but no one seems to do it without using echo)
Thanks a lot in advance
---------- Edit -------------
index.js
$.getJSON( 'myphppage.php', {}, function(data){
// I loop through the data here
}
}).done(function() {});
myphppage.php
<?php
$servername = "name";
$username = "username";
$password = "";
$dbname = "dbname";
$connection = mysql_connect($servername,$username);
if(!$connection) {
die("Database connection failed: " . mysql_error());
}else{
$db_select = mysql_select_db($dbname,$connection);
if (!$db_select) {
die("Database selection failed:: " . mysql_error());
}
$result = mysql_query("select * FROM tablename");
if (!$result) {
echo 'Could not run query: ' . mysql_error();
exit;
}
$array= array();
while($row = mysql_fetch_array($result)) {
array_push($array, $row);
}
echo json_encode($array);
}
Minimal example:
index.html
$.getJSON( 'myphppage.php', {}, function(data){
// Do stuff here
});
myphpwebpage.php
echo json_encode($arrayname);

Should this file be loaded as a valid .js file?

I am trying to create a PHP file that the browser will see as a js file, and are using the content-type header. But there's something not working, even though. So my question is, should this be interpreted as a valid .js file?:
<?php
header('Content-Type: application/javascript');
$mysql_host = "localhost";
$mysql_database = "lalalala";
$mysql_user = "lalalalal";
$mysql_password = "lalalallaala";
if (!mysql_connect($mysql_host, $mysql_user, $mysql_password))
die("Can't connect to database");
if (!mysql_select_db($mysql_database))
die("Can't select database");
mysql_query("SET NAMES 'utf8'");
?>
jQuery(document).ready(function() {
var urlsFinal = [
<?php
$result = mysql_query("SELECT * FROM offer_data ORDER BY id_campo DESC");
while($nt = mysql_fetch_array($result)) {
?>
"<?php echo $nt['url']; ?>",
<?php
};
?>
"oiasdoiajsdoiasdoiasjdioajsiodjaosdjiaoi.com"
];
scriptLoaded();
});
In order for your Browser to see your PHP file like a .js file, echo or print the entire PHP page into a string, there will be no need to use any headers, just something like:
// First let's make a secure page called database.php - put in a restricted folder
<?php
function db(){
return new mysqli('host', 'username', 'password', 'database');
}
?>
// now let's go over a new technique you'll cherish in the future - page.php
<?php
include 'restricted/database.php'; $db = db();
if($db->connect_errort)die("Can't connect to database. Error:".$db->connect_errno);
$db->query("UPDATE tabelName SET names='utf8' WHERE column='value'");
$sel = $db->query('SELECT * FROM offer_data ORDER BY id_campo DESC');
if($sel->num_rows > 0){
while($nt = $db->fetch_object()){
$output[] = $nt->url;
}
}
else{
die('No records were returned.')
}
$sel->free(); $out = implode("', '", $output); $db->close();
echo "jQuery(document).ready(function(){
var urlsFinal = ['$out'];
// more jQuery here - you may want to escape some jQuery \$ symbols
}"
?>
Now just make sure your script tag looks like:
<script type='text/javascript' src='page.php'></script>

Categories