I want make data exist checker.
data.check.php:
<?php
$nick = mysql_real_escape_string($_POST['nick']);
$query = mysql_query("select * from tb_user WHERE nick='$nick'");
$nick_exist = mysql_num_rows($query);
?>
<script language="javascript" type="text/javascript">
var nick_exist = "<?php echo $nick_exist; ?>";
</script>
and this for $POST data
input.data.js
var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function() {
if(nick_exist){
window.alert('Choose another nick please!');
}
});
I dont know where is the problem and my windows.alert is not running :(
thanks u
try like this get the count in php then return it to js:
NOTE: Please do not use mysql it is deprecated now start using mysqli or pdo.
data.check.php:
<?php
$nick = mysql_real_escape_string($_POST['nick']);
$query = mysql_query("select * from tb_user WHERE nick='$nick'");
$nick_exist = mysql_num_rows($query);
echo json_encode(array('count'=> $nick_exist));//send result to javascript
?>
input.data.js
var v_nick = $('input:text[name=nick]').val();
$.post('data.check.php', {nick: v_nick} ,function(resp) {
var resp=JSON.parse(resp);
if(resp.count){
window.alert('Choose another nick please!');
}
});
Related
I'm having a hard time getting the value of a specific variable in php to use in js. This is my code in php:
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
}
?>
I want to get the value of this ($result['status']) and pass it on the variable pos in js. This is my js code:
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
var pos = $('PHP VARIABLE HERE').val();
alert(pos);
}
Thanks for your help.
The easiest way is to output it to javascript directly:
?>
<script type="text/javascript">
window.MY_PHP_VAR = <?php echo json_encode($myPhpVar); ?>;
</script>
...
window.MY_PHP_VAR now contains your php variable
if your javascript code is on same page where the result is comming then you can use this
var pos = `<?php echo $result['status'] ?>`;
var pos = `<?= $result['status'] ?>`;
===============
// refresh.php
===============
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
echo "<script> alert('". $result['status'] ."'); </script>";
/* If the $result['status'] is 'success' the above line will be converted to:
echo "<script> alert('success'); </script>";
*/
}
?>
so, every time the refresh.php loads, the script is going to get executed.
However, I suggest you to assign a id or class attribute to your h4 where you are echoing your status and access the value using the selectors in the javascript.
you could try giving an id or class to the status.
then in JavaScript you could then get the value of the id or class.
PHP
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<h4> <span class="status">' . $result['status'] . '</span></h4>';
}
?>
JavaScript
var oldStatus = '';
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
// note that since we used a class, you will get the value of the first element only.
var pos = $('.status').text(); // use .text() instead of .val()
if (pos.toLowerCase() == 'out' && pos != oldStatus){
oldStatus = pos;
alert(pos);
}
}
<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>
I have mysql table like this
table = tbl_tst`
clm_num clm_amnt
1 - 25000
2 - 31700
5 - 52900
8 - 45000
I want to get that table data to php array like this
$temp = array([1,25000],[2,31700],[5,52900],[8,45000]);
After i'll convert php array into the javascript using this code
var jsArray = <? echo json_encode($temp); ?>;
Problem is when i run my code it's retrieve nothing. sometimes it's retrieving "Object" :(
This is my full php code
<?php
$con=mysql_connect("localhost","user","pass") or die("Failed to connect with database!!!!");
mysql_select_db("db", $con);
$query = "SELECT * FROM tblnum";
$result = mysql_query($query) or die(mysql_error());
$valueMap = array();
while($row = mysql_fetch_array($result)){
$valueMap[$row['clm_num'] & $row['clm_amnt']];
}
?>
<script>
var jsArray = <? echo json_encode($valueMap); ?>;
for(var i=0; i < jsArray .length; i++){
document.write("<li>"+jsArray [i]+"</li>");
}
</script>
Please help me to find this issue.
Thanks in advance!
You should enable PHP displaying errors, which would tell you there is an error while constructing your array.
<?php
## Turn on error reporting
error_reporting(-1);
ini_set('display_errors', 'On');
....
$valueMap = array();
while($row = mysql_fetch_assoc($result)){
$valueMap[$row['clm_num']] = $row['clm_amnt'];
}
?>
edit:
You requested a different sort of array I see:
while($row = mysql_fetch_assoc($result)){
$valueMap[] = array($row['clm_num'], $row['clm_amnt']);
}
MySQL is no longer maintained, please start using MySQLI or PDO http://rudiv.se/Development/Resource/when-to-use-mysql-vs-mysqli-vs-pdo-in-php
edit:
<?php
$temp = array(
array(1,2500),
array(2,31700)
);
?>
<ul id="list"></ul>
<script>
var json_array = <?php echo json_encode($temp, true);?>;
console.log(json_array);
var ul = document.getElementById("list");
for(i in json_array){
var li = document.createElement("li");
li.appendChild(document.createTextNode(json_array[i][0]+','+json_array[i][1]));
ul.appendChild(li);
}
</script>
First you have to check your php array is come or not. if it will be coming than use this code:
<script type='text/javascript'>
var js_data = <?php echo json_encode($valueMap); ?>;
var jsArray = js_data.toString().split(',');
for(var i=0; i < jsArray.length; i++){
alert(jsArray[i]);
}
</script>
This one for one array or one dimensional array like array['amount'].
i used this code for
$valueMap = array('25000','31700','52900','45000'); // php array
check this.
change this $valueMap[$row['clm_num'] & $row['clm_amnt']]; To $valueMap[] =array($row['clm_num'], $row['clm_amnt']);
$valueMap = array();
while($row = mysql_fetch_assoc($result)){
$valueMap[] =array($row['clm_num'], $row['clm_amnt']);
}
?>
<script>
var jsArray = <?php echo json_encode($temp); ?>;//change <? to <?php it's give error when sort tag is not enable
for(var i=0; i < jsArray .length; i++){
document.write("<li>"+jsArray [i]+"</li>");
}
</script>
//output
1,25000
2,31700
5,52900
8,45000
Try this:
while($row = mysql_fetch_array($result)){
$valueMap[$row['clm_num']] = $row['clm_amnt'];
}
And then in js:
for(var i in jsArray){
if (jsArray.hasOwnProperty(i)) {
document.write("<li>"+jsArray[i]+"</li>");
}
}
This code is when i hardcore the sentence "Have a nice day!", it will echo out the exact same line. My question is what if i want to retrieve sentence from the database, instead of hard-coding it.
<?php
$php_var = "Have a nice day!";
?>
<html>
<head>
<title>Hello</title>
</head>
<body>
<script>
var js_var = "<?php echo $php_var; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
</body>
</html>
I am suppose to do something like this is it? but it cant work. It printed out "SELECT * FROM sen WHERE id=1 ;" on the page.
<?php
$con = mysql_connect(localhost,root,password,database_name);
$php_var = "SELECT * FROM sen WHERE id=1 ;";
?>
<script>
var js_var = "<?php echo $php_var ; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
You're not executing the query and fetching the result. Something like this should work:
<?php
$con = mysqli_connect(localhost,root,password,database_name);
$php_var = mysqli_fetch_assoc(mysqli_query($con, "SELECT * FROM sen WHERE id=1 LIMIT 1"));
?>
<script>
var js_var = "<?php echo $php_var['id']; ?>";
//var js_var = "Try123";
document.writeln(js_var);
//document.writeln(js_var);
</script>
Please be aware of some things:
Don't forgot error handling on the right way. (Not or die)
Check if the MySQL connecton was successfully made.
Possibility of MySQL injection
I've updated mysql_* to mysqli_*, this because mysql_* is deprecated and will being removed in the future.
My suggestion is that you create a Rest api with json response backend in PHP and then have a javascript frontend using like JQuery $get or something.
Remove ; from the query.
Use $php_var = "SELECT * FROM sen WHERE id=1";
I'm basically working on a site in which a user repeatedly clicks a button, increasing his score each time he clicks. I don't want the page to refresh between each click, so I'm using AJAX.
The problems I'm having currently are as follows:
When I try to set my javascript var to = <? echo $result['count']; ?>, it doesn't seem to work.
I don't understand how to correctly use PDO to UPDATE a MySQL table with a calculation in the query, such as $update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");. Is this the correct syntax for the calculation and is this the right way to do it in PDO?
Here is the code for my testing page which I am using for the clicking system:
<html>
<?php
$hostname = 'localhost';
$username2 = 'refrigerator';
$password = 'xxx';
$dbh = new PDO("mysql:host=$hostname;dbname=refrigerator", $username2, $password);
$username = $_COOKIE["user"];
$rows = $dbh->prepare("SELECT count FROM count WHERE username = '$username'");
$rows->execute();
$result = $rows->fetchALL();
$result['count'] = $count;
if(isset($_POST['action'])){
if ($_POST['action'] == 'increase'){
$update = $dbh->execute("UPDATE count SET count='$count'+1 WHERE username='$username'");
}
}
?>
<body>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var count = <? echo $result['count']; ?>;
$("#update").click(function() {
$.ajax({
type: "POST",
url: "button.php",
data: {"action":"increase"},
success: function(update) {
count++;
$("#counter").html(+count);
}
});
});
});
</script>
<button id="update" type="button">Button</button>
<div id="counter"><? echo $result['count']; ?></div>
</body>
</html>
Thanks a lot, any help would be greatly appreciated. Even if you can point me in the right direction which will help me answer my questions, that would be awesome.
Thank you
You should have:
$count = $result['count'];
Instead of:
$result['count'] = $count;
The variable to the left of the = sign is what is receiving the assignment from whatever value is on the right of the = sign.
In your update statement you could, instead of using your count variable, could do:
$update = $dbh->execute("UPDATE count SET count=count+1 WHERE username='$username'");