This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to generate .json file with PHP?
I want to use php to create a json like below. it will return a string json as a response from result sql query. How do I do?
{"Orders":[
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"},
{"DeliveryId":"DeliveryId","CustomerName":"CustomerName","PhoneNumber":"PhoneNumber","Address":"Address"}
]
}
my code
<?php
mysql_connect("mysql12.000webhost.com","a4602996_longvan","longvan2012");
mysql_select_db("a4602996_lv");
$id=$_POST[user];
$sql=mysql_query("select * from testlongvan where Status = 'PACKED'" );
$json = array();
if(mysql_num_rows($sql)){
while($row=mysql_fetch_row($sql)){
$json['Orders'][]=$row;
}
}
//while($row=mysql_fetch_assoc($sql))
//$output[]=$row;
print(json_encode($json));
mysql_close();
?>
But when use my code i recieve result, don't result i want:
{"Orders":[
["longvan","10/12/2012","Be34433jh","Long Van","115 Pham Viet Chanh, quan Binh Thanh","http://longvansolution.tk/image/sample.jpg","PACKED","0909056788"],
["takeshi","24/12/2012","BF6464633","Vn-zoom","16 nguyen cuu van, quan binh thanh","http://longvansolution.tk/image/hoadon3.jpg","PACKED","098897657"]
]}
Can you help me!
You may use json_encode() function to do that.
And your JSON format is invalid. Use : instead of =
// SERVER SIDE
<?php
//... create array
//....Obviously you would use your own SQL link and query
$animals = array();
$result = #mysqli_query('YOUR DB LINK', 'YOUR QUERY');
while ($row = mysqli_fetch_array($result, MYSQLI_BOTH)) {
array_push($animals, array(
'animal' => $row['animal'],
'sound' => $row['sound']
));
}
?>
// CLIENT SIDE
<html>
<script>
// RETURN FROM PHP PAGE ECHO VIA AJAX PERHAPS //
var animals = <?php echo json_encode($animals) ?>;
$.each(animals, function (i, elem) {
console.log(elem.animal + " makes a " + elem.sound);
});
</script>
</html>
Related
I am trying to create javascript variable from php, this is what i want to get.
<?PHP echo "var color_name=[<?PHP echo $color_name;?>]"; //var color_name=["Green","Pink"];
<?PHP echo "var style_name=[<?PHP echo $style_name;?>]"; //var style_name=["Basic","Classic"];
this is my predefined_attributes table
this is what i have tried,
<?php
$predifined_qry = "SELECT attribute_column_name
FROM predefined_attributes
WHERE category_id=$id";
$predifined_result = mysqli_query($predifined_qry);
$columnNames = Array();
while ($predifined_result_row = mysqli_fetch_assoc($predifined_result)) {
$columnNames[] = $predifined_result_row['attribute_column_name'];
}
now i can get the attribute_column_name in an array using a foreach loop, but i dont know how to get the attribute_column_value array in a variable like this $style_name, $color_name. please help.
First of all, if you only need 1 column, and the resource/data you get is not massive, you could just fetch all and extract the column
You could expose your php variables in js through JSON
<?php
$predifined_result = mysqli_query($predifined_qry);
$predifined_rows = mysqli_fetch_all($predifined_result, MYSQLI_ASSOC);
$columnNames = array_column($predifined_rows, 'attribute_column_name');
?>
<script>
var columnames = JSON.parse("<?= json_encode($columnNames); ?>");
</script>
So now if we add in the other field :
<?php
$predifined_result = mysqli_query($predifined_qry);
$predifined_rows = mysqli_fetch_all($predifined_result, MYSQLI_ASSOC);
$columnNames = array_column($predifined_rows, 'attribute_column_name');
$columnValues = array_column($predifined_rows, 'attribute_column_value');
// array_combines uses the first array as the key and the second as the value
$columns = array_combine($columnNames, $columnValues);
?>
<script>
var columns = JSON.parse("<?= json_encode($columns); ?>");
</script>
Edit
as in the comments, a key can only appear once in a hashtable/array
so we need to generate an array of values per key
<?php
$predifined_qry = "SELECT attribute_column_name, attribute_column_value
FROM predefined_attributes
WHERE category_id=$id";
$predifined_result = mysqli_query($predifined_qry);
$columns = [];
while($row = mysqli_fetch_assoc($predifined_result)) {
if(!array_key_exists($row['attribute_column_name'], $columns)) {
$columns[$row['attribute_column_name']] = [];
}
$columns[$row['attribute_column_name']][] = $row['attribute_column_value'];
}
?>
<script>
var columns = JSON.parse("<?= json_encode($columns); ?>");
</script>
1st : You need to select attribute_column_value column too
SELECT attribute_column_name,attribute_column_value FROM predefined_attributes where category_id=$id
2nd : You need push both column value in two different array like this
while ( $predifined_result_row = mysqli_fetch_assoc($predifined_result) ) {
$color_name[] = $predifined_result_row['attribute_column_name'];
$style_name[] = $predifined_result_row['attribute_column_value'];
}
3rd : simple apply json_enocde and echo like this
<script>
var color_name=<?php echo json_encode($color_name); ?>;
var style_name=<?php echo json_encode($style_name); ?>;
</script>
$columnValues[] = $predifined_result_row['attribute_column_value'];
You can paste this code into your while loop
And dont't forget to get the need field form database:
$predifined_qry="SELECT attribute_column_name,attribute_column_value FROM predefined_attributes where category_id=$id";
Hi i have a function in jquery and using $.Post to send data on a php file where my query is working fine and sending data back
js
function send_agenda_data(cidade_data){
var data = {'cidade_data':cidade_data};
$.post('includes/agenda_data.php',data,function(info){
});
}
This function works fine and when i alert the data coming back that also works fine
here is php
<?php
include_once("connection.php");
$cidade_data = $_POST['cidade_data'];
if (isset($cidade_data)) {
$sql = mysql_query("select * from agenda where cidade = '$cidade_data'", $con) or die(mysql_error());
if (mysql_num_rows($sql) > 0) {
while ($data = mysql_fetch_object($sql))
{
$date = $data->data;
$cidade = htmlentities($data->cidade);
$estado = htmlentities($data->estado);
$local = htmlentities($data->local);
$endereco = htmlentities($data->endereco);
$site_local = htmlentities($data->site_local);
$site_ingresso = htmlentities($data->site_ingresso);
$endereco = htmlentities($data->endereco);
}
}
else{
echo "No Data";
}
}
?>
this works fine if i use directly using php and echo the variables in tags now
$.post('includes/agenda_data.php',data,function(info){
//need data here
});
i want to know how i can get the php returned data in js here and how i assign that data into tags. also want to know there is while loop in php is here will be also loop to populate all rows ?
if i use direct php in my webpage then i can use like this in while loop
<div><?php echo $date; ?></div>
<div><?php echo $cidade; ?></div>
<div><?php echo $estado; ?></div>
<div><?php echo $local; ?></div>
.
.
.
how can i get in $.Post case
Your loop is somewhat incorrect. You're simply fetching each row's data, and then overwriting the previous row's data in all those variables. You should be building an array of results, which you can then send over to the client-side JS code. e.g. something like
$data
while($row = mysql_fetch_assoc($result)) {
$data[] = $row;
}
echo json_encode($data);
On the client side, you'll receive an array of objects you can iterate over:
$.post('includes/agenda_data.php',data,function(data){
$.each(data, function(idx, row) {
$('#date').innerHTML = row['date'];
...
});
});
exactly what you do in that JS loop is up to you.
As well, note that your PHP code is vulnerable to SQL injection attacks.
$.post is an AJAX call, thus you need to echo the result in PHP, to make sure you can use the results.
Try using
echo json_encode($your_data)
And to use the data in client side (browser), you can use
http://api.jquery.com/jQuery.parseJSON/
That parseJSON is used so you can use the data easier.
Why not use jQuery to fill the contents of the div by assigning a class as in this example:
<div class="date"><?php echo $date; ?></ div>
<div class="cidade"><?php echo $cidade; ?></ div>
<div class="estado"><?php echo $estado; ?></ div>
<div class="local"><?php echo $local; ?></ div>
and with jQuery, the success of $.post retrieve the information returned and integrate like this.
$('.date').html(info[0]['date']);
this is how am using the ajax
$.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){
$this.find(".report").html(data);
and this is my PHP code from where data is coming
<?php
$countresult=0;
$questionid=$_GET['qid'];
$answer=$_GET['clickedvalue'];
$dbconnect=mysqli_connect('localhost','root','','quiz')or die("Error Connecting to database");
$query="select answer from question_answer where id=$questionid";
$result=mysqli_query($dbconnect,$query);
while($rows=mysqli_fetch_array($result))
{
$dbanswer=$rows['answer'];
}
if($dbanswer==$answer)
{
echo "Correct";
$countresult=$countresult+1;
}
else{
echo "Incorrect";
$countresult=$countresult-1;
}
?>
Now previously i was just checking the result is correct or not and displaying tha result but now i want the PHP page to return even the variable that store the counts that is stored in $countresult. I know I have to use json but how to use it in PHP page ,pass the value and get access to that value from another page ,
In your php:
$data = array('countresult' => $countresult);
$str = json_encode($data);
echo $str;
In your js:
$.get('checkanswer.php',{'clickedvalue':clickedvalue,'qid':qid},function(data){
alert(data['countresult']);
}, "json");
Document about jQuery.get()
Use json_encode in php
<?php
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5);
echo json_encode($arr);
?>
Put messages in an array normally:
$server_response['error'] = "something";
$server_response['Success'] = "some other thing";
$sever_response['vars'] = "blah blah";
echo json_encode($server_response);
Then from js if your response variable is ServerResponse, you can access as
ServerResponse.error or
ServerResponse.Success or
ServerResponse.vars
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
php in javascript?
I need to check an if condition inside the inner html property of javascript. And so for that I need to use php inside it. So is it possible. I tried the following and it doesn't seem to work.
document.getElementById().innerHTML =
"<?php if ($number == 1) { echo $ex; } else { echo $ey; } ?>";
So please help me out with this problem.
Your PHP is executed at the server. Once the page has been fetched, inserting PHP code into it at the client end via JavaScript, will not cause it to be executed.
You should store $number, $ex, $ey in JavaScript variables and perform the same comparison in JavaScript.
Firstly,
<script type="text/javascript">
var number = <? echo $number ?>
var ex = <? echo $ex ?>
var ey = <? echo $ey ?>
</script>
The above sets the values of JS variables.
Afterwards, you can call:
if (number == 1) { document.getElementById().innerHTML = ex; }
Try this
<?php
if ($number == 1){ ?>
document.getElementById().innerHTML = $ex;
<?php }
else
{ ?>
document.getElementById().innerHTML = $ey;
<?php } ?>
here is the code
<php?
$id1 =1;
$id2 = "module 1 loaded";
echo "$var1=$id1","$var2=$id2";
?>
i know this is not correct way how can i pass these two varables to flash
<?php
echo http_build_query( array(
'var1' => 1
,'var2' => 'module 1 loaded'
));
Paul Dixon's code snip is what you need on the PHP side. Here's the flash part:
myVars = new LoadVars();
myVars.load("http://localhost/foo.php");
myVars.onLoad = function (success) {
if (success) {
for( var attr in this ) {
trace (" key " + attr + " = " + this[attr]);
}
} else {
trace ("LoadVars Error");
}
}
Note, you will want to replace the loop logic with whatever your application requires.
If you want to create a script which outputs data which can be loaded with LoadVariables or LoadVars you need something like this
//set up your values
$vars=array();
$vars['foo']='bar';
$vars['xyz']='123';
//output
header ("Content-Type: application/x-www-urlformencoded");
$sep="";
foreach($vars as $name=>$val)
{
echo $sep.$name."=".urlencode($val);
$sep="&";
}
If your version of PHP supports it, http_build_query makes this even easier:
$vars=array();
$vars['foo']='bar';
$vars['xyz']='123';
header ("Content-Type: application/x-www-urlformencoded");
echo http_build_query($vars);
Shouldn't it just be in the form of a query string:
echo $var1.'='.$id1.'&'.$var2.'='.$id2;
Make sure the keys and values are urlencoded.
Flash Code:
btn.onPress = function(){
testLoadVars = new LoadVars();
testLoadVars.onLoad = function(success){
if(success){
trace(testLoadVars.var1);
trace(testLoadVars.var2);
}
else
trace("error");
}
testLoadVars.sendAndLoad("http://localhost/filename.php?uniqueID=" + getTimer(),testLoadVars,"POST");
}
That's all.. Any Problem faced??
PHP Code:
<php?
$id1 =1;
$id2 = "module 1 loaded";
print "&var1=$id1";
print "&var2=$id2";
?>
I am sure this will work...