I'm trying to catch the correct variable in this jQuery function but whatever the button I click, the alert always shows the name of the first label that I have. Any ideas? Thank you.
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function() {
var name = $("#name").val();
alert(name);
});
});
</script>
</head>
<body>
<?php
include("connection.php");
$link=connect();
$result=mysql_query("select * from names",$link);
if (mysql_fetch_array($result) == 0)
{
echo "No names registered. Add one";
}
else
{
while($row=mysql_fetch_array($result))
{
echo "<html>
<label>".$row["name"]."</label>
<input type='button' class='submit' value='Delete'>
<input type='hidden' id='name' value=".$row["name"].">
<br>
</html>";
}
mysql_free_result($result);
mysql_close($link);
}
?>
</body>
</html>
Use DOM navigation to get the value from the adjacent input:
$( document ).ready(function() {
$(".submit").click(function() {
var name = $(this).next().val();
alert(name);
});
});
Also, there should just be one <html> block in the page. Don't put that in the loop.
At first, html ID should be unique.
Try using html5 data attributes and remove your hidden form element:
while($row=mysql_fetch_array($result))
{
echo "<input type='button' class='submit' value='Delete' data-value=".$row["name"].">";
}
And JS part:
<script type="text/javascript">
$( document ).ready(function() {
$(".submit").click(function() {
alert($(this).data('value'));
});
});
You are re-using the same id - name - multiple times:
while($row=mysql_fetch_array($result))
{
echo "<html>
<label>".$row["name"]."</label>
<input type='button' class='submit' value='Delete'>
<input type='hidden' id='name' value=".$row["name"].">
<br>
</html>";
}
You should wrap your fields in individual forms (not html elements) and use the name attribute:
while($row=mysql_fetch_array($result))
{
echo "<form action='' method='post'>
<label>".$row["name"]."</label>
<input type='button' class='submit' value='Delete'>
<input type='hidden' name='name' value=".$row["name"].">
<br>
</form>";
}
This will make your form also work without javascript.
Then, in your javascript you can do:
$(".submit").click(function(e) {
e.preventDefault();
var name = $(this).closest('form').find('input[name="name"]').val();
...
Or if you need to post it using ajax afterwards:
var data = $(this).closest('form').serialize();
(or you catch the submit event of the form instead)
In addition to some of the other answers, you don't really need the hidden input. Could just change the button input to:
<input type='button' class='submit' name='".$row["name"]."' value='Delete'>
Then change your JQuery selector to:
var name = $(this).attr('name');
Related
Hi i've searched alot in Internet about accessing html tag using Jquery if the html tag's id or Class have string and php variable for Example:
<input type='button' value='Save' class='btn btn-warning clicked' id="id_<?php $value1["ID"] ?>" />
Normally if i havn't a php variable inside the HTML id or class would be in Jquery like that:
$(document).ready(function (e) {
$("#id").on('click', function () {
//some code
});
});
with any help i'll be Thankful.
$(".clicked").click(function() {
alert("Button #"+$(this).attr("id")+" was pressed!");
});
Try this.. you just need to use this to get to know which button was pressed
You can achieve this by not encoding data into the id but instead adding a data- attribute:
<input type='button' class='idbutton' data-id='<?php $value1["ID"] ?>'>
and then
$(".idbutton").click(function() {
var id = $(this).data("id");
});
html :
<input type='button' value='Save' class='btn btn-warning clicked newClassName' data-id="id_<?php $value1["ID"] ?>" />
Jquery:
$(".newClassName").on("click",function(){
var id = $(this).attr("id");
//Here you get the id also and you can do the processing.
})
Try this:
your input:
<input type='button' value='Save' class='btn btn-warning clicked' id="id_<?php echo $value1 ?>" />
JS code:
$(document).ready(function (e) {
$("#id_<?php echo $value1 ?>").on('click', function () {
//some code
console.log('clicked');
});
});
where $value1 is your php variable
EDITED
Example: on php file index.php I've tested below code and it's working
<?php
$value1 = 35;
?>
<!DOCTYPE html>
<html>
<head>
<title>Hello</title>
</head>
<body>
<input type='button' value='Save' class='btn btn-warning clicked' id="id_<?php echo $value1 ?>" />
<script type="text/javascript" src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function (e) {
$("#id_<?php echo $value1 ?>").on('click', function () {
//some code
console.log('clocked');
});
});
</script>
</body>
</html>
I cant seem to find the answer for this one. I need to grab a PHP variable and insert it into javascript.
Here is an example of what I have in the body of a PHP page:
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php Print($info); ?>";
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<?php
$info="some info";
?>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
So the problem is that the alert pops up but doesn't echo the $info string. Obviously i'm missing the right way to grab a PHP variable. Please help.
If the php variable is visible inside the inner HTML, you could do something like this to grab the variable:
HTML:
<span class="variable-content"><?php echo $variable; ?></span>
jQuery:
var php_variable = $(".variable-content").text();
alert(php_variable);
Change:
alert(info);
to:
alert('<?php echo "some info"; ?>');
It looks to me like you are declaring the variable after you use it. So there is nothing in $info.
try:
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php echo $info; ?>";
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
try this
<!DOCTYPE html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<span id="info" hidden><?php
$info="some info";
echo $info;
?></span>
<form id="frm1" method="post">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = $("#info").text();
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
</body>
</html>
Primary issue with your example code
All of the PHP executes ahead of the JS. PHP executes, then outputs Your HTML and JS to the browser where they are rendered/executed/etc.
As such, your Print of $info is executing before your declaration and definition of $info. You need to define it, then output it.
Further issues you should consider
Once this is solved, you'll eventually run into issues with simply spewing data into the middle of JS. It is not easily maintained, and unprepared data will eventually break your JS syntax. When I have to do such a thing, I generally separate the two as much as possible:
<?php
// declare and define the data
$info = "foo";
?>
<script>
// prepare an IIFE which takes the data as a param
(function (info) {
// inside this function body you can use the data as you
// please without muddling your JS by mixing in PHP
alert(info);
}(
// in the invoking parens, output encoded data
<?= json_encode($info) ?>
));
<script>
Another benefit of this approach is that you can pass any PHP data structure to JS without changing the approach in any way. (As opposed to using inputs or element texts where you'd need to parse the JSON and keep track of which elements contain which values)
If you don't want to use JQuery you could put the php value into a hidden input and get it from the hidden variable with JavaScript documentGetElementById... that way you can keep your script in the head, which seems to meet your requirements. Either the hidden span as per #Miko or:
<input type="hidden" id="php_info_data" name="php_info_data" value="<?php echo $info; ?>" />
and in your header script which executes after the body has loaded:
var info = documentGetElementById('php_info_data').value;
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
var info = "<?php echo($info); ?>";
alert(info);
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(info);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
Try this
var info = "<?php echo $info; ?>";
try this
<?php
$info="some info";
?>
<script type="text/javascript">
$(document).ready(function(){
$('#button').click(function() {
$.post($("#frm1").attr("action"), $("#frm1").serialize(), function () {
alert(<?php echo $info;?>);
});
});
});
</script>
<form id="frm1" method="post" action="somepage.php">
<input name="Text1" type="text" />
<input id="button" type="submit" value="submit" />
</form>
you can convert PHP variable to JSON and then send it Javascript, becoz JSON
is supported by all language
Example
var a=<?php echo json_encode($info); ?>
alert(a);
or simply
var a=<?php echo $info; ?>
alert(a);
<?php $info=10; ?>
<script>
var a=<?php echo $info; ?>;
var a1=<?php echo json_encode($info+10); ?>;
alert(a);
alert(a1);
</script>
Iam having a small issues with my dynamic form in javascript. when i click add supplier button, two form fields are added automatically. i can add how much fields ever i wanted. But when i click add supplier button the previously added form values are going off. What's the mistake iam doing?
<html>
<head>
<script type="text/javascript">
function addTextArea(){
var div = document.getElementById('div_quotes');
div.innerHTML += "<input type='text' name='sup_name[]' />";
div.innerHTML += "<input type='text' name='sup_email[]' />";
div.innerHTML += "\n<br />";
}
</script>
</head>
<body>
<form method="post" action="ajax.php?tender_id=<?php echo $tender_id ?>">
<div id="div_quotes"></div>
<input type="button" value="Add Supplers" onClick="addTextArea();">
<input type="submit" name="submitted">
</form>
</body>
</html>
Use appendChild() instead of innerHTML that will prevent the existing form elements from getting overwritten.
function addTextArea(){
var div = document.getElementById('div_quotes');
var temp = document.createElement('div');
temp.innerHTML ="<input type='text' name='sup_name[]' /><input type='text' name='sup_email[]' /><br />";
div.appendChild(temp );
}
I have a below PHP code to pass TextArea value to call another PHP page using button onclick. When I type some chars in the text area and click on the button, it does not take value to the mspec parameter.
echo "<TEXTAREA name=Tranrules cols=100 rows=5></TEXTAREA>"
echo "<INPUT TYPE=BUTTON VALUE=\"Add Mapping\"
onClick=\"javascript:JSopenReportWindow('sample8.php?mspec=$Tranrules');\" style=\"color:black; width:153px;\">";
Javascript is below
<script language="JavaScript">
function JSopenReportWindow(URL) {
popupWin = window.open(URL, 'Report',
'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=1,resizable=1,width=675,height=600');
popupWin.focus(); // bring window to front
}
</script>
here is a little sample of what you should be doing instead:
<script>
function popup(name){
var text = document.getElementsByName(name)[0].value;
alert(text);
}
</script>
<textarea name="Transrule"></textarea>
<input type="button" value="submit" onClick="javascript:popup('Transrule');" />
When You echo the HTML, it is HTML, so You cant access element's value by adding $ to name, You should use ID instead of Name and access it the right way.
http://jsfiddle.net/bE84a/
echo "<TEXTAREA id=Tranrules cols=100 rows=5></TEXTAREA>"
echo "<INPUT TYPE=BUTTON VALUE=\"Add Mapping\"
onClick=\"javascript:JSopenReportWindow('sample8.php?mspec='+document.getElementById('Tranrules').value);\"
style=\"color:black; width:153px;\">";
I have this form into PHP pages:
echo "<form action=\"xxx.php\" method=\"post\" id=\"test\" name=\"test\">
<input type=\"submit\" name=\"oooo\" value=\"Sincronizza\">
</form>";
On top I have this JavaScript for automatic submit:
<script type='text/javascript'>
<!--
function send() {
var objForm = document.getElementById('test');
objForm.action='xxx.php';
objForm.submit();
}
window.setTimeout('send()', 5000)
//-->
</script>
Unfortunately, the script start an refresh page and not an auto-submitting.
What is the problem?
Using JavaScript to submit, the value of the submit-input tag is not posted. A solution could be to include a hidden type input in the form:
<input type="hidden" name="oooo" value="Sincronizza">