Have error of syntax but don't know where - php

Well, i have a table generator, with the data of mysql db.
First, the code:
PHP
while($result = mysqli_fetch_assoc($SQL)){
$tbl->addCell("<p onBlur = 'editTable(" . $result['id_user'] . ", this, 'Name')' contentEditable = 'true'>" . $result['Name'] . "</p>");
$tbl->addCell("<p onBlur = 'editTable(" . $result['id_user'] . ", this, 'Username')' contentEditable = 'true'>" . $result['Username'] . "</p>");
$tbl->addCell("<p onBlur = 'editTable(" . $result['id_user'] . ", this, 'Email')' contentEditable = 'true'>" . $result['Email'] . "</p>");
$tbl->addCell("<p onBlur = 'editTable(" . $result['id_user'] . ", this, 'Grade')' contentEditable = 'true'>" . $result['Grade'] . "</p>" );
$tbl->addCell("<input type = 'button' class = 'Edit-TBB' value = 'Edit'>
<input type = 'button' class = 'Delete-TBB' value = 'Delete'>");
$tbl->addRow();
}
AJAX
function editTable(id, new_text, column) {
$.ajax({
url: "../PHP/Configuracion/edit_grade.php",
type: "POST",
data: 'id='+id+'&text='+new_text.innerText,
success: function(data){
alert(column);
}
});
}
Here is the problem:
I have this 'editTable(" . $result['id_user'] . ", this, 'Name')'
In Chrome, it show me this
if i change the code in Chrome like this ... It works, but i don't know what i need to change at the code editor.
What i need to change?
THANKS!

You have to use double quotes for your onBlur value since you are using single quotes to denote a js string as a parameter. To do this, you need to escape a double quote in your php. So change the addCell calls to look like:
addCell("<p onBlur=\"editTable(" . $result['id_user'] . ", this, 'Name')\" contentEditable = 'true'>");

Related

I need to refactor this php function

I need to refactor this code, Im not a php developer so i dont understand the syntax thats apparent here, what i want is this button to activate the moment the page is loaded.
<?php
$h = '';
if ($newsermonstomove) {
foreach ($newsermonstomove as $vettel) {
$h .= "<div style=\"padding: 5px;\">";
$h .= "<button id=\"btn_" . $vettel->ID . "\" class=\"btn btn-primary btn-xs\" onclick=\"doMe(" . $vettel->ID . ");\" >s3</button><span style=\"padding-left:5px;\">Channel: " . $vettel->ChannelID . ", Sermon: " . $vettel->ID . " " . $vettel->SermonTitle . "</span> <div style=\"display:none;color:blue;\" id=\"msg_" . $vettel->ID . "\"></div><br/>";
$h .= "</div>";
}
} else {
$h = "<h3>No new sermons.</h3>";
}
echo $h;
?>
From what i understand, the onclick has an escape in it onclick=\"doMe(" . $vettel->ID . ");\" In HTML i know that with a button if you do onclick=doMe its a reference to a function, which i feel like is the same thing thats happening here with the escape keys in it. its making a reference to the function doMe, but i want the function to fire automatically when the page loads.
Ok, i was able to figure out the answer I needed using JQuery.
$("document").ready(function() {
setTimeout(function() {
$(".btn").trigger('click');
},10);
});
essentially what this function does is wait for the page to load then after 10 milliseconds it targets all buttons on the screen with the class name btn and triggers the click functionality of the button, thus firing off the button on the page load.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<?php
if (!empty($newsermonstomove)) {
$h = '';
foreach ($newsermonstomove as $vettel) {
$h .= '<div style="padding: 5px;">';
$h .= '<button data-id="' . $vettel->ID . '" class="btn-vettel btn btn-primary btn-xs">s3</button><span style="padding-left:5px;">Channel: ' . $vettel->ChannelID . ', Sermon: ' . $vettel->ID . ' ' . $vettel->SermonTitle . '</span> <div style="display:none;color:blue;" id="msg_'.$vettel->ID.'"></div><br/>';
$h .= '</div>';
}
} else {
$h = '<h3>No new sermons.</h3>';
}
echo $h;
?>
<script>
$(function() {
$('.bt-vettel').on('click', function(e) {
var id = $(this).data('id');
doMe(id);
});
});
<script>

Single jQuery to update multiple elements

I have the following jquery statement:
$("#add").click(
function(event){
var groupName = $("#groupName option:selected").text();
var studentsToAdd = $('select#mainList').val();
var mode = "exempt";
$.post(
"addToList.php",
{ studentsToAdd: studentsToAdd, mode: mode },
function(data) {
$('#groupList').html(data[exemptList]);
$('#mainList').html(data[nonexemptList]);
}
);
});
With the following php code:
$studentsToAdd = $_REQUEST['studentsToAdd'];
$arrayLength = count($studentsToAdd);
$exemptList = "";
$nonexemptList = "";
for ($i=0;$i<$arrayLength;$i++){
$result = mysql_query("UPDATE students SET exempt=1 WHERE id = '$studentsToAdd[$i]'");
}
$result = mysql_query("SELECT * from students WHERE exempt = 1");
while($row = mysql_fetch_array($result))
{
$exemptList = $exemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$result = mysql_query("SELECT * from students WHERE exempt = 0");
while($row = mysql_fetch_array($result))
{
$nonexemptList = $nonexemptList . "<option value=\"" . $row['id'] . "\">" . $row['last'] . ", " . $row['first'] . "</option>";
}
$data = array(
'exemptList' => $exemptList,
'nonexemptList' => $nonexemptList
);
echo json_encode($data);
I am trying to update both mainList and exemptList select elements with the single jQuery .post. It is not working. Thoughts?
If your php code is in another page or in a function, which you haven't mentioned, return $data instead of return json_encode($data) should work and leave it as an array. Otherwise you are getting a json string back, from json_encode(), which you need to parse into a javascript object, so try:
var decoded = $.parseJSON(data);
$('#groupList').html(decoded.exemptList);
$('#mainList').html(decoded.nonexemptList);
At least from what i can tell at first glance and 11 pm.
Edit: You can always try console.log(data) with Firefox Firebug plugin and see what you are getting from the server and then see if you need to decode what you are getting, change how you write the array or quotes or whatever.
A possible solution is to decode the JSON object when it is returned. Additionally, the stuff inside the [] needs to have quotes around it:
function(data) {
var json = JSON.parse(data);
$('#groupList').html(json["exemptList"]);
$('#mainList').html(json["nonexemptList"]);
}
Also, maybe try $.ajax, and set dataType to json (even though the default is intelligent guess, which should work anyway since the PHP is sending a JSON object.)
Maybe you could try:
function(data) {
$('#groupList').html(data["exemptList"]);
$('#mainList').html(data["nonexemptList"]);
}
exemptList and nonexemptList were probably treated as variables instead of names.

About the evil of eval: How to clean up

I'm building a site that will (eventually) be the front-end for a game. I want to be able to dynamically build a list of "powers" that the user is able to purchase. In order to build these lists, I'm using a PHP-based SQL query, then passing it to Javascript for dynamic choices (some powers have prerequisite powers).
I know there's a simpler way to do what I'm doing, but I'm not super concerned with that right now (I will be later, but I'm trying to get this functional and then clean) (again, I know this is non-optimal).
I'm using eval to parse which divs to show, and I want to know how not to.
I'm having issues getting my div names built right in the first place.
Here's my code:
Javascript (separate file)
function upgradeList(passed)
{
var PowerArray = [];
var DetailPowerID = [];
var EscapedPowerID = [];
PowerArray.push([]);
PowerArray = eval(passed);
var OutputThing="";
for (i=0;i<PowerArray.length;i++)
{
DetailPowerID[i] = 'detail' + PowerArray[i][0];
EscapedPowerID[i] = "'" + DetailPowerID[i] + "'";
}
for (i=0;i<PowerArray.length;i++)
{
OutputThing = OutputThing + "<br><a href='#' onClick='showUpgradeDetails(" + DetailPowerID[i] + ")'>" + PowerArray[i][2] + "</a><div class='hidden' id='" +
DetailPowerID[i] + "'>" + PowerArray[i][3] + "</div>"; }
document.getElementById("secondUpgrade").innerHTML=OutputThing;
document.getElementById("secondUpgrade").style.display='block';
}
}
PHP writing HTML and JS:
{$AbleToUpgrade and $UpgradeList are both 2d arrays built from SQL queries)
echo "<script name='UpgradeList'>";
settype($UpgradesListSize[$i],"int");
for ($i=0;$i<count($AbleToUpgrade);$i++)
{
echo "var UpgradeList" . $AbleToUpgrade[$i][0] . " = new Array();";
for ($j=0;$j<=$UpgradesListSize[$i];$j++)
{
echo "UpgradeList" . $AbleToUpgrade[$i][0] . ".push(Array('"
. $UpgradeList[$i][$j][0] . "', '"
. $UpgradeList[$i][$j][1] . "', '"
. $UpgradeList[$i][$j][2] . "', '"
. $UpgradeList[$i][$j][3] . "', '"
. $UpgradeList[$i][$j][4] . "'));";
}
}
echo "</script>";
... and, later...
echo "<div id='SpendUpgrade'>
Select power to upgrade:
<ul>";
for ($i=0;$i<count($AbleToUpgrade);$i++)
{
echo "<li><a href='#' name='UpgradeList" . $AbleToUpgrade[$i][0] . "' onClick='upgradeList(this.name)'>" . $AbleToUpgrade[$i][1] . " - " . $AbleToUpgrade[$i][2] . "</a></li>";
}
echo "</select>
<div id='secondUpgrade' class='hidden'>
</div>
<div id='thirdUpgrade' class='hidden'>
</div>
</div>";
When I load the page, I wind up with generated text like this:
Real Armor
and the corresponding div:
<div class="hidden" id="detail21" style="display: none;">Your armor only works in the Waking</div>
In order to get the div to show (display:block;), I need to call the function like so:
showUpgradeDetails("detail21")
but I can't make JS / PHP write the quotes correctly. Help (with any or all of this?) please!
I found a resolution, and it wasn't JSON.parse().
I changed PowerArray = eval(passed); into PowerArray = window[passed];.
Because passed contains the name of a variable, and is not the variable itself, I couldn't work directly with it. However, because it was a string that held exclusively the name of a globally-defined variable, I could pass it to the window[] construct and have it work.

Creating Div using Zend_Form?

I want to hidden/store dynamically generated div inside parent div.I have taken the following piece of code from my form page.
....
$existing_billing_address = array();
if (count($all_addr) > 0) {
$hidden_existing_addr_div = '';
foreach ($all_addr as $addrvalue) {
$existing_billing_address[$addrvalue['address_id']] = $addrvalue['address1'];
$exname = $addrvalue['address_name'];
$exaddress1 = $addrvalue['address1'];
$exaddress2 = $addrvalue['address2'];
$excountry = $addrvalue['country'];
$exstate = $addrvalue['state'];
$excity = $addrvalue['city'];
$exzipcode = $addrvalue['zipcode'];
$exphone = $addrvalue['phone'];
$exaddress_id = $addrvalue['address_id'];
$hidden_existing_addr_div .= "<div id='selectBilling_" . $exaddress_id . "' style='display:none'>";
$hidden_existing_addr_div .= $exname . "||" . $exaddress1 . "||" . $exaddress2 . "||" . $excountry . "||" . $exstate . "||" . $excity . "||" . $exzipcode . "||" . $exphone . "||" . $exaddress_id;
$hidden_existing_addr_div .= "</div>";
}
}
....
This will generate some thing like below,
> <div style="display: none;" id="selectBilling_40">Dinesh
> billing||billing add1||Billing
> add2||IN||TA||Chennai||625001||1234567891||40</div><div
> style="display: none;" id="selectBilling_41">kumar shipping||shipping
> add1||shipping add2||US||CA||chennai||72944||1234567891||41</div>
I want to store the above hidden div using zend_form.
Kindly help me on this.
Well, in this case you can use a Zend_Form, hidden it and then store its values so you can make validation too.
If you want to display it as a div, you can change how it looks using Zend_Decorator. Anyway, you don't need to hide every element, you can just hide the whole form.
I have used hidden text box, Using jquery i ve taken the hidden text box value and create DIV with that content and clear the input box value.
$(function(){
var val = $('#edit_existing_billingaddr').val();
$('#edit_existing_billingaddr').after('<div>'+val+'</div>');
$('#edit_existing_billingaddr').val('');
});
But i am not use zend completely here.

PHP: $_POST["startId$i"]) != ""

I am trying to process a form that is dynamically created and therefore varies in length. The while loop seems to work fine. However, the 'if' statement is not; it should only print the startId$i and corId$i if and only if the form's particular text field was filled in. The code is printing a line for every text field on the form, regardless of if it was left empty or not.
$i = 0;
while(!is_null($_POST["startId$i"])){
if(($_POST["startId$i"]) != ""){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
$i = 0;
while(isset($_POST["startId$i"])){
if( !empty($_POST["startId$i"]) ){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}
Can you manage with fields names ?
If yes, better way is to name inputs with name="startId[0]" and name="corId[0]" and so on...
Then in PHP you just do:
$startIds = $_POST['startId'];
$corIds = $_POST['corId'];
foreach ( $startIds as $k => $startId ) {
if ( !empty($startId) ) {
$corId = $corIds[$k];
echo "startId: " . $startId . " ---<br>";
echo "corId: " . $corId . " ---<br>";
}
}
You should use empty() in this case:
if(!empty($_POST["startId$i"])) {
...
}
I suggest to check the real content of $_POST. You can do that via var_dump($_POST);
You may find out, for example, that the empty fields contain whitespaces. In that case the trim() function may help.
For example:
while(isset($_POST["startId$i"])){
if(trim($_POST["startId$i"])){
echo "startId: " . $_POST["startId$i"] . " ---<br>";
echo "corId: " . $_POST["corId$i"] . " ---<br>";
}
$i++;
}

Categories