why are single quotes not visible - javascript

I am making a array from values from databse in PHP then storing it into javascript array. When I alert the array the single quotes are not visible, although when PHP is seen it shows the quotes around values. What’s wrong in my code? It should be ['1','2','3','4'] but it shows [1,2,3,4].
<script>
var values = [
<?php
$conn = mysql_connect("localhost","root","") or die ("we couldn't connect!");
mysql_select_db("test_value");
$rs = mysql_query("SELECT * FROM test") or die(mysql_error());
while($row = mysql_fetch_array($rs))
{
echo "'".$row['var1']."',";
}
?>
];
window.alert(values);
</script>

<script>
var values=[
<?php
$conn =mysql_connect("localhost","root","") or die ("we couldn't connect!");
mysql_select_db("test_value");
$rs = mysql_query("SELECT * FROM test") or die(mysql_error());
while($row = mysql_fetch_array($rs)){
echo "\'".$row['var1']."\',";
}?>
];
window.alert(values);
</script>
Use this , this may help you

Related

Build and send PHP Array to JS via Ajax

I want to build an array in PHP from SQL query and send it back via ajax to my JS file.
$id = clear(filter_input(INPUT_POST, 'id'));
$sql = 'SELECT * FROM `counties` WHERE `id`="'.$id.'"';
$query = mysqli_query($con, $sql);
$array = array();
while($result = mysqli_fetch_array($query)) {
$id = $result['id'];
$name = $result['name'];
$array[] = array('id' => $id, 'name' => $name);
}
echo json_encode($array);
This is my code. In response I have always just one element. There's a lot of more. How could i do that correctly? I was browsing whole Internet and I didn't find anything useful... :(
$id = $_POST['id'];
$query = mysqli_query($con, "SELECT id,name FROM `counties` WHERE `id`='$id'");
$array = mysqli_fetch_all($query,MYSQLI_ASSOC);
echo json_encode($array);
this may simplified code

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

Passing an Array from PHP to Javascript

I'm trying to pass on a PHP array to then use the array in JavaScript.
The PHP code I'm using is as follows:
<?php
$link = mysqli_connect("localhost", "root", "password", "database");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT * FROM Employees";
if ($result = mysqli_query($link, $query)) {
/* fetch associative array */
while ($row = mysqli_fetch_assoc($result)) {
$data[] = $row;
}
print_r($row);
/* free result set */
mysqli_free_result($result);
}
/* close connection */
mysqli_close($link);
//convert the PHP array into JSON format, so it works with javascript
$json_array = json_encode($data);
?>
JavaScript:
<script>
var array = <?php echo $data; ?>;
console.log(array);
</script>
The data array in PHP doesn't seem to get passed on to the Javascript var array. When looking at the console on firebug the following error messages are displayed:
Notice - Array to string conversion.
I'd really appreciate any help as to why this error is occurring.
Maybe because you are echo'ing the array instead of the json encoded string.
Use this
<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>
I believe it should be:
<script> var array = <?php echo $json_array; ?>;
console.log(array); </script>
You're using json_encode in $data but you're not using that variable in your code. Could that be it?

How to echo PHP MySQL query into Javascript variable without outputting closing PHP tag "?>"?

<script>
$(function() {
var name = [
<?php
$Database = "database name";
$DatabaseUserName = "db_user";
$DatabasePass = "db_pass";
$connect = mysql_connect("~", $DatabaseUserName, $DatabasePass);
#mysql_select_db($Database) or ("Database not found");
$query = "SELECT ~ FROM ~";
$result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
while ($row = mysql_fetch_array($result)) {
echo "\"". $row['~']."\", ";
}
// $result = mysql_query($query) or die ( $result."<br/><br/>".mysql_error());
mysql_close($connect);
?>
];
$( "#~" ).autocomplete({
source: name
});
});
</script>
Basically, I'm getting correct output except the closing PHP tag "?>" is included in the output when I don't want it to be. Is there a better way to do this?
Use json_encode() to output JavaScript safe data. For example...
<script>
<?php
// connect, query, etc
$data = [];
while ($row = ...) {
$data[] = $row['~'];
}
?>
var name = <?= json_encode($data) ?>;
</script>
Here's a simplified demo ~ eval.in
And of course, here's the obligatory "don't use the deprecated mysql extension, etc" addendum.
Run this code and check if it is still coming. I could not reproduce the error.
<html>
<head>
<script>
var name = [
<?php
$row=array("Volvo", "BMW", "Toyota");
for($i=0;$i<count($row);$i++) {
echo "\"". $row[$i]."\", ";
}
?>
];
</script>
</head>
<body>
</body>
</html>

Why is this jQuery autocomplete not working?

I have the following in my page header
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="javascript/autoSuggest.js"></script>
<script type="text/javascript" src="javascript/suggest.js"></script>
suggest.js is made of:
$(function(){
$("#idName input").autoSuggest("../Test.php", {minChars: 2, matchCase: true});
});
and autoSuggest.js is a plugin by Drew Wilson (http://code.drewwilson.com/entry/autosuggest-jquery-plugin)
Test.php is
<?php
include('database_info.inc');
$input = $_POST["idName"];
$data = array();
var_dump($data);
// query database to see which entries match the input
$query = mysql_query("SELECT * FROM test WHERE title LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['title'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>
My var_dump() doesn't do anything and no items are suggested ...what could I be doing wrong? seems like there's no communication with Test.php
A quick look at the plug-in suggests it expects a parameter called q passed as a GET string, not as a POST.
<?
$input = $_GET["q"];
$data = array();
// query your DataBase here looking for a match to $input
$query = mysql_query("SELECT * FROM my_table WHERE my_field LIKE '%$input%'");
while ($row = mysql_fetch_assoc($query)) {
$json = array();
$json['value'] = $row['id'];
$json['name'] = $row['username'];
$json['image'] = $row['user_photo'];
$data[] = $json;
}
header("Content-type: application/json");
echo json_encode($data);
?>

Categories