How to insert a php array with innerHTML in javascript - javascript

I would like to be able to insert html code from javascript, which inserts php code that contains an array. What I do is get in the variable $ teams an array of teams. And then I go through the array with a foreach to set the values ​​in the select options
I have done the following but it does not work.
document.getElementById('selectTeam').innerHTML = '<select class="form-control"><?php $teams = ControllerTeam::ctrTeam(); foreach ($teams as $key => $value) { echo '<option value="'.$value["id"].'">'.$value["name"].'</option>';}?></select>';

First problem is that, probably, the content is loaded after the JS so the selector returns null hence the error in the OP code.
Cannot set property 'innerHTML' of null
That means, you should only execute the JS code on window.load or any other similar event that ensures the fact that the HTML is loaded before trying to execute.
Now, for the other issue in the comments, if you rewrite the PHP code like this :
<?php
$teams = ControllerTeam::ctrTeam();
$options_html = '';
foreach ($teams as $key => $value) {
$options_html .= '<option value="' . $value["id"] . '">' . $value["name"] . '</option>';
}?>
And in the JS - make sure it loads on window.load or similar -
document.getElementById('selectTeam').innerHTML =
'<select class="form-control"><?php echo $options_html ?></select>';
This makes the code more readable and helps you debug easier.

There is a typo in your code. Please change it to:
document.getElementById('selectTeam').innerHTML = '<select class="form-control"><?php
$teams = ControllerTeam::ctrTeam();
foreach ($teams as $key => $value) {
echo '<option value="' . $value["id"] . '">' . $value["name"] . '</option>';
}
?></select>';

Related

Adding a javascript function and removing it from the HTML instantly

I'm trying to add a script element to the HTML from the PHP code and instantly remove it so it won't be visible in the HTML. The script only contains things to execute at the same moment and not functions. Generally, I'm trying to replicate ASP.NETs runat property, so I'll be able to set values of elements (inputs for now) right from the PHP code.
This is what I tried so far (which I found in a different question, with some changes of mine) and it adds the script properly, but won't remove it.
function JSSetValue($id, $value) // Input 'value' only
{
echo '<script>
var input = document.getElementById("' . $id . '");
input.value = "' . $value . '"
</script>';
$html = <<<HTML
...
HTML;
$dom = new DOMDocument();
$dom->loadHTML($html);
$script = $dom->getElementsByTagName('script');
foreach($script as $item)
{
$item->parentNode->removeChild($item);
break;
}
$html = $dom->saveHTML();
}
Thanks for everyone who were trying to help. Anyway, I found a solution to my question, which is this:
function JSSetValue($id, $value) // Input 'value' only
{
echo '<script id="phpjs">
var input = document.getElementById("' . $id . '");
input.value = "' . $value . '";
document.getElementById("phpjs").remove();
</script>';
}
It adds the script and removes it, so it won't be visible when inspecting elements anymore.

Make first option value null in select menu coming from MySQL database

I am dumping some results from the database directly into tag in the html, how I can make the first option value to be null, and after that the database results to be sorted? This way I will have this drop down menu an option to not choose anything from it.
this is my code here:
<?php
$select = new Users;
$stmt = $select->selecttema();
while( $row = $stmt->fetch()){
echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
}
?>
Just
echo '<option value="">Select a topic</option>'
before the while loop.
actually Juan Pablo had answered the question. i just add something on his answer.
if you add selected in your option it will be first option and you do not need to add data in value
echo '<option selected value="">Select a topic</option>';
To make an empty option:
<select>
<option value="">Select</option>
<?php
$select = new Users;
$stmt = $select->selecttema();
while( $row = $stmt->fetch()){
echo '<option value="' . $row['id'] . '">' . $row['topic'] . '</option>';
}
?>
</option>
You're not clear about what this Users object is or how you're fetching data so I'll just assume you're using a mySQL database, in which case you can use ORDER BY:
SELECT * FROM `users` WHERE 1 ORDER BY id DESC
For instance the above statement will select all users in the users database and order them by their id in descending order.
To sort the <select> options in JS, take a look at Sort Select Options by Value Attribute Using jQuery and Javascript to sort contents of select element

Assign value to textbox onchange of php while select

I'm slowly understanding PHP but this one has me stumped.
I am populating a 'select' HTML element with data from PHP using.....
while($row = mysql_fetch_array($result))
All is working fine and I understand why.
I just wanted to fill in other textboxes on the page when a selection is made.
There is a very helpful fiddle at http://jsfiddle.net/TPE9r/5/ but it does not use PHP.
This is part of my code...
while($row = mysql_fetch_array($result)){
echo '<option value=" ',$row['ContactID'],' ">', $row['ContactName'],' -- ', $row['BusinessName'],
'</option>';}
Sorry about the formatting - new on here also...
I have used similar JavaScript to the fiddle but I can't display $row['ContactName'] or $row['BusinessName'] in a textbox. I can do this with a normal HTML select but not when the rows are in a 'while loop'
because you try to do something, what should be done on other way.
In the while loop, you are putting out the options html tags.
To do this, i think, the best practice, if you build an array from your results, so you can use that later, if you want to do it in PHP.
The code is not tested.
echo '<select name="whatever">';
$results = array();
while($row = mysql_fetch_array($result)){
//Storing all the rows in an array
$results[] = $row;
}
for($i=0;$i < count($results); $i++) {
echo '<option value=" ',$results[$i]['ContactID'],' ">', $results[$i]['ContactName'],' -- ', $results[$i]['BusinessName']."</option>";
}
echo '</select>';
//And now you can youse your $resuls array more then one time.
$key = 0;
//The key is based on, wich data you need.
//Maybe you want to set it in the loop with an if condition
echo '<input type="text" value="'.$results[$key]['ContactName'],' -- ', $results[$key]['BusinessName'].'" />';
Trying to post my own answer - having trouble with formatting on here.
The loop should be
for($i=0;$i < count($results); $i++) {
echo ''. $results[$i]['ContactName'].
"";
OOPS!!!!! Done it again - the loop code is truncated - don't know why
Finally, solved this one - maybe not the best way but it may help others.
I used : $(this).find(':selected').data('id') .... in the onchange
and used data-attributes in the loop
for($i=0;$i < count($results); $i++) {
echo '<option data-id="'.$results[$i]['ContactID'],' " data-bn="'.$results[$i]['BusinessName'],' " >'. $results[$i]['ContactName'].
"</option>";
and 3 textboxes whose id is bb, cc, dd ....
price2= this.value;
price1 = $(this).find(':selected').data('id')
price3 = $(this).find(':selected').data('bn')
$('#bb').val(price1);
$('#cc').val(price2);
$('#dd').val(price3);
Just a bit tricky with single and double quotes in the loop but 'Hey that's what we do!'
Use this instead. You do not want the value of the option but the text.
$('#job_title').live('change', function(){
var b = $(this).text();
$('#catch_value').val(b);
return false;
});

How to retrieve data from .php and display in <select> within Cordova hybrid app?

I am writing a hybrid app using Visual Studio with Cordova exetnstion and trying to pull data from www.a.com/b.php
My b.php code is:
<?php
// Connect to database server
mysql_connect("http://www.yo.com", "ya", "ye") or die (mysql_error());
// Select database
mysql_select_db("oh") or die(mysql_error());
// SQL query
$strSQL = "SELECT * FROM Properties ORDER BY number DESC";
// Execute the query (the recordset $rs contains the result)
$rs = mysql_query($strSQL);
// Loop the recordset $rs
// Each row will be made into an array ($row) using mysql_fetch_array
echo '<select name="Address" id="address_search" style="width:282px; display:block;" required>';
while($row = mysql_fetch_array($rs))
{
// Write the value of the full address including unit code, address, city, state, zipcode (which is now in the array $row)
echo '<option value="'. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .'">'
. $row['number'] . ", " . $row['address'] . ", " . $row['city'] . ", " . $row['state'] . ", " . $row['zipcode'] .
'</option>';
}
echo '</select>';
// Close the database connection
mysql_close();?>
I already add select tag form directly in php code, but I don't know how to display the whole select box (with options being retrieved data) in .html.
Any help or tutorial? Thanks.
I have solved this issue like this:
First, in the server side-code (php in this case), in "file.php", I have an array with the database elements and I do the following:
$arrayElements = json_encode($arrayElements );
echo $_GET['jsoncallback'] . '(' . $arrayElements . ');';
After that, in the app js code, I use jQuery method $.getJSON() for getting the php array we prepare before. When the function get the server answer, then execute the code inside. Note that the variable "respuestaServer" is the array you have sent from php file, so you can go throw it with a loop and taking its values to your select (if you need to pass variables to your php file and receive them via GET just add the js variables inside the {}, in this example I send the variable datosUsuario and in php I receive it $_GET['usuario']).
var archivoValidacion = "http://example.com/file.php?jsoncallback=?";
var select = document.getElementById("idSelect");
$.getJSON( archivoValidacion, { usuario:datosUsuario ,password:datosPassword})
.done(function(respuestaServer) {
for(var i = 0; i < respuestaServer.length;i++){
var option = document.createElement("option");
var textNode = document.createTextNode(respuestaServer[i]);
option.appendChild(textNode);
select.appendChild(option);
}
})
I hope this can help you. If you have some questions just tweet me #ulisesveraes ;)
it is not clear how you call this code
I suppose you do this with jQuery ajax function
so your code will like something this
$('box-selector').load('b.php');

Call to undefined function get_field_id() in wordpress

Fatal error: Call to undefined function get_field_id() in E:\wamp\www\customfield\wp-content\plugins\custom-widget2\update.php on line 6.
i am using ajax to create second dropdown. my ajax page name is update.php but in response give me this error Call to undefined function get_field_id().
i making a plugin for widgit
echo $ret='<select id="'.get_field_id('test2').';" name="">';
$categories= get_categories();
$categoryid="";
$categoryid=5;
$taxonomy_names = get_object_taxonomies($status);
$taxonomy_name =$taxonomy_names[0];
$tax_terms = get_terms($taxonomy_name);
foreach ($tax_terms as $tax_term):
option = '<option value="' .$tax_term->name . '" ';
if ($cat->cat_ID == $categoryid) :
$option .= ' selected = "selected" ';
endif;
$option .= '">';
$option .= $tax_term->name;
$option .= '</option>';
$ret.=$option;
echo $option;
endforeach;
$ret.="</select>'";
update.php
please help me......
That function is out of scope.
To fix add
require('/the/path/to/your/wp-blog-header.php');
at the top of your file

Categories

Resources