pass variable inside a php loop and jquery - php

hi guys i need another idea how to make this happend i got a loop on my script that shows id for each member and i want to pass a variable for each member this is an example
<?php
$loopvalue = $playerCount;
$i=1;
while ($i <= $loopvalue) {
$uid = $data['players'][$i-1]['avatar']['userId'];
?>
<input class="user_id_imput" type="hidden" name="id" value="<?php echo $uid;?>" />
<?php echo $userName;?></span>
<?php
$i++;
};
?>
and using jquery to show the variable with this
$(".Send_user_id").click(function() {
var uid = $(".user_id_imput").val();
console.log('id: ' + uid );
});
normaly i do this when not using a loop bu in this case i cant think of a diferent way to do it
using this will give me the id of the first result for all the results any idea how i can pass the id var for each result?
thanks for you help

Assuming that your <a> tag and <input> tags are back to back; you can use following approach:
$(".Send_user_id").click(function() {
var uid = $(this).prev(".user_id_imput").val();
console.log('id: ' + uid );
});
$.prev() Get the immediately preceding sibling

thanks for the help you gave me an idea instead of using the input using data-id to pass the variable
so the result code will be
php
<a data-id="<?php echo $uid;?>" href="#" class="Send_user_id"><?php echo $userName;?></a></span>
jquery
$(".Send_user_id").click(function() {
var uid = $(this).attr('data-id');
console.log('id: ' + uid );
});

Related

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 pass variable from PHP to JS, perform math on the variable then output to an on page element [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
how to access PHP variables from within JavaScript?
I am trying to pass a variable from mySQL to PHP then to JavaScript to perform some math on it then have the result displayed on page in a specific area (in a <p> element with a specific ID assigned to it). Is this possible or is there an easier solution?
Thanks!
I already know how to get the variable from MySQL to PHP just having trouble on what to do after that.
Here is my updated code after reading responses. Still not working but I am sure I'm doing something wrong!
<p id="p_id"><?php echo $price; ?></p>
<input type="radio" group="radio_group" value="Reduce 10%" onclick="radio_click();" />
<script type="text/javascript">
var price = <?php echo $price; ?>;
function radio_click() {
var target = document.GetElementById('p_id');
var final_number; // this will be variable your store the final number in
final_number = price * .9;
target.innerHTML = final_number;
}
</script>
In short, you have to pass the variable to the <script> tag as a string in a JavaScript friendly format (quotes and stuff).
<?php
$variable = 5;
$javaScriptAccessible = '
<script type="text/javascript">
var javaScriptAccessible = "'. $variable . '";
</script>
';
echo $javaScriptAccesible;
Also, you could JSON it:
<?php
$variable = 5;
$javaScriptAccessible = '
<script type="text/javascript">
var javaScriptAccessible = '. json_encode($variable) .';
</script>
';
echo $javaScriptAccessible;
With JSON, the quotes would be appended automatically.
Here you can see both in action: http://codepad.viper-7.com/Jyfw31
Update:
Here are more refined and, I think, better to understand examples: http://codepad.viper-7.com/1cloyB
Only thing you have to do, is use it on your radio buttons / elements.
I'd strongly suggest going with JSON, because it actually stands for JavaScript Object Notation, it has libraries in, probably, every single programming language on planet, and is specifically designed to pass JS data from one environment to other.
http://php.net/manual/en/function.json-encode.php here you can see multiple options you're able to pass in order to render it differently.
Just output the variable from PHP into a <script> item. Then set the innerHTML property of your <p> based on your calculation. You can put this into a function and call it from your radio button's onclick.
<p id="p_id"><!-- Your value will be inserted here --></p>
<input type="radio" group="radio_group" value="some_value" onclick="radio_click();" />
<script type="text/javascript">
var your_number = <?php echo $php_number; ?>;
function radio_click() {
var target = document.GetElementById('p_id');
var final_number; // this will be variable your store the final number in
// do your math here using your_number variable
target.innerHTML = final_number;
}
</script>
To pass the data from PHP to JavaScript, just echo it.
For example, say you want to display the data in a message box:
$data="something";
echo "<script>";
// Do the maths
echo 'var = ' . $data . ' + 1';
echo 'document.write("<p id=\"someID\">" + var + "</p>");' // PHP code writing Javascript code to write HTML code. Wow.
echo "</script>";
If you want to display the data on click of a radio button:
<input type="radio" onClick="someFunction();">
<?php
echo "<script>function someFunction() {";
// Do the maths
echo 'var = ' . $data . ' + 1';
echo 'document.write("<p id=\"someID\">" + var + "</p>");' // PHP code writing Javascript code to write HTML code. Wow.
echo "}</script>";
?>
*Edit: If the <p> tag already exists, use document.GetElementById(\"someID\").innerHTML = var; instead of document.write("<p id=\"someID\">" + var + "</p>");.

Jquery append textbox with unique PHP number

I have a site that appends a textbox to a div when the user clicks a button. The textbox works great. Now, I would like to generate a unique number for the id of each box. The following code is giving me 0 as the id of each box. I'm trying to get them to go 1,2,3,4...
Code:
<?php $x=0; ?>
$("#add").click(function(){
$('#boxes').append(<input type="text" id="<?php echo $x; $x++; ?>">);
});
PHP code is excuted earlier before the javascript code is executed. But in your code example you try to execute both at the same time. That is just not the case.
Instead of a PHP variable you need to use a javascript variable:
var x = 0;
$("#add").click(function() {
$('#boxes').append('<input type="text" id="' + ++x + '">');
});
You can use PHP variable as base for your javascript variable or just plain javascript.
//note, $x can be anything e.g. 1
var boxID = '<?php echo $x; ?>';
$("#add").click(function(){
//insert new box, increase boxID
$('#boxes').append('<input type="text" id="'+boxID+'">');
boxID++;
});

Javascript: dynamic var names with php?

Probably a dead simple and idiotic question (I'm totally new to javascript):
I have this code that loads a new post by clicking on a "next" or "back"-link. The clicks variable is used to scroll up and down in the sql-limit-statement (using the swapContent function), means you move backward or forward in the database by clicking the links. It works easy and perfectly:
<script type="text/javascript">
var clicks = -1;
function increase()
{
clicks++;
return false;
}
function decrease()
{
clicks--;
return false;
}
</script>
<div id="<?php echo $post['id'].'-multipost'; ?>">
<?php include('views/posts/_postmultipost.php'); ?>
</div>
<div id="<?php echo $post['id']; ?>-next" class="rightbutton" style="display:block;">
next
</div>
<div id="<?php echo $post['id']; ?>-back" class="leftbutton" style="display:none;">
back
</div>
The only problem: As you see I have several posts (post-IDs). But the javascript var "clicks" is always the same. How can I add the post-id into the javascript variable name "clicks", well, something like this :
var <?php echo $post['id']; ?>-clicks = -1;
Of course it doesn't work this way, but I have no clue how to manage it. Any advice? Sorry for this stupid question...
Thanks for your help!
UPDATE
Ok, got the solution: Bryan was right!!!
Changed the code to:
<script type="text/javascript">
var clicks = {};
clicks['<?php echo $post['id']; ?>'] = -1;
function increase()
{
clicks['<?php echo $post['id']; ?>']++;
return false;
}
</script>
The javascript in html stays as it is:
>
Clicks is now an object and will output the following in the swapContent-Function:
count: Array
(
[80] => 0
)
In php you would access the value like this:
foreach($count as $key=>$value) { $count = $value }
In javascript it seems to work a bit different like this:
for(x in clicks)
{
var clicks = clicks[x];
}
Seems to work perfectly now, thanks for your help!!
I'm not incredibly familiar with PHP, so I don't know about php echo. However, would using an object work?
var postClicks = {};
postClicks['<?php echo $post['id']; ?>'] = -1;
As far as I understand you are trying to get this:
var something-clicks = -1;
But in JS something-clicks is an expression - substraction of two variables.
Name tokens in JS cannot contain '-' in contrary with CSS.
You have a syntax error:
onmousedown="increase(); javascript:swapContent('next', clicks, '<?php echo $post['id']; ?>', '<?php echo $post['title']; ?>', '<?php echo $_SESSION['user']['id']; ?>');"
that javascript: is the problem. That property is expected to contain raw JS, and that token is invalid. the javascript used as a protocol is for use on the href property of an a tag.
Other than that, it looks alright. Just type clicks in the JS console of your browser to get the current value returned. Or add console.log('clicks:', clicks); to your function so that the result is logged out on each click.

How to insert PHP values into Javascript?

Javascript:
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option><option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
PHP/HTML:
<script type = "text/javascript" src="js/addinput.js"></script>
<form name="form1" method="POST" action="services.php" onsubmit="return valid()">
<br><br><br><center>
<table class="form" border=1>
<tr>
<td class="head" colspan="2" >Select Vehicle:</td>
</tr>
<tr ></tr>
<tr>
<td colspan="2" class="info">
<div id="dynamicInput">
<br><select name = "vehicle[]" id = "vehicle1">
<option value = "">Vehicle 1</option>';
include_once "vehicledbconnect.php";
$queryveh = mysql_query("SELECT * FROM vehicletbl");
while($fetch_2 = mysql_fetch_array($queryveh)) {
$brand = $fetch_2['vehbrand'];
$name = $fetch_2['vehname'];
echo '<option value = "'.$brand.' '.$name.'">'.$brand.' '.$name.'</option>';
}
echo '</select>';
echo '<input type="button" value="Add another vehicle" onClick="addInput(\'dynamicInput\');"></div>';
Hi. Is it possible to insert PHP values in a javascript? I have a program here that if the customer click the submit button (echo '), a new drop-down form will appear. And I want the drop down form to contain all of the values of the query ($queryveh = mysql_query("SELECT * FROM vehicletbl");). In my default drop-down form, all values of the query are shown. Please help me guys. I am desperate for an answer. Javascript is my weakness. Thanks a lot.
edit:
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option>" + "<?php include 'vehicledbconnect.php'; $queryveh = mysql_query('SELECT * FROM vehicletbl'); while($fetch_2 = mysql_fetch_array($queryveh)) { $brand = $fetch_2['vehbrand']; $name = $fetch_2['vehname']; <option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option> }?>";
Can this be the solution? I've tried but it's not working, if this can be the solution, maybe there's only something wrong with my code here.
The only way to retrieve values from a server from javascript is to use AJAX.
Well you can do it without AJAX if you don't mind a page refresh, but I don't think that is what you want.
I would use a jQuery load function. This is the simplest example I can muster up for you.
You will need to download jQuery (http://docs.jquery.com/Downloading_jQuery) and include it in your html header:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
Then you can make a simple function to call; either as a onclick or onchange depending on your preference.
function reloadDropDown()
{
document.getElementById('dynamicInput').innerHTML = 'Loading ...';
var v_name = document.formname.elementname.value;
$('#dynamicInput').load("dropdownload.php", { vehicle_name : v_name });
}
Let me go through this. dropdownload.php would have your '$queryveh' made drop down code. Javascript basically plonks whatever happens in dropdownload.php on to a div with the id 'dynamicInput' When javascript loads dropdownload.php it sends via POST a variable by the name vehicle_name which you can use as $_POST['vehicle_name'] within dropdownload.php.
So, dropdownload.php may look something like this.
<?php
$queryveh = mysql_query("SELECT * FROM vehicletbl WHERE vehname = '{$_POST['vehicle_name']}'");
// collect the data and put it in to an Array I like to do this so I can check the array to make sure it has something in it if not return an error message but I will skip that for the purpose of this explanation.
while($ucRow = mysql_fetch_array($queryveh, MYSQL_ASSOC)) array_push($resultsArray, $ucRow);
?>
<select name = "vehicle[]" id = "vehicle1">
<?php
foreach ($resultsArray as $fetch_row){
?>
<option value = "<?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname'].'; ?>"><?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname']; ?></option>
<?php } ?>
</select>
?>
I'm not entirely certain on the end result you are after but that is a basic jQuery ajax call. If you can grasp that, you are half way to a truly dynamic web page / app with some further practice with this area. Hope that gives you a direction to go in :)
JavaScript gets evaluated on the client ..so like Html ..so it is to be used the same way.
-> yes, you just use php in your javascript as long as its defined to be evaluated by php first (usually within a .php file)
edit:
just to clarify, if you want to get values within javascript from the server by php.. you need to have a look at what danishgoel said: Ajax (Asynchronous JavaScript) ..see - since Rikudo Sennin disrespected the link, another http://en.wikipedia.org/wiki/XMLHttpRequest ..or even better have a look at a javascript framework that does most of the stuff for you (f.e. jQuery)

Categories