How to use php fetched data into html using jquery post - php

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']);

Related

Stored HTML/PHP string in database won't evaluate when retrieved and echoed

This is the HTML/PHP before being stored in the database:<li><?= $item->item['Manufacturer']; ?> <span class="divider">|</span></li>
This is the HTML/PHP after being stored in the database:
<li><a href="&lt;?= dots('duo/'); ?&gt;">&lt;?= $item-&gt;item['Manufacturer']; ?&gt;</a> <span class="divider">|</span></li>
I assign this result to a variable:
$crumbles = $details['Crumbs'];
I echo the result like so:
<?php echo html_entity_decode($crumbles); ?>
But it returns this when I view source. It's not evaluating any of the PHP in the string.
<li><?= $item->item['Manufacturer']; ?> <span class="divider">|</span></li>
It shows in the browser as <?= $item->item['Manufacturer']; ?> |
How can I get it to evaluate the PHP as well as display the html correctly?
EDIT: Here is the code that handles the input into the DB. It serializes the form data (url, crumbs, meta info, etc) and adds it to an ajax queue.
$("form#seo_add").submit(function(e) {
console.log(this);
var data = $(this).serializeArray(),
$commitBtn = $(this).find("button"),
form_incomplete = false,
queueData = ['seo_add', data];
When fired, the queue controller runs $this->seo->add($seo_add, $user);
Which is modeled like this:
function add($data = null, $username = null) {
if (!is_array($data) || is_null($username)) die("Expecting new pageinfo");
//if a single item is being inserted, add it to a parent array so iteration works
if (!is_array($data[0]))
{
$data = array($data);
}
foreach ($data as $key => $page)
{
if (isset($page['section'])) unset($page['section']);
if (isset($page['action'])) unset($page['action']);
$add = $this->db->insert('pageinfo', $page);
$page = array_merge(array('id'=>$this->db->insert_id()), $page);
$last_queries[$key]['type'] = 'seo_add';
$last_queries[$key]['html'] = "New page: <b>" . $page['page'] . "</b>";
$last_queries[$key]['data'] = $page;
}
if ($this->db->_error_message())
$this->db_error('Unable to insert page');
return log_changes($last_queries, $username, $this->site);
}
Your PHP tags are being double encoded at your PHP tags &lt; so you can run html_entity_decode over it twice.
Even if your php tags were decoded they would never be interpreted by PHP since you're echoing them out straight away, the way around this is to run what your database returns through eval like so:
$crumbles = html_entity_decode(html_entity_decode($crumbles), ENT_QUOTES);
eval("?>{$crumbles}<?");
I suggest using placeholders.
$html = '<li>[item] <span class="divider">|</span></li>';
I suggest not saving the html encoded. This would do the trick for you I guess:
$html = str_replace(['href','item'],[dots('duo/'),$crumbles],$html);
Probably you've to encode the $crumbles or dots('duo/') if that is user input.

How can I call multiple PHP scripts with AJAX/JQuery?

I am new with AJAX and JQuery. I am trying to use it to call two PHP scripts. I found some examples online but just to call functions. I am just trying to call the scripts so it will load everything on my main PHP file that will then be display on the screen the results withouth refreshing the page.
Here is the fiddle example, it works if I put all my PHP scripts in one file : http://jsfiddle.net/vw4w3ay5/
thanks in advance, your help is very much appreciated!
main_php file (where I want to call my other PHP scripts):
<div id="map_size" align="center">
<script type="text/javascript">
/*I WANT TO CALL THE TWO SCRIPTS BEFORE EXECUTE THE FUNCTION BELOW*/
$(".desk_box").click( function() {
$(".station_info").hide(); // to hide all the others.
$("#station_info"+ $(this).attr('data') ).show();
});
</script>
display_desk.php (Script I want to call):
<?php
include 'db_conn.php';
//query to get X,Y coordinates from DB for the DESKS
$desk_coord_sql = "SELECT coordinate_id, x_coord, y_coord FROM coordinates";
$desk_coord_result = mysqli_query($conn,$desk_coord_sql);
//see if query is good
if($desk_coord_result === false) {
die(mysqli_error());
}
//didsplay Desk stations in the map
while($row = mysqli_fetch_assoc($desk_coord_result)){
//naming X,Y values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
//draw a box with a DIV at its X,Y coord
echo "<div class='desk_box' data='".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>id:".$id."</div>";
} //end while loop for desk_coord_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
display_stationinfo.php(second script I want to call):
<?php
include 'db_conn.php';
//query to show workstation/desks information from DB for the DESKS
$station_sql = "SELECT coordinate_id, x_coord, y_coord, section_name FROM coordinates";
$station_result = mysqli_query($conn,$station_sql);
//see if query is good
if($station_result === false) {
die(mysqli_error());
}
//Display workstations information in a hidden DIV that is toggled
while($row = mysqli_fetch_assoc($station_result)){
//naming values
$id = $row['coordinate_id'];
$x_pos = $row['x_coord'];
$y_pos = $row['y_coord'];
$sec_name = $row['section_name'];
//display DIV with the content inside
echo "<div class='station_info' id='station_info".$id."' style='position:absolute;left:".$x_pos."px;top:".$y_pos."px;'>Hello the id is:".$id."</br>Section:".$sec_name."</br></div>";
}//end while loop for station_result
mysqli_close($conn); // <-- DO I NEED TO INCLUDE IT HERE OR IN MY db_conn.php SINCE IM INCLUDING IT AT THE TOP?
?>
What about? :
<div id="map_size" align="center">
<?php
echo "<script>";
include "display_desk.php";
include "display_stationinfo.php";
echo "</script>";
?>
<script type="text/javascript">
/*I WANT TO CALL THE TWO SCRIPTS BEFORE EXECUTE THE FUNCTION BELOW*/
$(".desk_box").click( function() {
$(".station_info").hide(); // to hide all the others.
$("#station_info"+ $(this).attr('data') ).show();
});
</script>
To be sure add $(document).ready(function(){
});
/EDIT/
Hum you want to use Ajax . did you try with :
$.post("yourURL.php",function(html){
/*here what you want to do*/
/*return of your script in html*/
});

calling php using js

ok so I have this in my HTML code:
<script type="text/javascript" src="load2.php"> </script>
I saw somewhere you could call a php file like that and the javascript contained in it will be rendered on the page once echoed.
So in my PHP file i have this:
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[] = $row['DayNum']; }
$length = count($storeArray);
I connected to my database and stuff and pulled those records and stored them in an array. Now my problem is alerting them using js. This is what I have:
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
The test() function is being onloaded in my HTML page, but for nothing the values in the array won't alert. Any help please?
echo " function test() {
for(var i = 0; i<$length; i++){
alert($storeArray[i]);
}
}
";
This code is literally writing what you have written above. It's not completely clear, but I believe your intent is to loop over the contents of your database data, and alert that to the browser with alert() function.
You can achieve this in a couple of ways.
Write multiple alert statements
echo "function test() {"; //Outputting Javascript code.
for($i = 0; $i<$length; $i++){ //Back in PHP mode - notice how we aren't inside of a string.
$value = $storeArray[$i];
echo "alert($value)"; //Outputting Javascript code again.
}
echo "}"; //Outputting Javascript code to close your javascript "test()" function.
Write a Javascript array, then loop over it in Javascript
echo "function test() {";
echo " var storeArray = ['" . implode("','", $storeArray) . "'];";
echo " for (var i = 0; i < storeArray.length; i++) {";
echo " alert(storeArray[i]);";
echo " };";
echo "}";
Finally, you could use AJAX and JSON to load the data, rather than outputting a JS file from PHP. That is an entirely different topic, though, and you should search StackOverflow for more examples as there are numerous questions and answers involving it.
Unless your array contains only number, you probably have JS error. You should put your $storeArray[i] in quotes in the alert function so it considered as a string in js.
alert('$storeArray[i]');
Once printed out, the JS will look something like this
alert('foo');
alert('bar');
Whereas with your code, it would've printed it like this
alert(foo);
alert(bar);
in your php file include load2.php
header("Content-Type: text/javascript");
in the in the top. so your browser get what it wants.
$i=0;
$storeArray = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
$storeArray[$i] = $row['DayNum'];
$i++;
}
echo "var arr = Array();";
echo "function test() {";
foreach ($storeArray as $key=>$item) {
echo "arr[".$key."] = ".$item.";";
}
echo "}";
echo "alert(arr);";
actually you can comment out the two echos containing the <script></script> part when including the file as <script src="load2.php" type="text/javascript" ...

Passing a PHP variable to a javascript on an ONCHANGE event

I want to change the text of a label when i choose a new value in a dropdown list.
These are my php arrays:
$data = array(
'1'=>array('country'=>'Philippines','capital'=>'Manila'),
'2'=>array('country'=>'Finland','capital'=>'Helsinki'),
'3'=>array('country'=>'India','capital'=>'Delhi')
);
$countries = array(1=>'Philippines', 2=>'Finland', 3=>'India');
This is how it should be displayed in the page:
<div><?php echo form_label('Country: ', 'country'); ?></div>
<div><?php echo form_dropdown('country',$countries,'',
'onChange="javascript:displayCapitalCity(?????)"'); ?></div>
<div><?php echo form_label('Capital: ', 'capitalLabel'); ?></div>
<div id="capcity"><?php echo form_label('','capitalcity'); ?></div>
This is the javascript:
function displayCapitalCity(?????){
document.getElementById('capcity').innerHTML = '??????';
}
????? should be the capital city of chosen country. How will I pass the value of $data[index of chosen country]['capital']?
try this:
<div><?php echo form_dropdown('country',$countries,'',
'onChange="javascript:displayCapitalCity(this)"'); ?></div>
var jsdata = <?php echo json_encode($data); ?>;
function displayCapitalCity(_targ){
document.getElementById('capcity').innerHTML = jsdata[_targ.value]['capital'];
}
Best way (in my opinion) is to translate the PHP $data array into JSON, making it accessible on the client side (i.e. JavaScript).
<script type="text/javascript">
<?php printf('var countriesData = %s;', json_encode($data)) ?>
function displayCapitalCity(index) {
document.getElementById('capcity').innerHTML = countriesData[index].capital;
}
</script>
Just make sure you're passing for correct index corresponding with the $data array.
Assuming you are using CodeIgniter, the onChange should look like that:
onchange="javascript:displayCapitalCity(this.value)"

Write to javascript array within php loop

I have a php loop that is echoing out geolocation values. How can I get it to write those values to a javascript array, so I can then use them to plot points on an HTML5 canvas?
The php loop is as follows
<ul id = "geo-list">
<?php foreach($data as $phrase) { ?>
<li><?php
if ($phrase->geo != false) {
echo " | From (";
echo $phrase->geo->coordinates[0];
echo ",";
echo $phrase->geo->coordinates[1];
echo ")";
} else {
echo " | No Location Data";
}
?>
</li>
<?php } ?>
</ul>
Did you try
var myJavascriptData = <?= json_encode($php_data) ?>;
You might want to take advantage of the JSON library for PHP.
The cleanest way to pass data to a browser's javascript program is to put it into a "hidden" html table.
The html should look something like
echo "\n<TABLE style='display: none;' id='DATTAB' >" ;
get_rows();
while ($cf = next_row()) {
echo "\n <TR>";
echo "\n<TD>" . $cf['KEY'] . "</TD>";
echo "\n<TD>" . $cf['COL1'] . "</TD>";
echo "\n<TD>" . $cf['COL2'] . "</TD>";
echo " </TR>";
}
echo "\n</TABLE>";
This table is then easily accessable from your javascript:-
var dtab = document.getElementById("DATATAB");
var rows = dtab.getElementsByTagName("tr");
for (var r = 0; r < rows.length ; r++) {
row = rows[r];
item_key = row.cells[0].innerHTML;
item_col1 = row.cells[1].innerHTML;
item_col2 = row.cells[2].innerHTML;
// do your thing here ......
}
Alternatively you could look at using the AJAX libraries like prototype or dojo
which have the all javascript components for accessing data from a "REST" type service.
You then need to write a separate service which gets the XML or JSON required for your page.
My suggestion is to dump a script block to the output and set them in a variable there.
The array definition will have to actually be in the javascript code that gets output to the page.
e.g., you'll need an output of something like:
<script type="text/javascript">
var coords = new Array(2);
coords[0] = new Array(2);
coords[0][0] = 123.45;
coords[0][1] = 987.65;
coords[1] = new Array(2);
coords[1][0] = 234.56;
coords[1][1] = 876.54;
</script>
There are more efficient ways to create this array statically, but this is just an example.
A more efficient way (in terms of code) would be to build up a string that defined the literal array, then dump out a javascript definition. The output would be something like:
<script type="text/javascript">
var coords = [[123.45,987.65],[234.56,876.54]];
</script>
so in your loop within php, you'd build up a string which would ultimately contain var coords = [[123.45,987.65],[234.56,876.54]]. Outside your loop, you wrap it in the script blocks and output it to the page.

Categories