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
Related
I have a javascript function as follows::
//THIS IS javascript.js
function dosomething(data){
//splits and do something else
}
$(document).ready(function () {
dosomething();
}
Below is a php file from search(database search with jquery and ajax)
//THIS IS mysearch.php
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$url = $row['url'];
$text = $row['text'];
$argument = $url"."$separator"."$text";
);
How do I pass $argument to javascript function? I have tried something like this.
echo '<p>'.$text.'</p>';
What would be good way to approach this?
Any help would be appreciated! Thanks in advance!!
This should do the trick:
echo '<p>'.$text.'</p>';
// Edit:
If you run into problems with special characters like öäü… you can use json_encode()
A lot of people like using json and ajax.
http://api.jquery.com/jQuery.getJSON/
http://php.net/manual/en/function.json-encode.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.
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.
I can't seem to get the PHP to echo out within a Javascript tag:
places.push(new google.maps.LatLng("<?php echo the_field('lat', 1878); ?>"));
What am I doing wrong?
Have you tried it without the quotes ?
places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));
PHP works when you execute the page, and it should work.
Please note that php does not execute when you run a JS function.
Please also make sure that you really have that the_field function.
I suspect you have your " quotes in the LatLng method arguments when there shouldn't be any.
Your php should output a string such as '50.123123123, 12.123144' (without the ' quotes). The LatLng method expects 2 values.
places.push(new google.maps.LatLng(<?php echo the_field('lat', 1878); ?>));
Try that.
If you're looking to populate a Google Map with markers as the result of a database query, you probably want to wrap it in a JSON web service. Something as simple as:
<?php
// file to query database and grab palces
// do database connection
$places = array();
$sql = "SELECT * FROM places";
$res = mysql_query($sql);
while ($row = mysql_fetch_object($res)) {
$places[] = $row;
}
header('Content-Type: application/json');
echo json_encode($places);
exit;
And then in your JavaScript file:
// get places
$.getJSON('getplaces.php', function(response) {
for (var i = 0; i < response.length; i++) {
place[] = response[i];
places.push(new google.maps.LatLng(place.lat, place.lng));
}
});
If i understand what you are trying to do (maybe some more explanation of your problem is required for this), then this might be your answer:
places.push(new google.maps.LatLng(<?php echo '"' . the_field('lat', 1878) . '"' ?>));
EDIT: removed the ;
I tried searching the related posts, and having a hard time figuring out how to fix my query - I'm pretty close, any help is much appreciated (new to Jquery).
I program in PHP, and trying to pull either the HREF value from a tag, or the text. Either will work.
I basically have my HTML code in a string, might contain multiple tags, and would like to load the text of the tags into either a PHP array or variable (right now just trying to ALERT the results, I can dump it later).
My PHP Code:
<?php
$info = '<li><strong>I want this text</strong>';
echo '<script type="text/javascript">';
echo '$("document").ready( function () {';
echo 'alert($("a", $("' . $info . '")).html());';
echo '});';
echo '</script>';
?>
The above doesn't alert anything. Putting in
echo 'alert("yes")';
does work, so I'm guessing there's something basic wrong with my syntax, but 4 hours later still unable to find it! :)
Thanks in advance.
You aren't Javascript-escaping the quotes in your string.
Your code creates Javascript that looks like
$("<li>...<a href="http..."...")
The quotes in the attribute end the Javascript string, creating a syntax error.
You need to call json_encode.
SLaks has the rest of your problem. But also, it's not:
$("document").ready();
It's:
$(document).ready();
The former is a selector for a tag named <document>.
This should work the way you want it to:
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready( function () {
alert($("a", $("<?php echo $info; ?>")).html());
});
</script>
You are not closing your li Tag
$info = '<li><strong>I want this text</strong>';
should be
$info = '<li><strong>I want this text</strong></li>';
You should escape info. It's breaking because you've got double quotes inside of double quotes:
$info = addslashes($info);
or
$info = json_encode($info);
or just
$info = str_replace('"', '\\"');
Try to save the HTML is a JS variable first, then use it. Also, heredocs are your friend.
<?php
$info = '<li><strong>I want this text</strong></li>';
echo <<<END
<script type="text/javascript">
$(function(){
var HTML = '$info';
alert($('a', $(HTML)).html());
});
</script>
END;
?>
echo '<script type="text/javascript">
$(document).ready( function () {
var info = \''.$info.'\';
$("a").html(info);
alert(info);
});
</script>';