Javascript function calls php - javascript

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"]);

Related

Trying to open pdf file in new browser window

Cant get the PDF open in new browser window. There is a php code I use to set the PDF and open it!
<?php
if (($_POST['name_check']=="in") || ($_GET['type']=="in")){
header('Content-Type: application/pdf; charset=windows-1257');
header("Content-Disposition: inline; ");
header('Accept-Ranges: bytes');
$file_type = "in";
$flag = 0;
}
else{
header('Content-Type: application/pdf; charset=windows-1257');
header("Content-Disposition: inline;");
header('Accept-Ranges: bytes');
$file_type = "out";
$flag = 1;
}
?>
<?php session_start();
if (((isset($_SESSION['UserID'])) and (isset($_SESSION['Pin_code']))) and (isset($_COOKIE['CookieMy']))){
$form='<form action="login.php" method="get" style="width: 900px;margin: -1px auto -57px auto;" class="exit_but">
<input type="submit" name="exit" value="EXIT" style="margin-left: 800px;"></form>';
echo $form;
} else {
header("Location: login.php");
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="css/style1.css" />
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
idleTimer = null;
idleState = false;
idleWait = 1200000;
var theElement = document.getElementById("elem");
$(document).ready(function(){
$(document).bind('mousemove keydown scroll click', function(){
clearTimeout(idleTimer);
idleState = false;
idleTimer = setTimeout(function(){
idleState = true;
window.location.href = "login.php"
}, idleWait);
});
});
</script>
</head>
<body>
<?php
function last(){
if (($_POST['name_check'])=="in"){
$type = '"pdf-in"';
$flag=0;
echo "<script>window.flag_in=false;</script>";
}
else{
$type = '"pdf-out"';
$flag=1;
echo "<script>window.flag_in=true;</script>";
}
if (!isset($aircraftid)){
$aircraftid = $_POST['hostcountry'];
$aircraftid='"'.$aircraftid.'"';
}
if (!isset($date)){
$date = $_POST['per1'];
$date=date($date);
}
include ("config.php");
//////////////////////////////////////////
$mysqli = new mysqli($dbconf['host'], $dbconf['user'], $dbconf['password'], $dbconf['dbname']);
if ($mysqli->connect_errno) {
echo "MySQL: (" . $mysqli->connect_errno . ") " . $mysqli->connect_error;
}
$query = mysqli_multi_query( $mysqli, "SELECT dn_get_flight_file_name($date,$aircraftid,$type);") or die( mysqli_error( $mysqli ) );
if( $query )
{
if ($result = $mysqli->store_result()) {
while ($row = $result->fetch_row()) {
$PDF_File_Name=$row[0];
}
$result->free();
}
}
///////////////////////////////////
mysqli_close( $mysqli );
$qwerty=$PDF_File_Name;
///////////////////////////////////
$ftp .='ftp://'.$ftp_user.':'.$ftp_pwd.'#'.$ftp_server;
if($flag==0){
$file_path_ftp = $ftp_path_pdf_in.$qwerty;
$file_path_local = "in/".$qwerty;
}
else{
$file_path_ftp = $ftp_path_pdf_out.$qwerty;
$file_path_local = "out/".$qwerty;
}
$file_path_ftp = trim($file_path_ftp);
$file_path_local = trim($file_path_local);
$file = $file_path_local;
$current_content = file_get_contents($ftp.$file_path_ftp);
file_put_contents($file, $current_content);
$qwerty=$file_path_local;
$date2 = $_POST['date'];
$num = $_POST['num'];
return array ($qwerty,$date2,$num);
}
if (isset($_GET['name'])){
$qwerty=$_GET['name'];
}
else {
list ($qwerty,$date2,$num) = last();
}
if (!file_exists($qwerty)) {
$file_path_local=$qwerty;
$slash_occur = stripos($qwerty, '/');
$file_type = substr($qwerty, 0, $slash_occur);
$file_name = substr($qwerty, $slash_occur+1);
if($file_type=='pdf-in'){
$file_path_ftp = $ftp_path_pdf_in.$file_name;
}
else{
$file_path_ftp = $ftp_path_pdf_out.$file_name;
}
echo "<h2>file_type = ".$file_type.", file_name = ".$file_name."</h2>";
$ftp .='ftp://'.$ftp_user.':'.$ftp_pwd.'#'.$ftp_server;
$current_content = file_get_contents($ftp.$file_path_ftp);
file_put_contents($qwerty, $current_content);
}
if (isset($_GET['date'])){
$date2=$_GET['date'];
}
if (isset($_GET['num'])){
$num=$_GET['num'];
}
?>
<?php
if (($_POST['name_check']=="in") || ($_GET['type']=="in")){
#readfile($ftp_path_pdf_in.$qwerty);
} else {
#readfile($ftp_path_pdf_out.$qwerty);
}
?>
</body>
</html>
I'm trying to open PDF file in the new (Chrome) browser window.
document.action =window.open('date_PDF.php', 'newWindow', 'width=1000, height=1000');
Error is Failed to load PDF document.
When I do document.getElementById("edit").action ="date_PDF.php"; it opens pdf.
I get the PDF file from the ftp server and than display it on date_PDF.php #readfile($ftp_path_pdf_in.$qwerty);
Where is the problem?
Thank you!
You have not defined the name_check html element. Also you have not passed the 'type' parameter in the url. I think the name_check and type are present on the page from where you open the pdf file.
If you want to open the pdf file using window.open then you should use the url: date_PDF.php?type=in
After the readfile statement you should have an exit statement. See the example for the readline function: http://php.net/manual/en/function.readfile.php#refsect1-function.readfile-examples

Give Default Checked Value To The Checkbox Using Jquery

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>

Assigning PHP Variables To Javascript Variables Not Working

I am currently having trouble with this. I would like to make one of my variables in Javascript have a PHP value. Here is what I mean:
<script>
JSvariable = <?php echo $PHPvariable; ?>;
</script>
For some reason that is not working. Here is my full (snippet) of code:
<script>
currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
I am sure it is some stupid mistake, but I can not seem to find it! What is the problem? Thank you!
PS #parentcommentholder is an input field, and it just had the value 0 after the field is supposed to of been changed.
Here is some source:
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<script>
var currentreplyid = <?php echo $allpostcomments[$key]['replyid']; ?>;
$('#parentcommentholder').val(currentreplyid);
</script>
<input id="parentcommentholder"></div>
Don't forgot for give quotes ' or ". Use following:
<script>
var JSvariable = '<?php echo $PHPvariable; ?>';
//or
var JSvariable = "<?php echo $PHPvariable; ?>";
</script>
Reason: If php variable contains string and if while assigning it to javascript variable we shall not give quote like:
<?php $PHPvariable = 'String';?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = String;//which will give error in javascript
But this will work fine if PHP variable contains a numeric value like:
<?php $PHPvariable = 2;?>
var JSvariable = <?php echo $PHPvariable; ?>;
Will transform into :
var JSvariable = 2;//which will work perfect
Complete code should be:
<script>
var currentreplyid = "<?php echo $allpostcomments[$key]['replyid']; ?>";
//or if you are sure your variable contains int value
var currentreplyid = parseInt("<?php echo $allpostcomments[$key]['replyid']; ?>");
$('#parentcommentholder').val(currentreplyid);
</script>
Try the below instead of using javascript (as I don't think you need it):
<?php
$postcommentsquery = "SELECT * FROM comments WHERE parent = :parent AND postid = :postid ORDER BY datecreated DESC";
$postcommentsparams = array(':parent' => $allreplies[$key]["postid"],
':postid' => $postid);
try{
$postcommentsstmt = $connection->prepare($postcommentsquery);
$postcommentsresult = $postcommentsstmt->execute($postcommentsparams);
}
catch(PDOException $ex){
echo ("Failed to run query: " . $ex->getMessage());
}
$allpostcomments = $postcommentsstmt->fetchAll();
foreach ($allpostcomments as $key => $value) {
?>
<input id="parentcommentholder" value="<?php echo ((int)$allpostcomments[$key]['replyid']>0) ? $allpostcomments[$key]['replyid'] : 0; ?>" />
<?php
}
?>
If your defiantly sure $allpostcomments[$key]['replyid'] is bringing back a value, this should work without any issues.

how to php js variable to jquery file

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>

how can i get my script/jquery-ajax to continue responding to clicks?

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()

Categories

Resources