Passing a PHP variable to a javascript on an ONCHANGE event - php

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)"

Related

How to use php fetched data into html using jquery post

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

Dynamic PHP variable into a Javascript function

I am trying to pass $post; a variable created in a mysql query, to javascript function showDiv.
Currently this doesnt work.
$post = $row['id'];
?>
<script type="text/javascript">
function showDiv() {
var note = "<?php echo $post ?>";
document.getElementById("<?php echo $post; ?>").style.display = "inline";
}
</script>
<?php
$addnote = '<input type="button" value="addnote" onclick="showDiv()"><div id="'.$postid.'" style="display:none;" class="'.$postid.'"> WELCOME</div>';
But if I change $post to have a html value e.g
$post = '11';
then this code works.
I am novice in javascript so please be gentle,
Any help is greatly appreciated.
Thank you.
If you are in a loop, I think JS doesn't like redeclare your function "showDiv()". Try this :
$post = $row['id'];
$addnote = '<input type="button" value="addnote" onclick="showDiv('.$post.')"><div id="'.$post.'" style="display:none;" class="'.$post.'"> WELCOME</div>';
And the javascript NOT in the loop :
<script type="text/javascript">
function showDiv(note) {
document.getElementById(note).style.display = "inline";
}
</script>
check your $row['id'] if it's returning something.
<?php echo $row['id']; ?>
or check your source code.
your code might look something like
<script type="text/javascript">
function showDiv() {
var note = "";
document.getElementById("").style.display = "inline";
}
</script>
Assuming that: $post = $row['id'] has a value. You want var note to have a value of a string. JS wraps strings in single or double quotes. so wrap <?php echo $post ?> in a string like this:
var note = "'"+<?php echo $post ?>"'";
This will prepend and append the quotes around the $post value so that JS can recognize it as a string.

Why this onclick alerts only one result from the while loop

there are currently three posts but when onclick alerts only one post.If I echo the posts insite the loop,then all three posts are shown,however if I alert them,then onlyone posts is show.plz help or suggest any alternative approach.
$sql=mysqli_query($db3,"SELECT * from user where id='$id'");
$num_rows=mysqli_num_rows($sql);
while($row=mysqli_fetch_array($sql)){
$posts=$row['posts'];
}
?>
<span onclick=u(<?php echo $posts; ?>)> <?php echo $num_rows ?> </span>
<script type="text/javascript">
function u(posts) {
alert(posts);
}
</script>
<?php
Update
Here is second query
After using the array approach ,If i use fancy box with $num rows to show all posts in the fancybox .I am again getting the only one result on the fancybox.Plz help
$posts[] = $row['posts'];
}
foreach ($posts as $af){
echo "<div id='#modelbox_id'>$af</div>";}
?>
<?php echo $num_rows; ?>
<?php
It is because you are assigning a single post row into the $posts variable, and then overwriting that variable with a new value on each iteration of the while loop.
Try something like this instead:
$posts = array();
while($row=mysqli_fetch_array($sql)){
$posts[] = $row['posts'];
}
Then you will need to print each value of the $posts array.
For example, you could implode the array into a string:
<span onclick=u(<?php echo implode(', ', $posts); ?>)> ...
Instead try something like this
while($row=mysqli_fetch_array($sql)){
$posts .= $row['posts'].",";
}
?>
<span onclick="u('<?php echo $posts; ?>')"> <?php echo $num_rows ?> </span>
<script type="text/javascript">
function u(posts) {
alert(posts);
}
</script>

SlickGrid error: Slick.Editors.Text is not a constructor

I'm trying to implement SlickGrid on the edit page of a CakePHP project, and when the page loads I get this error in the javascript console:
slick.grid.js:2173TypeError:'Slick.Editors.Text is not a constructor' (evaluating 'new (editor || getEditor(activeRow, activeCell))')
The data renders correctly in the grid on my page, but when I click on a cell to edit it, it just turns white and I can't type anything. If I click on another cell, that cell will turn white and the first one will stay white.
Here is my php/jQuery code:
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-1.7.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery.event.drag-2.0.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/lib/jquery-ui-1.8.16.custom.min.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.core.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.grid.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.editors.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.formatters.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/slick.dataview.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellselectionmodel.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangedecorator.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.cellrangeselector.js"); ?>
<?php echo $this->Html->script("/js/slickgrid/plugins/slick.rowselectionmodel.js"); ?>
<?php // Setup rows and cols array for grid
$columns = array();
foreach($route['Stop'] as $stop) {
$columns[] = array( "name" => $stop['name'],
"field" => $stop['id'],
"id" => $stop['id'],
"editor" => "Slick.Editors.Text");
}
$tripId = 1;
$thisTrip['id'] = $tripId;
foreach($route['RouteTrip'] as $routeTrip) {
if($routeTrip['trip_id'] != $tripId) {
$rows[] = $thisTrip;
$tripId = $routeTrip['trip_id'];
$thisTrip['id'] = $tripId;
}
else {
$thisTrip[$routeTrip['stop_id']] = $routeTrip['time'];
}
}
?>
<?php
echo $this->Html->scriptBlock('
var rows = '.json_encode($rows).';
var columns = '.json_encode($columns).';
var options = { rowHeight:21,
defaultColumnWidth:100,
editable:true,
enableAddRow:true,
enableCellNavigation:true,
asyncEditorLoading:false,
autoHeight:true,
autoEdit:true
};
slickgrid = new Slick.Grid($("#scheduleTable"), rows, columns, options);
slickgrid.setSelectionModel(new Slick.CellSelectionModel());
slickgrid.updateRowCount();
slickgrid.render();
');
?>
The $rows and $columns are correctly formatted, and each column has an "editor" attribute with "Slick.Editors.Text" as its value.
Help?
I have also got this error initially when i started working with slickgrid.
The error is because you have specified the editor as string and not as a class.
So, remove the double quotes in "editor" => "Slick.Editors.Text" and give as "editor" => Slick.Editors.Text
This solved the error for me. Hope this solution will solve yours too.
Include the slick.editors.js file.
Also, make sure that the editor is being specified as a class, not as a string (I'm not familiar with PHP, so it's not obvious to me from the source code, but I suspect that's the case).

Dynamically add options to a list through a hidden iframe

I want to dynamically add options to a list through a hidden iframe; I suspect my mistake is in the PHP below:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
because my code works perfectly with:
<?php echo 'var oInner = document.createTextNode("Newoption");'; ?>
I don't know why createtextnode doesn't want to take my PHP var... I thought it could be a same origin policy since the database is located on a server outside my website.
I don't know.
You'll find enclosed the complete code:
In my HTML I have:
//select or change a country will trigger the javascript part
<select name="countrym" id="countrym" onchange="validcountry();">
<option value"France">France</option>
</select>
//Empty region list
<select name="regionm" id="regionm">
</select>
//My Iframe
<iframe name="upload_iframe2" id="upload_iframe2" frameborder="0"></iframe>
In my Javascript I have:
//My function triggering the PHP through the Iframe
function validcountry() {
var countrym = document.getElementById('countrym');
var choixco = countrym.options[countrym.selectedIndex].value;
document.getElementById('upload_iframe2').src = 'region.php?choix='+choixco;
In my PHP region.php file, I have:
<?php
// Get my choice
$codepays = $_GET['choix'];
//Retrieve the regions corresponding to the country
$pdo_options[PDO::ATTR_ERRMODE] = PDO::ERRMODE_EXCEPTION;
$bdd = new PDO(XXX);
$req = $bdd->prepare('SELECT name FROM regions WHERE country = :country');
$req->execute(array('country' => $codepays));
$donnees = $req->fetch();
while($donnees)
{
// I checked the format of the data (no problem so far)
echo var_dump ($donnees['name']);
?>
//I add an option through Javascript
<script language="JavaScript" type="text/javascript">
var oOption = document.createElement("option");
//Here is my big issue:
<?php echo 'var oInner = document.createTextNode("'.$donnees["name"].'");'; ?>
oOption.value = "none";
oOption.appendChild(oInner);
var parDoc = window.parent.document;
var regionm = parDoc.getElementById("regionm");
regionm.appendChild(oOption);
</script>
<?php
$donnees = $req->fetch();
}
$req->closeCursor();
exit();
?>
Have you tried simply oOption.innerHTML = '<?php echo $donnees["name"] ?>'; ?
I am suspecting that the indexed element cannot be found. But is all cases, this below should work.
<?php echo 'var oInner = document.createTextNode("'. (isset($donnees["name"]) ? $donnees["name"] : '') .'");'; ?>
Found the solution: it was the php inserting \n so the solution is to do the following:
$desc= 'var oInner = document.createTextNode("'.$donnees["name"].'");';
$desc= str_replace("\n", "",$desc);
$desc= str_replace("\r", "",$desc);
Thanks everybody

Categories