I am using PHP to generate dynamic dropdown, the dropdown list items are fetched from database.
Here's the php code for that and it works.
<select name="title[]" id="title">
<?php $categories = Category::find_by_cid(5); foreach($categories as $category): ?>
<option value="<?php echo $category->name; ?>"><?php echo $category->name; ?></option>
<?php endforeach; ?>
</select>
What i want to do is, Using jQuery whenever a link with id AddNew is clicked, a new dropdown should appear below that, containing same values.
Also, is there any way to execute php code inside javascript??
ex :
<script>
var name = "<?php echo $user->name; ?>";
</script
To clone elements, you can use jQuery's .clone() method (obviously):
$('#addNew').click(function() {
$('select.title').after($('select.title').clone());
});
Note that ID's should be unique on the page, if you are going to clone the select element, give it a class instead of ID.
And yes, you can "use" PHP in JavaScript, provided that the file is processed with PHP. Just note that you are not actually accessing PHP with JavaScript, but rather creating JavaScript files dynamically.
Use jQuery .clone() method.
Also, is there any way to execute php code inside javascript??
Not really, no. PHP is executed server-side, so in the example you provided:
<script>
var name = "<?php echo $user->name; ?>";
</scrip>
That will turn out to be:
<script>
var name = "Josh";
</script>
at run-time, when the javascript has access to it. The php code is executed, then rendered to html where the javascript finally sees it. What you are doing is dynamically creating javascript rather than executing php code.
Related
I am stuck in a problem and in need of support from you guys.
My problem is I want to pass a php variable(dynamically called through database in loop) to another div on the same page without page refresh
//This is a loop
<td><a class="linkright" href="#existingcase?case_id=<?php echo $row_mycases['case_id']; ?>"><?php echo $row_mycases['case_id']; ?></a></td>
//The div which should get the above php variable
<div class="tabright" id="existingcase">
<?php
$c_id = $_GET['case_id'];
echo $c_id;
?>
</div>
//the javascript code for calling divs on the same page
<script>
$(".linkright").click(function(){
$(".tabright").hide();
theDiv = $(this).attr("href");
$(theDiv).slideToggle();
});
</script>
It shows in the url like this index.php#existingcase?case_id=2012001 but never passes the case id to #existingcase. And also #existingcase div does not load either but without passing caseid value, #existingcase loads.
Any suggestions would be great.
I think you want to print clicked case_id in div without page load. To do this, you don't want to pass it using url. you can simply achieve it using javascript.
If your div id existingcase is just change your code like this below.
you are printing that same case_id as a text of anchor tag using $row_mycases['case_id'];. So, you can easily get that text using javascript and you can easily print it in your #existingcasediv.
<td><a class="linkright" href="#existingcase"><?php echo $row_mycases['case_id']; ?></a></td>
I don't know about your other scripts. in .linkright click function place this code like this
$(".linkright").click(function(){
$('#existingcase').text($(this).text()); //if your div id is existingcase it will print your case id.
});
try this code. And let me know the result.
SEE THIS FIDDLE DEMO
UPDATED:
To pass client side value to serverside without page reload, you can use jquery.post() method.
Place this PHP code at the top of your page.
<?php
if (isset($_POST['id'])) {
$caseid = $_POST['id'];
return print_r($caseid);
}
?>
$caseid will contain currently clicked case_id value. So, you can use this $caseid wherever you want in this page. If you click on the another case id, it will update with respect to currently clicked case_id
replace your js with below code,
$(".linkright").click(function () {
$(".tabright").hide();
theDiv = $(this).attr("href");
$(theDiv).slideToggle();
$.post("yourPHPFile.php", { //use your current php file name instead of "yourPHPFile.php"
id: $(this).text()
}, function (caseid) {
$('#existingcase').text(caseid);
});
});
id : $(this).text() means, get the current element .text() and assign it to $_POST variable name of id. It will post to yourPHPFile.php. And you can retrieve that value like $caseid = $_POST['id'];.
In function (caseid) {, caseid contains the value of $caseid. So, only in this code, I assigned $caseid = $_POST['id'];
By this you can directly print clicked case_id text to your #exixtingcase div.
Any values after # are not sent to the server. Since PHP is a server technology you php code will never see the values after #
<a class="linkright" href="#existingcase?case_id=<?php echo $row_mycases['case_id']; ?>">
try doing
<a class="linkright" href="existingcase?case_id=<?php echo $row_mycases['case_id']; ?>">
instead and your php code should fill the div.
In my understanding of your explanation I think you are making a mistake. You are trying to mix Javascript and PHP with out page refresh. This is not possible through your code as PHP is server side and only works on the server. You can't do href within the same page and expect PHP code inside this div to be executed. The PHP code will not be there. You can try "view source" in your browser and check it out.
I think the only way to solve your problem is to make AJAX call using Javascript, get the response and put wherever you want (without refreshing the page)
Hope this helps and excuse my English
EDIT : Here is a working example for making a simple AJAX call using Jquery.
Your table should be some thing like this:
<td>
<a class="linkright" href="#" data-id="<?php echo $row_mycases['case_id']; ?>"><?php echo $row_mycases['case_id']; ?></a>
</td>
You will notice I added "data-id" attribute. We will use this id in our AJAX call. Put this in your JS :
// Create Jquery ajax request
$("a.linkright").click( function() {
$.get("example.php", // Put your php page here
{ case_id : $(this).attr("data-id") }, // Get data, taken from the a tag
function(data) { // Call back function displays the response
$(".tabright").html("<p>" + data + "</p>");
}); // Get
}); // click event
}); // Document Ready
I tested the code and it is working. You will need to customize it to work for you. If all of this AJAX is new to you I suggest these links for you :
http://www.w3schools.com/ajax/default.ASP
http://learn.jquery.com/ajax/
Ok, so here is my code. I am trying to select a picklist value using Javascript, from PHP (I do not want a direct method to do this with PHP, as this won't work for my particular program)
Here's the code:
ECHO '<script type="text/javascript">
var pl = document.getElementById("cultpicklist");
pl.options[37].selected = true;
</script>';
However when I try to run this, it does not seem to work and it says pl.options[37] is undefined.
What am I doing wrong?
Note, there is a multiple select list which has an option with a value of 37.
EDIT: I seem to get this error or warning message:
Element referenced by ID/NAME in the global scope. Use W3C standard document.getElementById() instead.
admin.php?org=7()admin.php?org=7 (line 68)
pl.options[37].selected = true;
Here's the relevant HTML:
<fieldset><label for="culture">Culture:</label>
<select name="culture[]" multiple="multiple" id="cultpicklist"><?php
while ($cultrow = mysql_fetch_array($rescult)) {
ECHO '<option name="culture[]" value="'. stripslashes($cultrow['cult_id']) .'">'. stripslashes($cultrow['cult_desc']) .'</option>';
}
?>
</select></fieldset>
Here's the generated HTML code:
<select id="cultpicklist" multiple="multiple" name="culture[]">
<option value="36" name="culture[]">test1</option>
<option value="37" name="culture[]">test2</option>
<option value="38" name="culture[]">test3</option>
<option value="39" name="culture[]">test4</option>
</select>
The index of the options IS NOT the value of the option. When you use pl.options[37] you saying to JS to get the thirty-seventh option in the select and not the option with the value 37.
Try this:
<script type="text/javascript">
var pl = document.getElementById("cultpicklist");
for(var i=0; i<pl.options.length;i++) {
if(pl.options[i].value == "") { // Between the quotes you place the comparison value!
pl.options[i].selected = true;
}
}
</script>
BTW: If you already use jQuery on your page it's more correct to use it's functions, but if you don't use jQuery is too much code to add to your page just to change a select value.
You are likely putting the cart before the horse. You cannot use JavaScript to manipulate DOM elements until they've been rendered in the browser.
Put your script AFTER your HTML or check to see of the DOM is ready before running your script.
Why not use JQuery first of all...
$('#cultpicklist').val('myvaluetoselect');
Is MUCH easier to code, read and works instead of using bulky old school javascript...
Using jQuery, you could still put your code in between <head></head> tags. You would use $(document).ready() thus executing your code after the whole document has rendered.
I'm fairly new to jQuery and OOP in PHP,
but what I have is a PHP Object that has an array
$array[0] = "a"
$array[1] = "b"
$array[2] = "c"
$array[3] = "d"
and a select box in my HTML
<select class="box">
<option value="1">First Letter</option>
<option value="2">Second Letter</option>
<option value="3">Third Letter</option>
<option value="4">Fourth Letter</option>
</select>
<div></div>
How do I dynamically change whatever is in the div tags as someone changes the value of the select box using jQuery?
Is there a way to do something like
$('.box').change(){ var value = $object->array[index-1]}?
Assuming I had already have the value for index.
EDIT
I know I'll have to use Ajax, but I'm not sure how to call a method in an instance of an object already made.
You can't access PHP through javascript. There are several possible solutions:
Load all of the possible data combinations at once onto the page stored somewhere in the DOM. As the user cycles through the options, change them appropriately.
Load only the initial elements onto the page without javascript, then use Ajax to load all other possible combinations.
Load each combination with ajax on the fly.
You can either have javascript make an Ajax request to the same page and filter the request, or you can create a proxy that will serve only the requests you need when hit with ajax.
Remember that you are trying to combine PHP with Javascript.
Your code will primarily be written in javascript, but you'll
only inject bits of PHP code into the javascript code.
As in this instance, use the standard jquery onchange event method 'change()'
for the selectbox, set the javascript variable value to $object->array[0]
from PHP.
$('select').change(function() {
var value = <?php echo $object->array[$index] ?>
$('div').html(value)
});
You can use the php function json_encode to turn your php data into a javascript object. e.g
<script type="text/javascript">
var mydata = <?= json_encode($myarray) ?>;
console.log(mydata);
</script>
I want to display the photos according to the album selected. But, I don't want to post the page, I want to just change the div.
This is my script:
<script type="text/javascript">
function replaceContent(divName, contentS) {
document.getElementById(divName).innerHTML = <?php echo get_pictures_from_album($fb, $albums, contentS); ?>;
}
</script>
And this is the select tag that invokes it:
<select name="album" size= "1" style="width:210;" onchange="replaceContent('photos', this.options[this.selectedIndex].value);">
<?php get_albums_select_list($albums); ?>
</select>
<div id = "photos">
<?php echo get_profile_pictures($fb, $albums); ?>
</div>
I understand from a reading that I have done that the problem might be connected to javascript Vs php variable types.
Please advise.
Looks like you are looking for an AJax call to an PHP script that retrives the data for the appropriate album selected and THEN update the div with the callback function.
Ajax + PHP basics
You are mixing Clientside and Serverside Code here. The function replaceContent is called after the page (and the php code) was loaded. You would need an Ajax Call for that if you need more information about that:
Ajax Tutorials on Google
What you are doing is not possible because PHP code runs before (on the server because PHP is server-side language) javascript code.
You will have to resort ot AJAX for that.
Initially, I used a .js file that contains AJAX functions to call a .php file. The .php file contains code to dynamically populate a DropDown based on certain parameters passed via QueryString.
Everything works fine with the above method. But now I want to populate the DropDowns on page load and so want to use JQuery instead of my old method. I tried following code, but it is not filling the DropDown.
$.get("../Lib/filldropdown.php",
{ param1: "divMemberOf", param2: "inMemberOf", param3: "categorymaster" });
Below is the code of the .php file:
<?php
require("dbconnection.php");
require("dbaccess.php");
$dropdownControlName = $_GET['DropDownControlName'];
$query = ".....";
dbconnection::OpenConnection();
$result = dbaccess::GetRows($query);
?>
<select id="<?php echo $dropdownControlName; ?>" name="<?php echo $dropdownControlName; ?>">
<option>Select from the list</option>
<?php while($row=mysql_fetch_array($result))
{ ?>
<option value="<?php echo $row[0]; ?>"><?php echo $row[1]; ?></option>
<?php } ?>
</select>
Please note that the above JQuery code passes three parameters, but I have used only one in the PHP code above. I am going to use two parameters later. The above PHP code is perfectly working with my old AJAX method.
You are making an AJAX request using GET, but you are not adding a callback function to actually handle the returned HTML. It vanishes in thin air.
Check out the JQuery AJAX documentation on GET for a complete example.
Your call would have to look something like this:
$.get("../Lib/filldropdown.php",
{ param1: "divMemberOf", param2: "inMemberOf", param3: "categorymaster" },
function(data) { $('#myDivID').html(data); }
);
You either need to add a callback function, or the .load method might be more appropriate since you just want to inject the results from that PHP call into the page:
$("#someContainer").load("../Lib/filldropdown.php",
{ param1: "divMemberOf",
param2: "inMemberOf",
param3: "categorymaster" });
You just need some DIV or something to be a placeholder to inject the select box into.
You are not specifying the key correctly for your php to work as-is. In your javascript you are creating a request like this:
param1=divMemberOf¶m2=inMemberOf¶m3=categorymaster
I would think you need one of those parameters to be named DropDownControlName since you are using it as the id for your newly created select input. You might also check param2 and param3 since you are likely using those in your query.