how i can parse an Variable (php with js script) to an js file (jquery)?
This is what i do:
<script type='text/javascript'>
<?php
session_start();
$var1 = $_SESSION['one'];
$var2 = $_SESSION['two'];
$con = mysqli_connect("");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();}
$result = mysqli_query($con,"Select name FROM table WHERE one < '". $var1 . "' OR two < '". $var2 . "'");
$rows=array();
while($row=mysqli_fetch_array($result))
{
$rows[]=$row["name"];
}
$js_array = json_encode($rows);
echo "var stat = ". $js_array . ";\n";
?>
</script>
In my js file i have this:
$(document).ready(function($)
{
for (var x = 0; x < stat.length; x++) {
$(".class#" + stat[x]).css("background-color", "#e74c3c");
alert(stat);
}});
My browser show this :
var stat = ["a1","a2","a3"];
How i can now get the php js_array to the stat variable (js)?
Alternatively, since your using jquery, you could use $.each() function. This is very useful to what you want to achieve. Consider this example:
<div class="class" id="a1" style="width: 50px; height: 50px;"></div>
<div class="class" id="a2" style="width: 50px; height: 50px;"></div>
<div class="class" id="a3" style="width: 50px; height: 50px;"></div>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var stat = null;
<?php
// sample data
$array_from_db = array('a1', 'a2', 'a3');
$data = json_encode($array_from_db);
echo "stat = $data;"; // assign it to stat
?>
// use $.each();
$.each(stat, function(index, element){
// random colors for example's sake
var color = '#'+(Math.random()*0xFFFFFF<<0).toString(16);
$('.class#'+element).css({backgroundColor: color});
});
});
</script>
Related
<?php
include ('config.php');
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Platser</title>
<link rel="stylesheet" href="style.css" type="text/css"/>
<script type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js"></script>
<script type="text/javascript" src="js/jquery.json-2.2.min.js"></script>
</head>
<body>
<div id="glassbox">
<?php
if(isset($_POST['Spara'])){
}
$antal = $mysqli->query("SELECT `Grupp ID` FROM `Elevgrupper` WHERE `Grupp ID`=25");
$num = $antal->num_rows;
$res = $mysqli->query("SELECT `Namn`, `Efternamn` FROM `Elever` WHERE `ID` IN (SELECT `Användar ID` FROM `Elevgrupper` WHERE `Grupp ID` = 25)");
for ($i = 1; $i<=$num; $i++){
$get_coords = mysqli_query($mysqli, "SELECT * FROM coords WHERE id = '" . $i . "'");
$row = $get_coords->fetch_assoc();
$ok = $res->data_seek($i-1);
$row1 = $res->fetch_assoc();
//
$x = $row['x_pos'];
$y = $row['y_pos'];
echo '<div id="e'. $i .'" class="e" style="left:'.$x.'px; top:'.$y.'px;"><p id="p' . $i .'">'. $row1["Namn"] . " " . $row1["Efternamn"] . '</p></div>';
}
?>
</div>
<form action="<?echo $_SERVER['PHP_SELF'];?>">
<input onclick="spara();" type="submit" name="Spara">
</form>
<div id="respond"></div>
</body>
<script type="text/javascript">
$(document).ready(function() {
var antal = document.getElementsByClassName("e");
for (var i = 1; i <= antal.length; i++) {
$("#e" + i).draggable({
containment: '#glassbox',
scroll: false
});
}
});
function spara(){
var antal = document.getElementsByClassName("e");
for (var i = 1; i <= antal.length; i++) {
var coords=[];
var coord = $("#p" + i).position();
var item={ coordTop: coord.left, coordLeft: coord.top };
coords.push(item);
var order = { coords: coords };
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response){
});
}
}
</script>
</html>
<?php
if(!$_POST["data"]){
echo "Nothing Sent";
exit;
}
include ('config.php');
$data = json_decode($_POST["data"]);
foreach($data->coords as $item) {
//Extract X number for panel
$coord_X = preg_replace('/[^\d\s]/', '', $item->coordTop);
//Extract Y number for panel
$coord_Y = preg_replace('/[^\d\s]/', '', $item->coordLeft);
//escape just-in case
$x_coord = mysqli_real_escape_string($mysqli, $coord_X);
$y_coord = mysqli_real_escape_string($mysqli, $coord_Y);
//Setup Query
$sql = "UPDATE coords SET x_pos = '" . $x_coord . "' WHERE id"= . substr($data->id, -1) .;
mysqli_query($mysqli, $sql);
$sql = "UPDATE coords SET y_pos = "'. $y_coord .'" WHERE id"= . substr($data->id, -1) .;
mysqli_query($mysqli, $sql);
}
//Return Success
echo "success";
?>
If I am not mistaken everything except the spara function should work and it's driving me crazy since I don't get even get any error messages, seems like it runs through the entire script without errors and without saving anything.
What I am trying to do is a teacher tool that from a database which contains all students places out benches that you can drag around and move to your choosing so that you can decide seats for everyone without having to do much work as the teacher. And I want the layout to save by pressing a button which runs the function.
I believe this line could be wrong:
$.post('updatecoords.php', 'data='+$.toJSON(order), function(response)
Usually I would have something like this:
$.post('updatecoords.php', {data: somevar}, function(response)
Give that a try, assign $.toJSON(order) to a variable and pass it as suggested.
UPDATE:
Based on Domeniks feedback below, you probably just need to do this:
$.post('/updatecoords.php', somevar, function(response)
I tried to add checked property to a specific checkbox using jquery, but it seems doesn't work properly.
Checkbox Function Display
function product_category_loop_array ($product_category_array = array (), $parent_id = 0, $margin = -20) {
if (!empty ($product_category_array[$parent_id])) {
$margin = $margin + 20;
foreach ($product_category_array[$parent_id] as $items) {
echo "<input style='margin: 0 0 0 ".$margin."px; overflow: hidden;' id='".$items['id']."' class='category_checkbox left' name='product_category[]' type='checkbox' value='".$items['id']."'><label class='category_checkbox_label left'>".$items['name']."</label>
<div class='clear'></div>";
product_category_loop_array ($product_category_array, $items["id"], $margin);
}
}
}
function product_category () {
$db_connect = mysqli_connect (db_host, db_username, db_password, db_name);
$product_category_query = $db_connect->query ("SELECT id, name, parent_id FROM `product_category` ORDER BY name ASC");
$product_category_array = array ();
if (mysqli_num_rows ($product_category_query)) {
while ($row = mysqli_fetch_array ($product_category_query, MYSQLI_ASSOC)) {
$product_category_array[$row['parent_id']][] = $row;
}
product_category_loop_array ($product_category_array);
}
}
HTML
<div id="tabs-2" class="product_detail hide">
<div class="left">
<form class="product_detail_form" method="post" action="">
<?php product_category () ?>
<p class="detail_submit"><input name="save_product_category" type="submit" value="Save"></p>
</form>
</div>
</div>
Jquery
<script>
$ (document) .ready (function () {
<?php echo $hide_div ?>;
var selected_array = <?php echo json_encode ($product_category_selected) ?>;
$.each (selected_array (key, value) {
$ ("#"+value).prop("checked", true);
});
});
</script>
Any help will be appreciated.
Use
$ ("#"+value).attr("checked", "checked");
<script>
$(document).ready(function() {
<?php echo $hide_div ?>;
// DECODE JSON IN JS
var selected_array = $.parseJSON(<?php echo json_encode ($product_category_selected) ?>);
$.each(selected_array(key, value) {
$("#" + value).prop("checked", true);
});
});
</script>
I am trying to get member photos from my sql and show as a slide. i am trying this with DHTML slideshow script- © Dynamic Drive DHTML code library (www.dynamicdrive.com) check the basic code here basic code
now i change the code to get the image url from mysql using php
my code :
Here is the html and script code.
<html>
<head>
<script type="text/javascript">
/***********************************************
* DHTML slideshow script- © Dynamic Drive DHTML code library (www.dynamicdrive.com)
* This notice must stay intact for legal use
* Visit http://www.dynamicdrive.com/ for full source code
***********************************************/
var photos = new Array()
<?php
$mid=$_POST['mid'];
//echo $mid;
$mid=$_POST['mid'];
require_once("datacon.php");
$result = $data->query("SELECT * FROM tempregist where id= $mid ");
$row = mysqli_fetch_array($result) or die(mysqli_error());
$folde= "uploads/thumb/";
$folder=utf8_encode($folde);
//echo $folder;
$mid1 =$row['mid'];
require_once("datacon.php");
$result = $data->query("SELECT image_name FROM tbl_images where mid= '$mid1' ");
$phparray = array();
$count = mysqli_num_rows($result);
if($count>=1)
{
while($crow = mysqli_fetch_array($result))
{
$i=0;
$phparray[$i] = $folder. $crow['image_name'];
$i++;
?>
photos<?php echo"[".$i."]" ;?> = <?php echo '"'. implode( $phparray) . '"'."\n" ;
} }
?>
var photoslink = new array
var x
x =<?php echo json_encode($count) ?>;
var which=0
/
//Specify whether images should be linked or not (1=linked)
var linkornot=0
Set corresponding URLs for above images. Define ONLY if variable linkornot equals "1"
photoslink[0]=""
photoslink[1]=""
photoslink[2]=""
//do NOT edit pass this line
var preloadedimages=new Array()
for (i=0;i<photos.length;i++){
preloadedimages[i]=new Image()
preloadedimages[i].src=photos[i]
}
function applyeffect(){
if (document.all && photoslider.filters){
photoslider.filters.revealTrans.Transition=Math.floor(Math.random()*23)
photoslider.filters.revealTrans.stop()
photoslider.filters.revealTrans.apply()
}
}
function playeffect(){
if (document.all && photoslider.filters)
photoslider.filters.revealTrans.play()
}
function keeptrack(){
window.status="Image "+(which+1)+" of "+photos.length
}
function backward(){
if (which>0){
which--
applyeffect()
document.images.photoslider.src=photos[which]
playeffect()
keeptrack()
}
}
function forward(){
if (which<photos.length-1){
which++
applyeffect()
document.images.photoslider.src=photos[which]
playeffect()
keeptrack()
}
}
function transport(){
window.location=photoslink[which]
}
</script>
</head>
<body>
<div align="center">
<img src="images/logo.jpg" border = "2" align="center" alt="no logo">
</div>
<table border="0" cellspacing="0" cellpadding="0">
<tr>
<td width="100%" colspan="2" height="22"><center>
<script>
if (linkornot==1)
document.write('<a href="javascript:transport()">')
document.write('<img src="'+photos[0]+'" name="photoslider" style="filter:revealTrans(duration=2,transition=23)" border=0>')
if (linkornot==1)
document.write('</a>')
</script>
</center></td>
</tr>
<tr>
<td width="50%" height="21"><p align="left">Previous Slide</td>
<td width="50%" height="21"><p align="right">Next Slide</td>
</tr>
</table>
<p align="center"><font face="Arial" size="-2">Free DHTML scripts provided by<br>
Dynamic Drive</font></p>
</body>
</html>
Now i am getting out put as follows
var photos = new Array()
photos[0] = "uploads/thumb/220816_1412135472.jpeg"
photos[0] = "uploads/thumb/312840_1412135511.jpeg"
photos[0] = "uploads/thumb/589453_1412135511.jpeg"
photos[0] = "uploads/thumb/467341_1412135630.jpeg"
photos[0] = "uploads/thumb/800658_1412135790.jpeg"
photos[0] = "uploads/thumb/366793_1412135826.jpeg"
But i need the out put like this
photos[0] = "uploads/thumb/220816_1412135472.jpeg"
photos[1] = "uploads/thumb/312840_1412135511.jpeg"
photos[2] = "uploads/thumb/589453_1412135511.jpeg"
photos[3] = "uploads/thumb/467341_1412135630.jpeg"
photos[4] = "uploads/thumb/800658_1412135790.jpeg"
photos[5] = "uploads/thumb/366793_1412135826.jpeg"
i tried so much. please any one help.
while($crow = mysqli_fetch_array($result))
{
$i=0;
You're resetting $i in your loop
$result = $data->query("SELECT image_name FROM tbl_images where mid= '$mid1' ");
{
$count = mysqli_num_rows($result);
if($count>=1)
{
$i=0;
while($crow = mysqli_fetch_array($result))
{
$phparray[$i] = $folder. $crow['image_name'];
echo $i. "\n";
$i++;
}
}
use $i=0 initialization outside while
finally i found it with help of Hammerstein and Dhanush Bala. i mingled two persons suggestion i got it here is the answer
$phparray = array();
$count = mysqli_num_rows($result);
if($count>=1)
{
$b=0;
while($crow = mysqli_fetch_array($result))
{
$i=0;
$phparray[$i] = $folder. $crow['image_name'];
$i++;
$b++;
?>
photos<?php echo"[".$b."]" ;?> = <?php echo '"'. implode( $phparray) . '"'."\n" ;
} }
now the out put is:
photos[1] = "uploads/thumb/220816_1412135472.jpeg"
photos[2] = "uploads/thumb/312840_1412135511.jpeg"
photos[3] = "uploads/thumb/589453_1412135511.jpeg"
photos[4] = "uploads/thumb/467341_1412135630.jpeg"
photos[5] = "uploads/thumb/800658_1412135790.jpeg"
photos[6] = "uploads/thumb/366793_1412135826.jpeg"
thanks Hammerstein and Dhanush Bala
Still a programming and markup newbie...
I have several little in/out button that reads and writes back from a mysql table to track whether different users are available or unavailable. But I can only click the button once to change the status. After that, it stops responding. How can I get it to just keep working? Thanks!!!!
list.php
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script>
$(function(){
$(".rating").on("click", function(){
var status = $(this).attr("id").substr(0,1);
var id = $(this).attr("id").substr(1);
var data = "id="+id+"&status="+status;
$.ajax({
type: "POST",
url: "rate.php",
data: data,
success: function(e){
$("#r"+id).html(e);
}
})
});
});
</script>
<style>.rating { cursor: pointer; }</style>
</head>
<body>
<?php
include ("headers.php");
$qq = mysql_query("SELECT * FROM $io");
while($rr=mysql_fetch_array($qq)){
$id = $rr["id"];
$content = $rr["status"];
include("buttons.php");
$list .= '<div style="border-bottom: 1px #32baed solid">'.$q[0].'
<div id="r'.$id.'"><img class="rating" id="'.$q[0].$id.'"
src="'.$color.'"> '.$status.'</div></div><br><br>';
}
echo $list;
?>
</body>
</html>
rate.php
<?php
include ("headers.php");
$id = $_POST["id"];
$status = $_POST["status"];
if($status == 0){
mysql_query("UPDATE $io SET status = 1 WHERE id='$id'");
}
else {
mysql_query("UPDATE $io SET status = 0 WHERE id='$id'");
}
include("buttons.php");
$list = '<img class="rating" id="'.$q[0].$id.'" src="'.$color.'"> '.$status;
echo $list;
?>
buttons.php
<?php
$q = mysql_query("SELECT status FROM $io WHERE id='$id'");
$q = mysql_fetch_array($q);
if($q[0]){
$color = "green.png";
}
else{
$color = "red.png";
}
?>
headers.php
<?php
$c = mysql_connect("localhost", "username", "password");
$db = mysql_select_db("likes", $c);
$io = 'io';
?>
Replace
$(".rating").on("click", function(){
With
$(document).on("click", ".rating", function(){
You have to do like this:
$(document).on("click", ".rating", function(){
//YOUR CODES HERE
});
And make sure that these codes are outside of document ready function.
Read the documentation for help on .on()
I´m really frustrated about a problem with my website. From a php File, I get this list of JSON:
{"Data":{"Recipes":{"Recipe_5":{"ID":"5","TITLE":"Spaghetti Bolognese"},"Recipe_7":{"ID":"7","TITLE":"Wurstel"},"Recipe_9":{"ID":"9","TITLE":"Schnitzel"},"Recipe_10":{"ID":"10","TITLE":null},"Recipe_19":{"ID":"19","TITLE":null},"Recipe_20":{"ID":"20","TITLE":"Hundefutter"},"Recipe_26":{"ID":"26","TITLE":"Apfelstrudel"},"Recipe_37":{"ID":"37","TITLE":null},"Recipe_38":{"ID":"38","TITLE":"AENDERUNG"},"Recipe_39":{"ID":"39","TITLE":null},"Recipe_40":{"ID":"40","TITLE":"Schnitzel"},"Recipe_42":{"ID":"42","TITLE":"Release-Test"},"Recipe_43":{"ID":"43","TITLE":"Wurstel2"}}},"Message":null,"Code":200}
In my html file, I´ve got a JS function that parses this JSON data and save it to a array.
<script type="text/javascript">
function test() {
//var availableTags = new Array(400);
//availableTags[0] = "Test";
alert("misstake");
var availableTags = JSON.parse(<?php include("/php/search_new.php"); ?>);
alert("misstake");
//var availableTags = JSON.parse(<?php include("/php/getAllRecipes.php"); ?>);
alert("misstake");
for(var i=0;i<availableTags.length;i++){
alert("<b>availableTags["+i+"] is </b>=>"+availableTags[i]+"<br>");
}
alert("Hallo");
}
</script>
I´m sure, the function is called because I tried it just with a alert in it.
Here´s my HTML:
<body>
<form action="search.html" onsubmit="test()">
<input type="text" class="searchinput" style="margin-left: 850px; margin-top: 0px; width:170px; background: #fff url(images/search_icon.png) no-repeat 100%;" placeholder="Suchen..."></input>
<input type="submit" value="" width: 5px></input>
</form>
</body>
So there must be a mistake at
var availableTags = JSON.parse(<?php include("/php/search_new.php"); ?>);
What is the problem? How can I figure out that?
If you need the php:
<?php
include 'db_connect.php';
session_start();
if (isset($_SESSION['last_activity']) && (time() - $_SESSION['last_activity'] > 1200)) {
session_destroy();
session_unset();
}
else
{
$_SESSION['last_activity'] = time();
}
$arr = array('Data' => null,'Message' => null,'Code' => null);
$sql = "SELECT * FROM RECIPES";
$result = mysql_query($sql,$db) or exit("QUERY FAILED!");
while($row = mysql_fetch_array($result))
{
$arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['ID'] = $row['recipes_id'];
$arr['Data']['Recipes']['Recipe_'.$row['recipes_id']]['TITLE'] = $row['title'];
}
if($arr['Data'] == null)
{
$arr['Message']= "nothing found";
$arr['Code'] = 404;
}
else
{
$arr['Code'] = 200;
}
mysql_close($db);
echo json_encode($arr);
?>
You don't need to do a JSON.parse you can simply do
var availableTags = <?php include("/php/search_new.php"); ?>;
And name your php file as somename.php and make sure it is on some local or hosted server.
and you can see you data as,
alert(a['Data']["Recipes"]["Recipe_5"]["ID"]);