"Convert" PHP to Javascript - php

I'm using CodeIgniter and I have a PHP MySQL Statement in a model:
function getAllDevices() {
$query = $this->db->query("SELECT * FROM Device_tbl ORDER BY Manufacturer");
return $query->result();
}
I then pass this through my controller to my view using:
$this->load->model("get_device");
$data['results'] = $this->get_device->getAllDevices();
And output this into a div using the following PHP:
<div class="hold-cont">
<div class="holder">
<div class="image-hold"><img class="image-icon" src="<?php echo base_url(); ?>assets/images/devices/<?php echo $row->Image; ?>"></div>
</div>
<div class="device-name devicename-txt">
<?php $mod = $row->Model;
$model = str_replace(" ","-",$mod);
?><?php echo($row->Manufacturer. ' ' .$row->Model); ?><br>
</div>
</div><?php } ?>
This currently works fine, however I have now incorporated a searchbox into my page which uses the jQuery function autocomplete and uses the JSON Array of $results
What I need to do is "convert" the PHP into Javascript which will enable the page to be populated using the JSON Array. I then need to be able to use this to pass the selection from the search box into a query which will change the content on the page without reloading it.
How can I go about this? I previously mashed together a way of doing it using the ajax function in jQuery, however this requires a URL which contained a PHP MySql statement which I cannot do now. The idea behind doing it like this is so it only runs 1 SQL Query when the page loads and I cannot change this method.

There is nothing to stop PHP "writing" Javascript.
You would need to build up a suitably formatted Javascript object either manually or by using the json_encode method of PHP (which essentially turns a PHP object into it's JSON notation). Assuming your PHP object is in $row then something like:
<code>
<script language="text/javascript">
var jsObject = <?php json_encode($row); ?>
</script>
</code>
Would give you a Javascript object in jsObject containing keys and values corresponding to the properties of the PHP $row object that you can then work with from Javascript.

json_encode();
json_decode();
Turns PHP arrays into a JSON array and back.
http://php.net/manual/en/function.json-encode.php
They work great.

Your ajax page:
$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);
and fetch this echoed json encoded data in your javascript
this is just a rough code, avoid using mysql function.

Related

Can't send DOM var trough $_session

I am extracting some parts from a html webpage using DOM+php and trying to send the results to other pages as $_SESSION variables and eventually to update a mysql DB.
example of the HTML webpage code:
<html>
<body>
<div id="title">some title </div>
<div id="city">some city</div>
<div id="country">some country</div>
<div id="company">some company</div>
<div id="text">some text</div>
<body>
<html>
This is the code that I a using to get the data and is working...I can echo the $var:
<?php session_start(); ?>
---- some HTML---
<?
include('simple_html_dom.php');
$file = 'webpage.html';
$html = new simple_html_dom();
$html->load_file($file);
$title = $html->getElementById('title');
$city = $html->getElementById('city');
$country = $html->getElementById('country');
$company = $html->getElementById('company');
$text= $html->getElementById('text');
echo '<b>'.$title.'</b>';
$_SESSION['title'] = $title;
echo '<b>'.$city.'</b>';
$_SESSION['city'] = $city;
echo '<b>'.$country.'</b>';
..............
?>
My problem is that I can't send this $var ($title,$city, ...) to any other php page using $_SESSION... and I get this error:
Catchable fatal error: Object of class __PHP_Incomplete_Class could not be converted to string
According to the PHP docs, sessions can only contain data that can be serialized.
When PHP shuts down, it will automatically take the contents of the $_SESSION superglobal, serialize it, and send it for storage using the session save handler.
Source: http://php.net/manual/en/session.examples.basic.php
It looks like DOM elements unfortunately cannot be serialized and therefore cannot be stored in the session correctly.
UPDATE: It looks like you can fix this by casting the DOM elements as a string:
$_SESSION['title'] = (string)$title;
$_SESSION['city'] = (string)$city;

Passing a PHP variable to a java-script function

im trying to pass a value to a java-script function. but when i click the link i get a
Uncaught SyntaxError: Unexpected identifier
here is the code
<?php
include_once("php_includes/check_login_status.php");
$routeHTML = '';
$sql = "SELECT user,title FROM route";
$query = mysqli_query($db_conx, $sql);
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)) {
$title = $row["title"];
$user = $row["user"];
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';
}
?>
i echo the $routeHTML in a div tag
you forgot to add quotes for the javascript:
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';
You'll have to surround your string with a '' quotes like this...
$routeHTML .= '<p>Planned By '.$user.'</p>'.$title.'<br />';
The Parameter to your JS function is undefined (since the parsed HTML is missing quotes - JS assumes title is an undefined variable).
You forgot to escape the quotes, do like this:
fetchdata(\''.$title.'\')
Otherwise php will not render the ' properly and you get an error.
You can pass a php variable to a javascript function in this way:
<input type="button" value="Send" onClick="js_function('<?php echo $var; ?>')">
It's generally not recommended to make inline Js (as an attribute of the tag).
So, i encourage you to separate javascript from html code, like this :
Html:
$routeHtml = '<p>Planned By '.$user.'</p>'.$title.'<br />';
Js (with jQuery, but also work for vanillaJs):
$(document).ready(function(){
$(".MyLink").click(function(e){
fetchData($(this).data("title"))
});
});
Note the data-title attribute, the data-* attributes are intended to store custom data, so it's a great way to exchange informations between php and Javascript inside templates.
More info about data-* attributes : http://webdesign.tutsplus.com/tutorials/htmlcss-tutorials/all-you-need-to-know-about-the-html5-data-attribute/

Include a php file with a lot of includes using ajax .load()

I'm trying to load an php file through ajax using load(). Here's my code:
var loadUrl = "myfile.php";
$("#lst-results").load(loadUrl);
So, when I do this, it works:
<?php
$test = 'Hi :3';
?>
<h3>Hi</h3>
<h3><?php echo $test ?></h3>
But I need to include a file that contain a lot of includes and functions using a lot of different classes. I've tryed to include this file and use it as a function like this, but does not work and Nothing appears int the load() results. This function return an array.
<?php
include 'path/myfile.php';
$result = myFunction();
?>
I can't figure out how to solve it. :(
You need to "echo" the $result.
<?php
include 'path/myfile.php';
$result = myFunction();
echo $result;

Moving JavaScript into PHP

I'm just starting out with PHP, and I am attempting to move some jQuery ajax into PHP. Here is my PHP file:
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT * FROM agency ORDER BY name";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo "<li class=\"agency\">$name<ul class=\"agency-sub\"></ul></li>";
}
include 'closedb.php';
?>
Here is my current js function:
//Add Agency content
$("ul.top-level").on("click", "li.agency a", function (event) {
if($(this).next().length) {
var numbs = $(this).attr("href").match(/id=([0-9]+)/)[1];
showContentAgency(numbs, this);
} else {
$(this).closest('ul').find('a').removeClass('sub-active');
}
event.preventDefault();
});
And here is the showContentAgency(); function:
function showContentAgency(id, elem) {
$.post("assets/includes/contentAgency.php?id=id", {
id: id
}, function (data) {
$(elem).addClass("nav-active").parent().find("ul").html(data).show();
});
}
What I'd like to do is have PHP render the unordered list rather than have jQuery insert it. This is how it is currently featured in the above PHP file:
echo "<li class=\"agency\">$name<ul class=\"agency-sub\"></ul></li>"
So I would like the PHP to populate the <ul class="agency-sub"> list.
The structure of your code is a little bit unclear to me, but the broad outline is this: You take whatever function is generating the content in contentAgency.php and call that to get the HTML, then stick that inside when you're building up the list.
Php can not access the DOM of the page like Jquery can. If you wanted to access the DOM with Php, you would have to parse the entire web page, which is probably impractical for what you want to do. Php can only modify the page before it is loaded by the browser. If you want to run code after page load, you have to use javascript.
We might be able to help you more if you post more of your code, as we currently don't know what the page's code looks like.
Is this a list inside list?
By the way you can write php code like below, it is more readable
<?php
include 'config.php';
include 'opendb.php';
$query = "SELECT * FROM agency ORDER BY name";
$result = mysql_query($query);
while($row = mysql_fetch_assoc($result)){
$id = $row['id'];
$name = $row['name'];
echo "<li class='agency'><a href='contentAgency.php?id=$id'>$name</a><ul class='agency-sub'></ul></li>";
}
include 'closedb.php';
?>
if you are using double quotes in echo you can use single quotes inside.
I'm uncertain as to what exactly you want but it sounds like you're looking for the 'foreach' loop. When I wanna populate a list of stuff from a result set i simple use:
<ul>
<? foreach($result as $object) ?>
<li><?=$object?></li>
<? endforeach; ?>
</ul>
foreach acts a for loop but doing all the logic in the background. Hope this helps.

PHP / MySQL / JSON encoding help

I am trying to implement the auto-complete script from http://www.devbridge.com/projects/autocomplete/jquery/. It's asking for JSON output like:
{
query:'Li',
suggestions:['Liberia','Libyan Arab Jamahiriya','Liechtenstein','Lithuania']
}
I am using PHP/MySQL. My query to get the suggestions would be something like...
<?
$drug = $_GET['drug'];
$query = mysql_query("SELECT * FROM tags_drugs WHERE drug_name LIKE '$drug%'");
while ($query_row = mysql_fetch_array($query))
{
$drug_name = $query_row['drug_name'];
}
?>
This is where I'm stuck. How do I put the array $drug_name in the suggestions and encode it for json? Thanks in advance!
Use
$drug_name[] = $query_row['drug_name'];
instead of $drug_name = $query_row['drug_name'];
Then use
?>
<script type="text/javascript">
var drugName = <?php echo json_encode($drug_name);?>
</script>
Use this grugName variable in your JavaScript.
json_encode($drug_name)
From PHP.net - json_encode

Categories