i need help to pass mysql/php variable to javascript? - php

im trying to get the id of the picture the user selected to rate with the onclick,however it will only alert "null". when the user selected the div tag, it will alert the id. i want to display the id. i can build off of this and then implement ajax to rate the picture. But, i need help on getting the id of the picture the user selected.
<?php
mysql_connect('localhost','root','');
mysql_select_db("ajax");
$query="SELECT * FROM xxxx";
$result= mysql_query($query);
while($row= mysql_fetch_array($result)){
$rating=$row['ID'];
echo "<img src='".$row['filepath']."'>";
echo "<br>";
echo "<div id='".$row['ID']."' value='".$row['ID']."' onclick='getrating();'>Likes: ".$row['Likes']."</div>";
echo "<br>";
}
im trying to get what picture the user selected to rate.
?>
<script type="text/javascript" >
function getrating(){
var x= document.getElementById("<?php echo $row['ID']; ?>");
alert(x)
}
</script>

A few things that you should do:
Try giving an id which starts with a letter for example, when writing the HTML code use:
echo "<div id='img" . $row[ 'ID' ] . "'></div>"
Note that i've added a prefix 'img' to the div's ID.
You have to pass the correct index to the javascript function because you are drawing the divs in a list but not the javascript function:
onclick='getrating( " . $row[ 'ID' ] . " );'
Now the javascript function will get the correct image ID when called upon clicking the respective DIV element.
Change the javascript function to:
<script type="text/javascript" >
function getrating( id )
{
var x = document.getElementById( "img" + id );
alert( x );
}
</script>

onclick="getrating(this.value);"
That code will pass the current value attribute of the div to the function you made in JavaScript. Be sure to add a parameter to your function to receive the data.

Easy.
Change this:
echo "<div id='".$row['ID']."' value='".$row['ID']."' onclick='getrating();'>Likes: ".$row['Likes']."</div>";
to this:
echo "<div id='".$row['ID']."' value='".$row['ID']."' onclick='getrating(this.value);'>Likes: ".$row['Likes']."</div>";
And this:
function getrating(){
var x= document.getElementById("<?php echo $row['ID']; ?>");
to this:
function getrating(row_id){
var x= document.getElementById(row_id);

You should put your event handler inside image like this:
<img src="" onclick="getrating(this.value)">
And you function should be like this:
function getrating(row_id){
x = document.getElementById(row_id);
alert(x);
}

Related

need help on php with javascript

I need help on some update like function:
<html>
$result = mysql_query("SELECT *FROM tbl_a LEFT JOIN tbl_b lass ON tbl_b.b_id=a.class_id LEFT JOIN category ON category.category_id=tbl_a.category_id WHERE list ='{$id}'"); </br>
while($row = mysql_fetch_array($result)){
$id_list = $row['id'];
$name = $row['name'];
....
}
}
echo "<script type='text/javascript'>
var id = document.getElementById('list').value = '.$id_list;'
var name = document.getElementById('fname').value ='.$name;'
</script> ";
</html>
my problem is that i can retrieve data but it not displaying on my input elements it should be like an update function
Quotes, quotes...
echo
"<script type='text/javascript'>
var id = '".$id_list."',
name = '".$name."';
document.getElementById('list').value = id;
document.getElementById('fname').value = name;
</script> ";
Working example: http://codepad.viper-7.com/3eI3Od
You need to call your input elements and then give them the new values instead of setting variables like you are doing. Remove the "var something =" and just do document.get.......
If what you posted is the complete code, then there is no list and fname elements. Better open the page and view the source code to see if you have the right value written into your Javascript.
NOTE:
Remember that if you put your Javascript after the element HTML, Javascript cannot retrieve the element. For example:
<script>
document.getElementById('test').value = 'Hello World';
</script>
<input type='text' id='test' value=''>
As you can see, it does not assign value to test element. Solution,
<input type='text' id='test' value=''>
<script>
document.getElementById('test').value = 'Hello World';
</script>
Put the input before the Javascript.

Can only read first value from form list using jQuery and PHP

I´m trying to build a shopping cart in jQuery and PHP but cannot read values from form list.
When trying to get value from the form that is submitted i only get values from
the first form in the list view.
Please look at behaviour here:
http://www.adlertz.se/index.php?op=prodlist&katID=9&sidemenu=menushop
Click buy on ex. the middle, you get value from first.
Please help me with this, i have benn looking for solution for three days.
Probably a simple problem but i cant find the answer anywhere :| !!!.
Many thanks in advance!
function prodlist(){
$katID = $_GET['katID'];
$sql = mysql_query("SELECT * FROM shop_prod WHERE kategoriID=$katID");
while ($rad=mysql_fetch_array($sql)) {
echo "<div class=\"shop_prod_list\">";
echo "<div class=\"shop_prod_list_tmb\"><img src=\"shop/images/prod_images_tmb/".$rad['prodID'].".png\" alt=\"\"></div>";
echo "<form id=\"addcartform\" class=\"addcartform\" method=\"post\">";
echo "<input type=\"hidden\" name=\"prodID\" id=\"prodID\" value=\"".$rad['prodID']."\" />";
echo "<input type=\"submit\" class=\"shop_prod_list_kundvagn\" value=\"\" id=\"addcart\"/>";
echo "</form>";
echo "</div>";
}
echo "<div id=\"search_results\"></div>";
}
$(document).ready(function(){
$(".addcartform").click(function(e){
e.preventDefault();
addcart();
});
});
function addcart(){
var prodID=(this).document.getElementById('prodID').value; <-(Reads value but only the first)
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
}
<?php
include "db_config.php";
include "db_connect.php";
$prodID = strip_tags(substr($_POST['prodID'],0, 100));
$prodID = mysql_escape_string($prodID);
echo $prodID ." is added.";
?>
Use class instead of id
echo "<input type=\"hidden\" name=\"prodID\" class=\"prodID\" value=\"".$rad['prodID']."\" />";
Send the element which was clicked to your function
$(".addcartform").click(function(e){
e.preventDefault();
addcart(this); //this line
});
Then use that element to find the input with your class
function addcart(element){
var prodID = $(element).find('.prodID').val(); //Get val of clicked item
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
})
Although i would use only one button, without a form like this.
Php:
echo "<button name='prodID' class='shop_prod_list_kundvagn addcart' data-prodid='".$rad['prodID']."' value='Add' />";
Javascript:
$(".addcart").click(function(e){
e.preventDefault();
var prodID = $(this).data('prodid');
$.post("functions/cart.php", {prodID : prodID}, function(data){
if (data.length>0){
$("#search_results").show();
$("#search_results").html(data);
}
});
});
The code you use to pick out the value is not correct.
In theory you are supposed to have unique id's - so thats your first issue to resolve.
Secondly you need to find a better way to locate the value you are interested in.
My suggestion would be to add a button within each form and call it 'submit'.
On this button you add a data attribute that contains the product id.
With an onclick handler on this button you'll be able to get the data attribute directly.
Example which is not tested:
<button data-prodid="XYZ" onlcick="handleclick()">submit</button>
Javascript:
$(this).data('prodid')
Please note that you should not have duplicate IDs on the same page.
In this case, all three of your products have the id of "prodID". So in your JavaScript, when you getElementById, you will always get the first ID with that name.
There are many solutions for this. For example, you could add the product ID to the ID of the button, like 'id="addcart_' . $rad['prodID'] . '"'
You'd then parse that ID upon form submit to determine which product was selected.
I found another solution here: http://api.jquery.com/serialize/ - to pass hidden values.
But your solution is much simpler :)

How to pass php values to javascript then to ajax?

I am echoing data into a table with values from my database. It looks like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array //I know this may be wrong, but that's not the point
echo "<tr><td>".$somedata."</td></tr>";
?>
So the value of this table row will be displayed based on how much data is in the database. I want to asynchronously update the page, for example the user wants to delete this from the DB. How can I pass this value to javascript with an onClick function? Or is there another way? If I have a link to delete in the table like:
<td><a onClick="delete(ThisValueOfThisTableRow)">Delete</a></td>
And in javascript or jQuery I want to find this value and set it to a variable, then pass it as:
var some_value = //get this value
.ajax{
url: "somephpfile.php"
data:{some_value:value}
}
I think this would be helpful to anyone if they a responsive member page. Please help out!
maybe something like this:
<?php
//mysqli_num_rows function
while($row=mysqli_fetch_array) {
?>
<tr>
<td><?=$somedata;?></td>
<td><a href='#' class='delete-btn' id='row-<?=$someID;?>'>Delete</a></td>
</tr>
<?
}//end while
?>
and then for the js event
$('.delete-btn').click(function() {
var id = $(this).attr("id");
id = id.split("-");
data = { "id" : id[1] }
//your ajax here, pass in your data obj
});
best of luck-
PHP
while ( $row = mysql_fetch_array( $result ) ) {
echo '<tr><td><a onclick="delete_row(' . $row['id'] . ')">delete row</a></td></tr>';
}
Javascript
function delete_row( id ) {
alert( id ); //To show you are getting the id remove this for production
//ajax goes here
}

how to get information from a field that is in a loop using javascript

I have a bunch of image names that is being retrieved from my data base and is in a while loop. In this loop I have a small form with the image names. This form is being use for another purpose. what I want is to get the field information with the item name to a javascript.
Example :
while($row = mysql_fetch_array($query)) {
$itemname = $row['name'];
echo "< input type='hidden' name='$itemname' value='$itemname'>
<img src='source' onclick='getname()' width='100%' height='100%' />";
}
I believe the reason why every image I click on is only giving me the first information from the database is because my id is being duplicated. My question is how can I get the field information to javascript without using the getElementById?
Use the following altered PHP:
$i = 0;
while($row = mysql_fetch_array($query)) {
$itemname = $row['name'];
echo "<input type='hidden' name='".$itemname."[]' id='input$i' value='$itemname' />";
echo "<img src='source' onclick=\"getname('input$i')\" width='100%' height='100%' />";
$i++;
}
Then you can retrieve the input value in Javascript:
function getname(id) {
var theinput = $('#'+id).val(); // jQuery example
// do something
(I also changed the input name to be an array, of couse you could name it what you want, maybe $itemname$i could be an idea, it depends how and if you want to process your form, however the name should be unique or array for good practice)
Here is a working example of HTML/JS: http://jsfiddle.net/fuHSv/1/
How about using some jQuery 1.8.2 like the following:
$(document).ready(function() {
var inputs = $('input').on('click', function() {
var name = $(this).attr('name');
var val = $(this).val();
// do stuff
});
});
See api.jquery.com for more.

Javascript and PHP (window.open)

So, in my website, I have a news system which has an option to edit and delete the news the administrator desires.
Well, I got the edit part right by using:
href="noticiaEditarForm.php?id_noticia=<?php echo $id ?>">Editar</a>
And then a $_GET on the other page.
However, this is not how I desire my editing window.
Therefore, I have been exploring a way to send the PHP variable that contains the primary key for the news table (MySQL) to a popup window, using JavaScript. But that's just the thing, it will only return the 1st value it gets from the query... (i.e If I click to edit the 3rd article, it edits my 1st one. Always.)
Here is my current code:
<div class="noticias">
<?php
include('conn/conn.php');
mysql_select_db($bd, $conn);
$resultado = mysql_query("SELECT * FROM noticia INNER JOIN user ON noticia.id_user=user.id_user ORDER BY id_noticia DESC");
while ($linha = mysql_fetch_array($resultado)) {
echo "<h1>" . $linha['titulo'] . "</h1>";
echo "<i>Posted by " .$linha['username']. " on " . "<y>" . $linha['data'] . "</y>" . "</i>";
echo "<p>";
echo $linha['texto'];
$id = $linha['id_noticia'];
if (isset($_SESSION['admin'])) {
?>
<div class="noticiasOpcao">
Editar
<a onclick="return confirm('Are you sure?')" href="noticiaApagar.php?id_noticia=<?php echo $id ?>">Apagar</a>
</div>
<?php
}
}
?>
<script language="javascript">
function open_win_editar() {
window.open (
"noticiaEditarForm.php?id_noticia=<?php echo $id; ?>",
"Editar notícia",
"location=1, status=1, scrollbars=1, width=800, height=455"
);
}
</script>
<?php mysql_close($conn); ?>
</div>
My point is to then use another query to get the title and text of the article to display on an WYSIWYG editor.
Can anyone point out my flaw?
This code:
<script language="javascript">
function open_win_editar() {
window.open ("noticiaEditarForm.php?id_noticia=<?php echo $id; ?>", "Editar notícia", "location=1, status=1, scrollbars=1, width=800, height=455");
}
</script>
Is happening outside of the PHP while loop, so the value of $id will be the last value that was set to $id in the loop. So the JavaScript code will always open the same link.
If you need the code within the PHP loop to specify the $id value for the JavaScript, then you can pass it as an argument to the JavaScript function. Something like this:
<script language="javascript">
function open_win_editar(targetID) {
window.open ("noticiaEditarForm.php?id_noticia=" + targetID, "Editar notícia", "location=1, status=1, scrollbars=1, width=800, height=455");
}
</script>
So the code rendering the anchor tags in the loop would pass the argument like this:
Editar
The rendered output would then contain the record-specific $id value on each a tag to be used by the JavaScript code on the client.
<script language="javascript">
function open_win_editar() {
window.open ("noticiaEditarForm.php?id_noticia=<?php echo $id; ?>", "Editar notícia", "location=1, status=1, scrollbars=1, width=800, height=455");
}
</script>
This is only rendered once, probably with the last ID. You need to figure out a structure so you can pass a different ID to it based on what article you clicked to edit.
The id of the piece to edit is only updated within the while loop and never outside of it.
To use it as you wish you should use a parameter for the open_with_editar function:
<script language="javascript">
function open_win_editar(id) {
window.open ("noticiaEditarForm.php?id_noticia="+id, "Editar notícia", "location=1, status=1, scrollbars=1, width=800, height=455");
}
</script>
Now you only have to update the onclick event and hand over teh respective id:
<div class="noticiasOpcao">
Editar
That should work.
Regards
STEFAN

Categories