I did many HTML dropdown (which generate select tags etc) with PHP scripts for different HTML files. Previously, I had as many dropdown scripts as there are HTML files. But now, I would like to have one script for all HTML files. For this, I need to have a variable 'id' attribut of the select tag which depend of the parameter of the url of each HTML page. I try to affect the parameter of the url to the 'id' attribut but without results.
Here is the url of one of the web page with a parameter 'name'.
http://127.0.0.1/projetwebtest/projetweb/indexSuperClass.php?name=superClass
And here is the code of the PHP script where I try to affect the url parameter value to the 'id' attribut.
One way :
$opt .= "<select class = 'custom-dropdown__select custom-dropdown__select--emerald' id = '<?php echo $_GET['name']; ?>' onchange = 'change();'>";
Another way :
$opt .= "<select class = 'custom-dropdown__select custom-dropdown__select--emerald' id = '$_GET['name'];' onchange = 'change();'>";
When I try to print with a 'echo' the url parameter $_GET['name'] it works but it doesn't in this case.
How can I affect the url paramter to the 'id' attribut ?
Thanks.
Your string is comprised of various uses of " and ' which is causing it to fail. Here's a working example. You can copy and paste it here to test it online.
$_GET['name'] = 'SELECT_TEST_ID';
$opt = '<select class="custom-dropdown__select custom-dropdown__select--emerald" id="' . $_GET['name'] . '" onchange="change();">';
echo $opt;
Sidenote: When you're creating HTML strings like these, and are not using a template engine, try using 'HTML String' instead of "HTML String", letting you avoid quote hell for HTML attributes.
Related
I'm working with Selectize.js currently and am stuck on a problem relating to HTML entities not displaying correctly in Selectize fields, and therefore failing checks after submission. We use PHP on the backend and run every Selectize option through htmlspecialchars($option);. We then export the PHP array to a JSON array in preparation for adding it to the Selectize script/field.
//Array of options
$options = getOptions();
$optionsArray = array();
foreach($options as $item) {
$optionsArray[] = array('text' => htmlspecialchars($item), 'value' => htmlspecialchars($item));
}
//Create html script to run selectize initialization
$htmlcode = "<script>";
...
$htmlcode .= "var optionList = " . json_encode($"optionsArray") . ";";
$htmlcode .= "$('#selector').selectize({ options: optionList });";
...
$htmlcode .= "</script>";
The point here is to protect against malicious entries by encoding. This typically wouldn't be a problem, as browsers will detect the entities and convert them automatically (ie. will detect & and display as &. However, that is NOT happening inside the selectize. As you can see in the image below, outputting an option with an ampersand displays correctly on the page, but it doesn't display accurately in the Selectize field.
Example:
The problem then becomes larger, as we are comparing the selected item against the database after submission, to ensure that the selected entry actually exists. If the entry testOption&stuff actually exists, the form submission will check testOption&stuff against it, and will obviously fail the check.
//For simplicity, checking against static option
var $selectedOption = $_POST["options"];
if ($selectedOption == "testOption&stuff") {
//Do success
} else {
//Do failure
}
How can I resolve this and make it so that the Selectize field will store and display the correct entry (ie. &)?
Thanks!
I'm working on a code like this:
<?php
$id=$_POST['id'];
$url_tag = $_POST['url_tag'];
$url_back = 'https://www.page.example.com/page.php?';
$query='id='.$id.'&url_tag='.$url_tag;
$url = $url_back.$query;
echo 'Look how this url shows up: '.$url;
echo '<a href='.$url.'>Click here</a>';
?>
This is, the page receives two POST parameters. Then prepare a link to https://www.page.example.com/page.php? and I append those two parameters as GET parameters with the ids id and url_tag respectively.
Then I display how the whole link looks like. It shows up correctly, in this case https://www.page.example.com/page.php?id=ID&url_tag=URL_TAG, where ID and URL_TAG are the actual values received as POST parameters.
However, when I click on the 'Click here' link, it redirects me to https://www.page.example.com/page.php?, which is the url without any GET parameter.
Why is that happening and how would I solve it? I've tried to feed HREF with urlencode($url) instead, but it redirects me to an address flooded with undesired characters...
Any idea? Thank you!
Try to replace the last line of your code by this:
echo 'Click here';
It should work.
Try using http_build_query(), it takes care of any URL character compatibility issues for you...
// assuming you've already checked and validated your $_POST parameters
$query = http_build_query(array(
'id' => $_POST['id'],
'url_tag' => $_POST['url_tag']
));
$url = 'https://www.page.example.com/page.php?' . $query;
?>
Click here
Is it possible to create an HREF link that calls a PHP function and passes a variable along with it?
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='search($id)' >$name</a>";
}
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
You can do this easily without using a framework. By default, anything that comes after a ? in a URL is a GET variable.
So for example, www.google.com/search.html?term=blah
Would go to www.google.com/search.html, and would pass the GET variable "term" with the value "blah".
Multiple variables can be separated with a &
So for example, www.google.com/search.html?term=blah&term2=cool
The GET method is independent of PHP, and is part of the HTTP specification.
PHP handles GET requests easily by automatically creating the superglobal variable $_GET[], where each array index is a GET variable name and the value of the array index is the value of the variable.
Here is some demo code to show how this works:
<?php
//check if the get variable exists
if (isset($_GET['search']))
{
search($_GET['search']);
}
function Search($res)
{
//real search code goes here
echo $res;
}
?>
Search
which will print out 15 because it is the value of search and my search dummy function just prints out any result it gets
The HTML output needs to look like
anchor text
Your function will need to output this information within that format.
No, you cannot do it directly. You can only link to a URL.
In this case, you can pass the function name and parameter in the query string and then handle it in PHP as shown below:
print "<a href='yourphpscript.php?fn=search&id=$id' >$name</a>";
And, in the PHP code :
if ($_GET['fn'] == "search")
if (!empty($_GET['id']))
search($id);
Make sure that you sanitize the GET parameters.
No, at least not directly.
You can link to a URL
You can include data in the query string of that URL (<a href="myProgram.php?foo=bar">)
That URL can be handled by a PHP program
That PHP program can call a function as the only thing it does
You can pass data from $_GET['foo'] to that function
Yes, you can do it. Example:
From your view:
<p>Edit
Where 1 is a parameter you want to send. It can be a data taken from an object too.
From your controller:
function test($id){
#code...
}
Simply do this
<?php
function sample(){
foreach ($json_output->object ){
$name = "{$object->title}";
$id = "{$object->id}";
print "<a href='?search=" . $id . "' > " . $name . "</a>";
}
}
if (isset($_REQUEST['search'])) {
search($_REQUEST['search']);
}
function search($id){
//run a search via the id provide by the clicking of that particular name link
}
?>
Also make sure that your $json_output is accessible with is the sample() function. You can do it either way
<?php
function sample(){
global $json_output;
// rest of the code
}
?>
or
<?php
function sample($json_output){
// rest of the code
}
?>
Set query string in your link's href with the value and access it with $_GET or $_REQUEST
<?php
if ( isset($_REQUEST['search']) ) {
search( $_REQUEST['search'] );
}
function Search($res) {
// search here
}
echo "<a href='?search='" . $id . "'>" . $name . "</a>";
?>
Yes, this is possible, but you need an MVC type structure, and .htaccess URL rewriting turned on as well.
Here's some reading material to get you started in understanding what MVC is all about.
http://www.phpro.org/tutorials/Model-View-Controller-MVC.html
And if you want to choose a sweet framework, instead of reinventing the MVC wheel, I highly suggest, LARAVEL 4
i have two text type forms(id,name) and another form dropbox type(school name)(select option type).
when user enters the id form, the remaining form (name) and the drop box(school name) needs to be filled based on the values in mysql.
filling form text type (name) is not a problem which i am able to do using json and jquery ,but i do not know how to auto select the dropbox.
any tutorials or code snippets suggestions are appreciated.
if your drop box is in xhtml, you can use the "selected" param.
with jquery, you could write semething like :
$("#optiontoSelect").attr("selected","selected");
More info in the jquery doc
I may have misunderstood the question. If you wish the focus to move from the input field to the select you would use .focus(). I would imagine you want to call focus on successful population of the select.
$('#select').focus();
or
$(this).focus();
jQuery Docs : focus()
This'll get you started:
<?php
$options = Array('red', 'green', 'blue');
$opt_from_db = 'green'; // for example
echo '<select name="fieldName">';
foreach ($options as $opt) {
$selected = ($opt_from_db == $opt) ? ' selected' : '';
echo "<option{$selected}>{$opt}</option>";
}
echo '</select>';
?>
The key is to write the selected attribute (in some form or another) into the programmatically-rendered HTML.
I have a cool project where I need to upload an image via php/my_sql. That I can handle, but the images need to be linking to a certain url out of 100. In php can I save a url as a variable, then allow a drop-down menu of the 100 choices which point to a variable with a url?
The best choice would be to use an array:
$urls = array("url","url2","url3");
After you add all the 100 URLs in there, you can recurse through the array and output options into the tag.
<?php
echo "<select>";
foreach($urls as $current_url){
echo "<option>" . $current_url . "</option>";
}
echo "</select>";
?>
That would go through the array, echoing all the URLs into the tag.
If you don't want to set the text in the dropdown to the actual URL, you could set the array using keys array("This URL" => "url") etc. and put the URL value into the "value" property of the tag, and using the key name as the value between the opening and closing tags of the list.
If you need an explanation of that as well, I can provide one.
I'm still not sure what you mean, but if you want to know how to store a url in a variable that is usually done in a string like this:
$url = "http://www.mysite.com/the/beautiful/image.gif";
You can also redirect to that url like this:
header('Location: '.$url);
die();
If you want the user to decide to which site to go, do it similar to what BraedenP posted:
<select id="urls" onchange="document.location.href=document.getElementById('urls').options[document.getElementById('urls').selectedIndex].value;">
<?php
$urls = array(
'Image One' => 'http://www.mysite.com/one.gif',
'Image Two' => 'http://www.mysite.com/two.gif',
'Image Thee' => 'http://www.mysite.com/three.gif'
);
foreach($urls as $name=>$url){
echo "<option value=\"{$url}\">{$name}</option>";
}
?>
</select>