I am trying to set some fields of a form with the values of an array.
I have an array like this:
Array
{
'elementID1' => Array
{
'id1' => 'some value',
'id2' => 'some value',
'id3' => 'some value',
...
}
'elementID2' => Array
{
'id1' => 'some value',
'id2' => 'some value',
'id3' => 'some value',
...
}
...
}
The array is filled with the response of a webservice to whom I sent some parameters with a form. Once I filled the array, I draw a table and iterate over the array.
<table width = "100%" border = "1">
<tr>
<th>Header 1</th>
<th>Header 2</th>
<th>Header 3</th>
<th>View details</th>
</tr>
<?php
foreach($array as $id => $detail)
{
echo "<tr>";
echo "<td>";
if(array_key_exists('id1', $detail))
echo $detail['id1'];
echo "</td>";
echo "<td>";
if(array_key_exists('id2', $detail))
echo $detail['id2'];
echo "</td>";
echo "<td>";
if(array_key_exists('id3', $detail))
echo $detail['id3'];
echo "</td>";
echo "<td>";
echo "View more";
echo "</td>";
echo "</tr>";
}
?>
</table>
Now, here comes the problem, as you can see there is a fourth column called View details, this column is filled with a hyperlink that calls a javascript function with the elementID value of the specific row as parameter.
A little more below I have the script:
<script>
function equisYe(id)
{
var equis = "<?php echo $array['" + id + "']['IncidentID']; ?>";
alert(equis);
}
</script>
When I click on the hyperlink doen't happen anything, I think the problem has something to do with the special characters inside the quote punctuations. In my browser, when I inspect one of the hyperlinks, it shows the following message inside de scripts tags:
function equisYe(id)
{
var equis = "<br />
<b>Notice</b>: Undefined index: + id + in <b>
";
alert(equis);
}
That means, for some reason, the strings aren't concatenating, and if I delete a 'p' from php tag in the equis var like this:
var equis = "<?ph echo $array['" + id + "']['IncidentID']; ?>";
Then the alert shows this:
"<?ph echo $array['10']['IncidentID']; ?>"
So, it works when it doesn't have the php tags.
The other answer is correct, but not explaining it at all (or even politely). The PHP stuff runs before your Javascript stuff does. You'll never get this to work this way, unfortunately. If it was the other way around, it might work, but this isn't going to work the way you have it.
The only way to have something like this working is to have the ID value chosen in advance and have PHP set something in Javascript. Javascript can never set a PHP value simply by virtue of PHP being run prior to the page being served and Javascript being run after the page is served.
dude... javascript executes on client(browser) and php on server; you CANNOT do that
try to use <? ?> instead of <?php ?>
Everyone is correct in that you can't simply call PHP functions from Javascript without performing some kind of HTTP request.
Since you already have the "IncidentID" in php while you're generating the page, you can simply write it to the page.
instead of
echo "<td>";
echo "View more";
echo "</td>";
do
echo "<td>";
echo "View more";
echo "</td>";
You can use data attribute to pass the $id to js, always using the DOM.
Check this: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Then use a click event in "view details" to get the data from element and trigger the function, this way you will be abble to work with it
Related
I'm trying to manipulate an amount based on the name of class that changes with jQuery. My amount comes from here:
<script>
var inboundAmount = <?php echo json_encode($inbound); ?>;
</script>
Let's just say that amount is 10.
I output with a bit of php and script like this:
echo "$<script>document.write(inboundAmount);</script>";
The class changes when a user clicks on it. Sample classes are as follows:
half first3547
pending first3547
paid first3547
What I've been trying to do is make it so that if the class contains the word 'half', then it would do some math:
document.write(inboundAmount/2);
Producing the number 5.
I've tried this and some variations with no luck:
if ($("#mycontent").find("a.half").length > 0) {document.write(inboundAmount/2);}
'mycontent' is the id for the table that a href exists in.
I have also tried the following:
if ( $( this ).hasClass( 'half' ) ) { {document.write(inboundAmount/2);}
still to no avail.
A full example is this:
<td class='grav-results-td'>
<?php if (!empty($check_inbound)):echo "<a href=\"#inbound\"
class=\"$inbound_status first$id\" onclick=\"comtype($id,'inbound',
$vendor)\">$<script>if ( $( this ).hasClass( 'half' ) )
{document.write(inboundAmount/2);}</script></a>"; endif; ?></td>
And I have also tried the manipulation in the success area of my ajax script.
Answering some of the questions below:
$inbound_status first$id is a PHP variable.
The output of document.write(inboundAmount/2); is working correctly and showing half the amount of document.write(inboundAmount);
The this scope inside your <script> tag will not point to the element you expect. Instead of checking in javascript you can check the condition in php itself. Otherwise, you can refer the code below to do it on javascript. You can use the php variable to check whether it contains the string half
echo "<td class='grav-results-td'>";
if (!empty($check_inbound)):
echo "<a href=\"#inbound\"
class=\"$inbound_status first$id\"
onclick=\"comtype($id,'inbound',$vendor)\">
$<script>if ('$inbound_status' == 'half' )
{document.write(inboundAmount/2);}
</script>
</a>";
endif;
echo "</td>";
If inboundAmount is a php variable you can do it easily without using javascript
echo "<td class='grav-results-td'>";
if (!empty($check_inbound)):
echo "<a href=\"#inbound\"
class=\"$inbound_status first$id\"
onclick=\"comtype($id,'inbound',$vendor)\">$";
if ($inbound_status == 'half'):
echo $inboundAmount/2;
endif;
echo "</a>";
endif;
echo "</td>"
I have a problem, trying to create a button with Ajax/Php which is to appear on my main page and is supposed to have a onclick function. To be more specific, I end up in a while loop, which fetches through the rows of my mySQL-table and displays the following:
echo "<table>";
while($result == true && $a <= 15){
$res = $result["uberschrift"];
echo "<tr id='$res'>";
echo "<td>".$a."</td>";
echo "<td>".$res."</td>";
echo "<td>"."<button id='b_löschen' onclick='k_löschen($res)'> löschen </button>"."</td>";
echo "</tr>";
$result = $stmt->fetch();
$a++;
}
echo "</table>";
In fact, this works quite well, and on my main page the string contained in $result["uberschrift"] is displayed properly. However, if I call the function k_löschen with $res as shown above, it will not take the String but a certain
[object HTMLTablerowElement] as input, which naturally causes an Error. Can someone tell me how to change the code so that the function actually takes the string as it's input?
You have issues with your quotes. Also you could tell us what $res typically contained.
I would do this
echo "<tr id=\"".$res."\">";
echo "<td><button id='b_löschen' onclick='k_löschen(\"".$res."\")'>löschen</button></td>";
I want to call a JavaScript function inside PHP code,This function return a number, the Result for example is : http://localhost/1.php?id=fn(3)
as you see this function cannot be interpreted by the browser I already tried ' ' or " " But I get the same problem, normally I must receive for example http://localhost/1.php?id=3
Any help on this problem would be greatly appreciated! Thank you in advance!
<body>
<script type="text/javascript">
function fn(a)
{
var table = document.getElementsByTagName("table")[0];
var res=table.rows[a].cells[0].innerHTML;
return res;
}
</script>
<table class="table " id="tableId">
<?php
$bdd = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'root', '');
$reponse = $bdd->query('SELECT * from jeux_video');
while ($donnees = $reponse->fetch()){
echo "
<tr onclick=\"location.href='1.php?id=fn($donnees[ID])'\">
";
?>
<td id="td1"><?php echo $donnees['ID']?></td>
<td><?php echo $donnees['nom']?></td>
<td><?php echo $donnees['possesseur']?></td>
<td><?php echo $donnees['prix']?></td>
</tr>
<?php } $reponse ->closeCursor(); ?>
</table>
</body>
The string you're putting on the href won't be parsed as a javascript expression, but just as a string.
You need to output a valid javascript statement for the fn call to execute:
echo "<tr onclick=\"location.href='1.php?id=' + fn(".$donnees[ID].")\">";
This will output:
<tr onclick="location.href='1.php?id=' + fn(3)">
PHP runs on the server, and Javascript on the client. That's the rule. If you want PHP to output a value anywhere in your document, you need to do it with PHP:
echo "<tr onclick=\"location.href='1.php?id=' + fn(" . $donnees[ID] . ")'\">"; // ...
As it is, this is likely the exact markup that is being output:
<tr onclick=\"location.href='1.php?id=fn($donnees[ID])'\">
Which, to Javascript, makes no sense.
This doesn't do what you think it does:
location.href = '1.php?id=fn(3)'
JavaScript isn't going to automatically evaluate code inside of a string. You have to execute the code itself and concatenate its result to the string. Something like this:
location.href = '1.php?id=' + fn(3)
I'm making this app to practice asynchronous websites, all it does is show the contents of a database table on the site in table format using jQuery and PHP.
Everything works perfectly, except I wanted to add a button on each < tr > that on click deletes the respective entry on the database, however, I can't seem to get it done. I've got through the documentation of everything I used and just don't see the problem. Here is my code:
HTML:
<div class="row">
<div class="col-lg-12" id="table_container">
<table class="table table-striped" id="result_table">
</table>
</div>
</div>
The table is created on a separate PHP file that's called by ajax, this is the relevant loop:
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['ID']."</td>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default deleteWaitlist" type="submit" name="' . $places['ID'] . '">X</button>
</td>';
echo "</tr>";
}
All buttons are created with the correct 'name' on the final html (that is an auto_increment number).
jQuery:
$(".deleteWaitlist").click(function(){
console.log("click on .deleteWaitlist");
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
console.log("success" + result);
}
});
});
As I said, kinda new to ajax. correct me if I'm wrong: this calls deleteWaitlist.php and posts a parameter 'id' with value '$(this).attr('name')' which is an auto_increment value on the database and should be diferent for every entry.
deleteWaitlist.php
$sql = "DELETE FROM waitlist WHERE id=" . $_POST[id] . "";
mysqli_query($c,$sql);
It's pretty straightforward, isn't it? Can you help me find the mistake? Maybe something like (int)$_POST[id] somewhere? I could swear I tried that everywhere.
EDIT: Strangely, Im not even getting the console log "click on .deleteWaitlist" when I click the button, as if I weren't even clicking it at all. What can be happening? I also changed the id "deleteWaitlist" for a class, since it seems to be the best practice.
Seems there is multiple delete button in your output html and jQuery matches exactly one element when querying for an ID.
Try use CLASS instead of ID on the delete button.
while ($places = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>". $places ['ID']."</td>";
echo "<td>". $places ['NAME']."</td>";
echo "<td>". $places ['CHAIRS']."</td>";
echo "<td>". $places ['CREATED']."</td>";
echo '<td>
<button class="btn btn-default deleteWaitlist" type="submit" name="' . $places['ID'] . '">X</button>
</td>';
echo "</tr>";
}
jQuery:
$(".deleteWaitlist").click(function(){
console.log("click on .deleteWaitlist");
// Get the varible name, to send to your php
var i = $(this).attr('name');
$.post({
url: 'deleteWaitlist.php',
data: { id : i},
success: function(result){
console.log("success" + result);
}
});
});
I have a php function which displays all the data in my mysql table and allows the user to delete data not needed. I managed to get the data to show in a table, get the delete button to ask for confirmation using javascript, but when i try to get the value in the 2nd cell of the table with the query result (the name) and display it on the confirmation tab, it says undefined. Why is that happening? From what i understand, document.getElementById("myText").value where myText is the id of the cell, should return the value in the cell, correct? Also, how would i call and send that value to another php file that has the delete query?
<?php
$row = mysqli_fetch_array($result);
echo "<table>";
echo "<tr class='header'><td class='header'>Delete</td>";
echo "<td class='header'>Added</td>";
echo "<td class='header'>Name</td>";
echo "<td class='header'>Genre</td>";
echo "<td class='header'>Developer</td>";
echo "<td class='header'>Rating</td></tr>";
?>
<script type="text/javascript">
function ConfirmDelete(){
var name = document.getElementById("name").value;
if (confirm("Delete" +name+"?")){
//send the value and call the php
}
}
</script>
<?php
for ($x=0; $row; $x++) {
echo "<tr><td><input type='button' onclick='ConfirmDelete()' name='deleteGame' value='DELETE'></td><td>$row[Added]</td><td id='name'>$row[Name]</td><td>$row[Genre]</td><td>$row[Developer]</td><td align='right'>$row[Rating]</td></tr>";
$row = mysqli_fetch_array($result);
}
?>
</table>