use php variable inside javascript retuns null - javascript

I have the following code:
<?php
include('Connection.php');
$query = $conn->prepare("SELECT DISTINCT c.movieName, c.castName, c.movieImdbId, f.year, f.posterLink FROM cast_movie as c JOIN film_info as f ON c.ImdbId = f.ImdbId WHERE c.castName = :q");
$query->execute(array(':q' => $searchText ));
while($row = $query->fetch(PDO::FETCH_ASSOC)):
?>
<tr>
<td><?php echo $row['movieName']; ?></td>
<td>Add to list
</tr>
<?php
endwhile;
?>
<script type="text/javascript">
$('#add').on('click', function (e) {
var selectedOpts = "<?php echo $row['movieName']; ?>";
var obj = {
"movie_name":selectedOpts,
"movie_info": ""
};
parent.window.opener.addToBasket(selectedOpts); //addToBasket is a function that add selected movies to the basket.
});
</script>
My question:
When I click on "add to list" link, it add Nothing to the basket (I mean, the function addToBasket works fine, but the value of "selected" is null..
Could someone kindly let me know how should I use <?php echo $row['movieName']; inside my javascript code? I know I have to put it between "", but I think there should be another problem.. (maybe because this row is not known in javascript code, but I have no idea how to fix it..)
I add also this image to clarify the problem:
Thanks in advance,

Not tested code, but this should work for you :)
<?php
include('Connection.php');
$query = $conn->prepare("SELECT DISTINCT c.movieName, c.castName, c.movieImdbId, f.year, f.posterLink FROM cast_movie as c JOIN film_info as f ON c.ImdbId = f.ImdbId WHERE c.castName = :q");
$query->execute(array(':q' => $searchText ));
while($row = $query->fetch(PDO::FETCH_ASSOC)):
?>
<tr>
<td><?php echo $row['movieName']; ?></td>
<td>Add to list
</tr>
<?php
endwhile;
?>
<script type="text/javascript">
function addmovie(movieName) {
var obj = {
"movie_name":movieName,
"movie_info": ""
};
parent.window.opener.addToBasket(obj); //addToBasket is a function that add selected movies to the basket.
}
</script>

You could use the .prev() jquery option, that will return the dom object previous to your '#add td.
in this case the that olds the movie name, and get the value inside the previous as selectedOps

There are couple of issues I can see:
You have used id="add" for all the rows(movies) and then attaching click event to the id. Change id="add" to class="add".
put the movie name in a data attribute like:
<td>Add to list
Then change the javascript to :
<script type="text/javascript">
$('.add').on('click', function (e) {
var selectedOpts = $(e).data("movieName");
var obj = {
"movie_name":selectedOpts,
"movie_info": ""
};
parent.window.opener.addToBasket(selectedOpts); //addToBasket is a function that add selected movies to the basket.
});
</script>
This should work.

Your first mistake is you are using "id" to fetch the value
Add to list
and you have used while loop because of which your id is getting duplicated and as we all know "id" of element in js should be unique throughout the page.
There are many solutions available for your problem out of which following is one
while($row = $query->fetch(PDO::FETCH_ASSOC)):
?>
<tr>
<td><?php echo $row['movieName']; ?></td>
<td>Add to list
</tr>
<?php
endwhile;
?>
Javascript :
<script type="text/javascript">
$('.add').on('click', function (e) {
var selectedOpts = $(this).attr('lang');
var obj = {
"movie_name":selectedOpts,
"movie_info": ""
};
parent.window.opener.addToBasket(selectedOpts); //addToBasket is a function that add selected movies to the basket.
});
</script>
Suggession : Avoid direct use of php in javascript code instead try to use hidden () variables.

Related

How to get a value of an attribute inside a loop using jQuery

I have this code from my HTML form.
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" id="charge<?php echo $c->id; ?>" cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
when I tick a textbox I want the value for that element pops up.
So far, only the value for the first occurrence pops up.
This is the jQuery code. I know I'm missing something, but i dont know
function triggerChange1(){
$("#ch1").trigger("change");
}
$("#charge1").change(function() {
var v = $(this).attr('cash');
alert(v);
});
if($("#charge1").prop('checked')){
triggerChange1();
}
Firstly you should use a class attribute to group elements together. You should also use data-* attributes to assign any custom meta data to an element as creating your own non-standard attributes will render the page invalid and lead to potential UI and JS issues:
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" class="charge" id="charge<?php echo $c->id; ?>" data-cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
Then you can have a single click handler to get the value from the element which raised the event:
$('.charge').change(function() {
var v = $(this).data('cash');
alert(v);
});
// raise the event on checked elements on load:
$('.charge:checked').change();
EDIT: As rightfully stated in Rory's answer you should prefix your custom attributes with data-
What you need is a class.
<?php foreach ($charges as $c): ?>
<br><input type="checkbox" class="charge" id="charge<?php echo $c->id; ?>" data-cash="<?php echo $c->amount; ?>"> <?php echo $c->description; ?>
<?php } ?>
$(".charge").change(function() {
var v = $(this).data('cash');
alert(v);
});
You can see it working here: http://jsfiddle.net/0cude9jr/
function triggerChange1(){
$("#ch1").trigger("change");
}
$(document).ready(function() {
$("#charge1").change(function() {
var v = $(this).attr('cash');
alert(v);
});
if($("#charge1").prop('checked')){
triggerChange1();
}
}
And you should use value attribute and not cash attribute.
And then you can call var v = $(this).val();

How to get the parent div id in javaScript?

I want to get the parent div id (the div class is called "col-sm-2") when selecting each option in HTML "select" tag in each div. But it always gives only the div id of latest added product at "id" alert. For example if the id of my last added product is "7", it always gives "7" as the alert.
Here is my PHP code for getting the product id.
$jsql_ae7 = mysql_query("select request_list.product_id from request_list where request_list.product_id='{$jrowa2['id']}' and request_list.email='$visit_email'") or die(mysql_error());
$jfeta7 = mysql_fetch_assoc($jsql_ae7);
Here is my HTML code.
<div class="col-sm-2" id="<?php echo $jfeta7['product_id']; ?>">
<select id="formats_id" name="aformats" onchange="showFormat(this);">
<option value="<?php echo $jrowa2['formats']; ?>"><?php echo $jrowa2['formats']; ?></option>
<?php foreach($formats3 as $v3){ ?>
<?php if($v3 !== $jrowa2['formats']) { ?>
<option value="<?php echo $v3; ?>"><?php echo $v3; ?></option>
<?php } ?>
<?php } ?>
</select>
</div>
Here is my javaScript code.
var showFormat = function(dd) {
var format_value = dd.options[dd.selectedIndex].value;
var scriptTags = document.getElementsByTagName('select');
var id = scriptTags[scriptTags.length - 1].parentNode.id;
alert(id);
};
Try to use each:
$('select').each(function() {
alert($(this).parent().attr('id'));
});
You coild get the id property of the immediate container div using closest() :
$('select').on('change',function() {
alert($(this).closest('div').prop('id'));
});
use this code
var showFormat = function(dd) {
var format_value = dd.options[dd.selectedIndex].value;
var scriptTags = document.getElementsByTagName('select');
var parent = scriptTags[scriptTags.length - 1].parentNode;
alert(parent.getAttribute('id'));
};
Try this:
Fiddle
$('#formats_id').change(function(){
alert($(this).parent().attr('id'));
});
First we will start with making the selection:
$('select').each(function() {
var selectField = $(this); // this will point to select element
});
There are two ways:
This will take direct parent of select
selectField.parent().attr('id');
This will select first ancestor that is a div with class 'my-class':
selectField.closest('div.my-class').attr('id');
Both work, but differ in deep of search:)

Passing a AJAX Variable to PHP

Hi wondering how to send a AJAX variable to php, I thought I had it but apparently not. In my console I get the error "Uncaught TypeError: Illegal invocation line 6"
Im taking it there is something wrong with my code straight after the alert?
(NOTE where it say "jquery" is in replace of $ simply because joomla does not like $ in scripts for some reason)
UPDATED, Pay attention to
Script to click and get rowID
<script language="javascript" type="text/javascript">
jQuery(document).ready(function()
{
jQuery("tr.getRow").click(function()
{
rowID = jQuery(this).find("td.idCell");
alert(jQuery(rowID).text());
//Send the row ID to ajaxupdate.php
jQuery.post("ajaxupdate.php", { submit: "update", ID_ID: rowID})
.done( function(data) {
var results = jQuery.parseJSON(data);
console.log( results );
})
.fail( function() {
console.log("AJAX POST failed.");
});
});
});
</script>
Load first table(the one thats being clicked)
<table border="",th,td, width="500", align="center">
<tr>
<th>TP ID</th> <th>Permit Deny</th> <th>Level</th> <th>Session</th> <th>Information Specialist</th>
</tr>
<?php foreach ($results as $row): ?>
<tr class="getRow">
<td class="idCell"><?php echo $row->TP_ID ?></td>
<td><?php echo $row->Permit_or_Deny ?></td>
<td><?php echo $row->Level ?></td>
<td><?php echo $row->Session ?></td>
<td><?php echo $row->Information_specialist ?></td>
</tr>
<?php endforeach ?>
<br>
</table>
Second table, the one that im trying to get to load
<?php
// In ajaxupdate.php file
if( (isset($_POST['ID_ID'])) || (isset($_POST['submit']))) //im Sure this part is wrong
{
$ID_ID =($_POST['ID_ID']); // pass JS var as a PHP var
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query
->select($db->quoteName(array('CV_ID', 'Classifier', 'Value', 'TP_ID')))
->from($db->quoteName('sessionta'))
->where($db->quoteName('TP_ID') . ' LIKE '. $db->quote('".$ID_ID."'));
$db->setQuery($query);
$results = $db->loadObjectList();
}
?>
3425742,
I rewrote your script and tested it with this JSfiddle. Try it out.
I see that you are using Joomla. Diving into Joomla as a novice is daunting. Within ajaxupdate.php the script is expecting to see a $_POST['submit'] variable. Either remove that requirement or add it like I did below. At the bottom of ajaxupdate.php add this line so that jQuery has something to test.
echo $results ? json_encode("succeeded") : json_encode("failed"); die();
Here is the jQuery ajax code:
//Send the row ID to ajaxupdate.php
$.post("ajaxupdate.php", { submit: "update", TP_ID: rowID})
.done( function(data) {
var results = $.parseJSON(data);
console.log( results );
})
.fail( function() {
console.log("AJAX POST failed.");
});
Edit "ajaxupdate.php" to the correct location of that file. If ajaxupdate.php is in a different directory you have to tell jQuery to look there. For example, if your $.post is in index.php in the root of your webserver and ajaxupdate is in the /js directory change "ajaxupdate.php" to "js/ajaxupdate.php".
you are passing rowID as an object, not as a single text-variable. You'd need
$.post("ajaxupdate.php", ({ TP_ID: rowID.attr('id') }), function( data )
...

Dynamically changing dropdown to textfield opencart

I am trying to change a drop down so that a user can add a custom input instead.
I am using VQMod and have currently set up a PHP array as follows:
<td><select name="electricColours">
<?php foreach (array("", "White", "Black", "Add Custom Colour..." ) as $eColours) { ?>
<?php if ($electricColours == $eColours) { ?>
<option value="<?php echo $eColours;?>" selected="selected"><?php echo $electricColours; ?></option>
<?php } else { ?>
<option value="<?php echo $eColours;?>"><?php echo $eColours; ?></option>
<?php }?>
<?php } ?>
<td class="left"><a onclick="AddCustomColour();" class="button"><?php echo "Add Custom Colours"; ?></a></td>
</select>
How would I be able to add new values to the eColours using the "Add Custom Colour..." so that the user inputs something and that colour is added on to the array.
I thought using Javascript so that it shows up as an alert and the user gets to choose their option would work however it keeps saying the variable is not defined.
<SCRIPT TYPE="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var arrays = <?php echo json_encode($electricColours); ?>;
if (colour!=null)
{
electricColours.push(colour);
}
}
</SCRIPT>
Thanks
Use the DOM API:
var option = document.createElement("option");
option.setAttribute("value", value);
option.appendChild(document.createTextNode(value));
document.getElementById("the_select_element").appendChild(option);
Instead of:
document.getElementById("the_select_element")
You could do something like:
document.forms.the_form.electricColours
replace this code
<SCRIPT TYPE="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var arrays = <?php echo json_encode($electricColours); ?>;
if (colour!=null)
{
electricColours.push(colour);
}
}
</SCRIPT>
With this Code
<script type="text/javascript">
function AddCustomColour()
{
var colour=prompt("Please add custom colour","Silver");
var ob = $("#electricColours");
if (colour!=null)
{
ob.prepend("<option value="+ val +">" + text + "</option>");
}
}
</script>

Pass and update php variable into javascript

Is there a way I can pass the php option value variable $option_value['price'] into javascript as a string, then each time a different option is chosen, the javascript 'updates' the string with the new value. I have tried with onchange() but must be doing something wrong. I am sure my mistake is because php is server side and javascript is client side, but I have no idea how to get the two to act how I want.
<?php if ($options) { ?>
<?php foreach ($options as $option) { ?>
<?php if ($option['type'] == 'select') { ?>
<span id="option-<?php echo $option['product_option_id']; ?>" class="option">
<select name="option[<?php echo $option['product_option_id']; ?>]" onchange="getIt(this)">
<?php foreach ($option['option_value'] as $option_value) { ?>
<option value="<?php echo $option_value['product_option_value_id']; ?>"><?php echo $option_value['name']; ?>
<?php if ($option_value['price']) { ?>
<?php $option_value['price']; ?>
<?php } ?>
</option>
<?php } ?>
</select>
</span>
I have tried:
<script type="text/javascript">
function getIt(elm) {
var val = elm.options[elm.selectedIndex].text;
window.alert(val);
}
</script>
and
<script type="text/javascript">
function getIt() {
var val = "<?php $option_value['price']; ?>";
window.alert(val);
}
</script>
Here is an example how you can do it. What you have to do are:
Analyze the code (notice that I use jquery from google's account. You will need to at some point install jquery on your web site and use this one instead of the google's one.
Build your fruits array so it looks like the one in the example.
I have prepared page that will show you this working here: http://jsfiddle.net/7uudp/
Below is what it contains. Notice that this example does not use your variables. You will need to use them the way you want/need. I have also defined entry_fruit to show you how to chose the default one to be selected. Hope it will help.
<html>
<head>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script>
<script type="text/javascript">
fruits = [{n:"apple",p:1},{"n":"strawbery",p:3}];
entry_fruit="strawbery";
function build_select(select,list,which)
{
$.each( list, function(i,v){
var selopt="" ;
if ( v.n == which ) selopt="selected" ;
$(select).append("<option "+selopt+" value="+i+">"+v.n+" - $"+v.p+"</option>");
}) ;
}
$(document).ready(function(){
build_select($("select[name=fruits]"),fruits,entry_fruit);
$("select[name=fruits]").change(function(){
alert("Price is $" + fruits[$(this).val()].p);
}) ;
})
</script>
</head>
<body>
<select name="fruits"></select>
</body>
</html>
<script type="text/javascript">
function getIt() {
var val = "<?php echo $option_value['price']; ?>";
window.alert(val);
}
</script>
Like so? Looks to me like you just forgot the "echo".
EDIT-
<script type="text/javascript">
var val = "<?php echo $option_value['price']; ?>";
function getIt(elm) {
val = elm.options[elm.selectedIndex].text;
window.alert(val);
}
</script>
Okay, Revoking my previous entry.
What you need to do is to add selected keyword to your <option> element when you match your option_value['price']
Now yuou need to arrange your data in a little bit different way.
In your javascript, prepare an array that will map $option_value['product_option_value_id'] to $option_value['price'];. When you build your <select>, for each $option_value['product_option_value_id'] check if its price matches the one that came in initially from php.
Your getIt will simply take the <option value="___"> value, find it in that map, and show it to the user using the alert() window.

Categories