I want to push a php variable to javascript. The code is below but does not seem to work. Can anyone show me how to do this?
ticks.push(<?php echo json_encode($new); ?>);
Is this what you're looking for?
ticks.push(JSON.parse('<?= json_encode($new); ?>'));
Or broken down:
var json = '<?= json_encode($new); ?>';
var obj = JSON.parse(json);
ticks.push(obj)
also addressed in this issue:
Accessing an array in PHP from Javascript/jQuery
can you try this
var tricks = [
<?php
foreach ($new as $n) {
echo '"'.$n'", ';
}
?>
];
you can use websocket to do such like functionality; in it you can send the result back to the client from the php code when it is ready one good example on that is how stackoverflow notify you when there is new question, or when they notify you if the post is edited.
Related
I am attempting to create a JavaScript array from a MSSQL query results. Below is my syntax that I attempt to use, but the array is not created. How should this be set-up so that the JavaScript array is properly assigned?
<?php
$mssql = new mssql("localhost", "user", "password", "testdb");
$data=mssql_query($mssql,"SELECT * FROM test");
?>
<script>
var firstNames=[<?php
while($info=mssql_fetch_array($data))
echo $info['f_name'].',';
?>];
<?php
$data=mssql_query($mssql,"SELECT * FROM test");
?>
var lastNames=[<?php
while($info=myssql_fetch_array($data))
echo '"'.$info['l_name'].'",';
?>];
</script>
<?php
$mysqli->close();
?>
A good approach here would be to get the query (after correcting the deficiencies in the code as noted below your post, then casting the whole array to JSON using json_encode($data); and then echo $data in to your javascript.
This is not the only way to do it. I'm sure others will suggest other things.
Look at this page: https://www.w3schools.com/jquery/ajax_ajax.asp
I know, W3 Schools isn't the best, but it's okay.
You can do that with jQuery easy, just google a bit and you need php knowledge for creating an array out of a mysql query.
The approach used in this question is WRONG. As mentioned in comments, PHP is server side processing and JS is client side processing (browser). The 2 should not be mixed.
Seems like a trivial problem with an apparently easy solution. I have a PHP file which is loaded via a post. In this document I can retrieve the posted value as such:
$userid = $_POST["userid"];
Then in my Javascript in $(document).ready(function() I am trying to assign the post value to Javascript variable as such :
var jsvariable = <?php echo($_POST["userid"])?>;
Keep geeting either variable undefined in js error or syntax error, unexpected T_VARIABLE error inPHP.
Please advise how I can successful retrieve this value.
There are two approaches for this:
First if your js is present inside a php file then in that case.
var jsvariable = "<?php echo $_POST["userid"]; ?>";
And if your js is present in a .js file then in that case.
var jsvariable2 = "<?php echo $_POST["userid"]; ?>";
and below this line. Call the js file.
<script src="whatever.js" type="text/javascript">
And inside the js assign the above created variable to it:
var jsvariable = jsvariable2;
Hope it helps.
try
var jsvariable = <?php echo('\"'.$_POST["userid"].'\"')?>;
instead
var jsvariable = <?php echo($_POST["userid"])?>;
if userid="ehdrbs0318" in php,
in javascript
var jsvariable = ehdrbs0318;
you have to assign string like
var jsvariable = "ehdrbs0318";
You could use json_encode:
var jsvariable = <?php echo json_encode($_POST["userid"]) ?>;
This will add the necessary quotes if the PHP variable is a string, but will also respond well to non-string values.
As a side note: you can use the PHP short-cut notation to output values:
var jsvariable = <?= json_encode($_POST["userid"]) ?>;
PHP error
The error unexpected T_VARIABLE in PHP you (sometimes) get, is unrelated to the code you have provided: it is a simple syntax error, and it means the parser found a variable name at an unexpected place. Maybe you forgot to end the previous statement with a semicolon, or maybe you forgot a closing parenthesis or bracket....
I am using laravel 5.2 , I am using like below
var data = <?php json_encode($data['value']); ?>
when I am using JavaScript code below in the blade file, then its working fine, but when I am using the code as a separate file and trying to gulp that , then it is not working , my data is not loading
var data = "<?=json_encode($data['value']);?>"
or
var data = "<?php echo json_encode($data['value']);?>"
You are not echoing out the value, your var is null
Other mate already provided the correct solution specially #user1779617, now i am explaining with a basic example:
<?
// a simple array
$data['value'] = array(1=>'test');
$encodedData = json_encode($data['value']);
?>
<script type="text/javascript">
var data = <?=$encodedData?>;
console.log(data); // Object { 1="test"}
</script>
If you have posted original code than you have an error in your javascript, you miss the ending termination semicolon (;) plus you need to echo the result as other mentioned in answers.
UPDATE 1
if you are still facing the same issue than use JSON.parse in javascript
<script type="text/javascript">
var data = JSON.parse( ' <?=$encodedData?>');
console.log(data); // Object { 1="test"}
</script>
The idea here is to automatically load (or load at all) my index page with some products out of a MySQL database table.
Firstly, my PHP.
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
echo json_encode($itemsJSON);
}
This seems to be working great, and gives me two properly encoded JSON objects of my Item class.
{"name":"Slippers","quantity":"3","cost":"4.00"}
{"name":"Gloves","quantity":"5","cost":"9.00"}
My JavaScript looks like this(and many other similar variations)
$(document).ready(function () {
$.post( "productloader.php", function( data ) {
$( "#result" ).html( data );
});
});
I'm not sure why it is not working. I did not want to use $.getJSON() because there is no query string to work with, so I'd assume I would need $.post().
It seems like this is a pretty common issue, but I've not found a solution yet. Any help would be appreciated. Thank you.
You can't json_encode() each item separately. The data you're sending to the browser is not valid JSON, just many little chunks of valid JSON one after the other. Build an array inside your loop and then encode the whole thing. See also http://jsonlint.com/
<?php
header('Content-Type: application/json');
require_once 'classloader.php';
$db = new Database();
$items = $db->getRows('SELECT * FROM products');
foreach($items as $eachItem){
$itemsJSON[] = new Item($eachItem->product_name, $eachItem->product_quantity, $eachItem->product_cost);
}
echo json_encode($itemsJSON);
In your method of AJAX, you're outputting multiple JSON strings while the js side is expecting 1 string (data). Try removing your for loop to just:
echo json_encode($items);
You are creating JSON for each row, so you are getting separate JSON objects for each row in front end.
You should put all row in to and array and create the JSON object outside the loop, and echo the encoded JSON string.
<?php
$allitem = $db->getRows('SELECT * FROM products');
$itemArr=array();
foreach($allitem as $item){
array_push( $itemArr , new Item($item->product_name, $item->product_quantity, $item->product_cost) );
}
echo json_encode($itemArr);
?>
or
$allitem = $db->getRows('SELECT * FROM products');
echo json_encode($allitem );
Im trying to send a variable from a controller to a JavaScript, I have my controller, and I can send an array:
public function index()
{
$casa = new Casa(true);
$result = $casa->where(['show'=>true])->get();
return view('casa', array('casa' => $result));
}
If i go to my HTML and I make and echo:
<html>
<body>
<?php echo $casa ?>
</body>
</html>
I can show my array in the body, I was thinking about make an invisible element and get the array with document.getElementById().innerHTML, but I think this is not the best way.
Also, I think that I could make an Ajax petition sending a post and get the result, but I dont know if I can get my variable in a simpler way.
I tried to make and echo in Javascript and doesn´t work. some ideas?
Can I have 2 method post to get request in my controller? I already have one to get data from a form, and if I set the Ajax request I will have two post request. I would like have just one.
Jeffrey Way created a package for that. He also made a video explaining it in laracasts.com.
The package can be found here: https://github.com/laracasts/PHP-Vars-To-Js-Transformer
You can simply get PHP variable in JavaScript like this:
<script>
var casa = '<?php echo $casa ?>';
</script>
you can use alert to see the result in popup dialog too:
<script>
var casa = alert('<?php echo $casa ?>');
</script>