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.
Related
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 );
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.
I am very new to PHP and JavaScript. I am currently using echo in PHP to run some JavaScript on the page. I need to make a new javascript array and a new variable that are equal to an existing PHP array and variable, so I did this:
var messages = <?php print_r($messages)?>
var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>
However, there is a problem caused by my using echo to echo script containing echo. How would I solve this. I would like to echo it because it is only about 4 lines long, so is there an alternative.
Thank you in advance.
Edit: This is the whole JavaScript. It is for a messaging system. $messages is declared from another PHP function, and the basic aim of this code is to 'refresh' the echo every few seconds so that the user can see new messages without having to refresh their page:
echo '<script type="text/javascript">;';
echo 'var messages = <?php print_r($messages)?';
echo 'var list = <?php echo $message['user_name'].': '.$message['text'].' ('.date('d/m/Y H:i:s', $message['date']).')'.'<hr />'; ?>';
echo 'setInterval(function(){console.log("hello")},3000);';
echo '</script>';
Not getting what you want,but if you want to use php array in javascript than make it javascript array
<script>
<?php $test_arr = array('apple','banana','mango');?>
var js_array = <?php echo json_encode($test_arr);?>;
</script>
output
<script>
var js_array = ["apple","banana","mango"];
</script>
Your Javascript will execute on the client, not on the server. This means that foo is not evaluated on the server side and therefore its value can't be written to a file on the server.
The best way to think about this process is as if you're generating a text file dynamically. The text you're generating only becomes executable code once the browser interprets it. Only what you place between <?php tags is evaluated on the server.
By the way, making a habit of embedding random pieces of PHP logic in HTML or Javascript can lead to seriously convoluted code. I speak from painful experience.
I am using a javascript slide show on my index page. Instead of the array being static, I want to build the array with PHP and add it with something like and include statement. Since the array is inside the javascript I am unsure how best to do this. Here is a sample of the array:
var fadeimages=new Array()
fadeimages[0]=["pics/fade_pic_1.jpg", "", ""]
fadeimages[1]=["pics/fade_pic_2.jpg", "", ""]
fadeimages[2]=["pics/fade_pic_3.jpg", "", ""]
And here is the PHP file that builds the array. It works great. I just don't know how to place it in the javascript code:
<?php // Build fadepic array for index page
$x=0;
foreach (glob("pics/*.*") as $filename) {
$filename = substr($filename, 20); //gets just the file name
echo "fadeimages[".$x."]=[\"pics/".$filename."\", \"\", \"\"]<br>";
$x++;
} ?>
Thank you in advance for any help you can give me!
You can use json_encode() for this.
<?php
//buildfadepic.php
$result = array();
foreach (glob("pics/*.*") as $filename) {
$result[] = array("pics/".$filename, "", "");
}
print json_encode($result);
This will give you valid JSON (and hence valid JavaScript). If you want to mix JavaScript and PHP, you should be able to do it like this now
var fadeimages = <?php include "buidfadepic.php"; ?>;
Since buidfadepic.php will give you a result like this
[ ["pics/foo.jpg", "", ""], ["pics/bar.png", "", ""], ...]
Or if you have both in the same file, simply print/echo instead of include as suggested in the comments.
The right way, as the comments said would be using json_encode.
For example:
Server
<?php
$files = array('file1.jpg', 'file2.jpg', 'file3.jpg');
$view->assing_var('files', $files); // if you're separating the view from the php, else just do return for including
View (client):
<script type="text/javascript">
var images = <?=json_encode($files)?>;
</script>
I agree with other posters that JSON would be a nice clean way to do this. But you don't necessarily have to, you can also include the array straight away:
<script type="text/javascript">
var fadeimages=new Array();
<?php
echo "fadeimages[0] = ...;"; // Include code to create array
?>
</script>
Just to clarify (based on the comments we seem to have a bit of misunderstanding): you can put PHP code inside <script> tags. After all, the PHP code is run server-side and the client that runs the JavaScript will also see the resulting output. So as long as your PHP script does not produce syntax errors in the JavaScript you should be OK.
An alternative approach, if the script becomes very large, is to include your PHP script as an external JavaScript:
<script type="text/javascript" src="list_fade_images.php"></script>
Can you please show me ,how to pass the java script array to the
php . is it this way.
$.post("php_mysql_write.php", {datageo: shapes});
and after ur php script .. but php say's
Warning: mysqli::prepare()
[mysqli.prepare]: Couldn't fetch mysqli in
C:\xampp\htdocs\blitz-gmap-editor-master\php_mysql_write.php on line
25
Fatal error: Call to a member function bind_param() on a non-object
in C:\xampp\htdocs\blitz-gmap-editor-master\php_mysql_write.php on
line 26 please.
i used ur code
<?php $mysqli = new mysqli(/*args*/); $stmt =
$mysqli->prepare('INSERT INTO `tableName`(`columnName`) VALUES
(?)'); $stmt->bind_param('s', $json);
foreach($_POST['shapes'] as $value){ $json = json_encode($value);
$stmt->execute(); } ?>
Dr.molle's answer on
How to save a Google maps overlay shape in the database?
You should:
JSON.stringify(array);
to encode your JavaScript array, then use:
$array=json_decode($_POST['jsondata']);
in your PHP script to get the array.
Good luck!