I have a php array called $user.
At the minute I am getting the variables across to javascript by manually adding them like so.
var username = ' . $user['username'] . ';
And so on is there a way I can make php echo a javascript array that I can access?
You're looking for json_encode
PHP:
$json_user = json_encode($user);
JavaScript:
var user = JSON.parse('<?php echo $json_user; ?>');
That's untested code but the idea behind it is sound
Have you tried json_encode ?
<?php echo json_encode ( $array ); ?>
See the documentation here.
Related
I was trying to generate a Javascript varialbe using php. I am getting the desired result on the source page but it looks like that result is not being processed into the array. Is there any way of doing it using javascript? Here, I'm generating URLs for images that need to be displayed on my website carousel and though a for loop would save me the time of entering every url. The images are also number serially. Since I'm not well versed in javascript can you suggest me a javascript alternative?
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>
You can do it using javascript only. No reason for using PHP here.
var leftrightslide = new Array()
var finalslide = ''; // this line is not really relevant to the question
for (var i = 0; i < 34; i++){
var j = i + 1;
leftrightslide[i] = '<img src="../images/'+ j +'.jpg" border="0">';
}
echo "leftrightslide[".$i."]='<img src=\"../images/".$j.".jpg\" border=0>';";
Here's a snippet of code that I use to move data from PHP To JS
if (isset($javascriptData)) {
echo "<script>";
foreach(array_keys($javascriptData) as $jsData) {
echo "var " . $jsData . " = " . json_encode($javascriptData[$jsData]) . ";\n";
}
echo "</script>";
}
I pass in $javascriptData to my view which is an array with the structure array('JS_VAR_NAME' => 'JS_VALUE')
You can then use those variables in any scripts you've added below that
Since your example code contains no script tags, or other HTML elements for that matter, one might assume that this PHP snippet is intended to generate some JavaScript source "file" external to the page in which it is being used.
If that is the case, consider that the following additional line may just fix it:
<?php header( 'Content-Type: text/javascript' ); ?>
var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
$j=$i+1;
echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>
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.
$allVal = array(array(123, 0), array(345, 1), array(456, 2));
Code at above is an PHP array, currently I would like to pass this array to javascript and the output in Javascript should look like the following:
<script type="text/javascript">
var d = [[123, 0], [345, 1], [456, 2]];
</script>
BTW: PHP code and Js code in the same page.
Is there anyone can help me? Thanks in advance!
json_encode should be able to help you
<?php
$allVal = array(array(123, 0), array(345, 1), array(456, 2));
?>
<script type="text/javascript">
<?php echo 'var d = ' . json_encode($allVal) . ';'; ?>
</script>
You can use php's json_encode method to convert an array into a javascript oject prior to sending it back to the client side. See
http://php.net/manual/en/function.json-encode.php
--Inline
Use a line similar to
<?php echo "var = ". json_encode($myArray); ?>
--Asynchronous
A line similar to
<?php echo json_encode($myArray); ?>
One thing you will have to take into consideration is that you'll need to pass a header to the server stating that you expect the response format to be json.
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>';