I'm trying to create an Edit Modal. Provided that I have the html code for this, I write this javascript/jquery code:
<script type='text/javascript'>
$(function() {
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
while($r = $q->fetch(PDO::FETCH_ASSOC)){
echo " <script type'text/javascript'> alert('1');</script>";
$unitID = $r['unitID'];
$unitStatus = $r['unitStatus'];
$unitNumber = $r['unitNumber'];
$floorNumber = $r['floorCode'];
$unitType = $r['unitType'];
$t = $db->query("select floorLevel, floor_buildingID from tblFloors where floorLevel = '$floorNumber'");
while( $u = $t->fetch(PDO::FETCH_ASSOC)){
$floorLevel = $u['floorLevel'];
$floor_buildingID = $u['floor_buildingID'];
$w = $db->query("select unitTypeName from tblUnitType where unitTypeID = $unitType");
while($x = $w->fetch(PDO::FETCH_ASSOC)){
$unitTypeName = $x['unitTypeName'];
?>
$("#editModal<?php echo $unitID; ?>").click(function(){
$("#editUnitNumber").val("<?php echo $unitNumber;?>");
$("#editUnitType").val("<?php echo $unitType; ?>").material_select('update');
$("#editFloorNumber").val("<?php echo $floorNumber; ?>");
});
<?php }}}?>
});
The code above is used to write the data from the modal, but instead it output this:
$("#editModal5").click(function(){ $("#editUnitNumber").val("12002"); $("#editUnitType").val("4").material_select('update'); $("#editFloorNumber").val("12"); }); });
How do I solve that? What causes this?
Use json to pass data from php to javascript, instead of echoing everything out in one place. It may seem an overkill but it's readable, and is more beneficial on the long run.
The code below is not tested, but it should give you a general idea on how to approach these things. I did not include the second and third queries within the first while loop. You can nest the results from those queries in the $unit array and access the relevant data via additional loops in javascript.
Also, ideally you wouldn't just echo out the decoded array right after the php, a better solution would be to call a function in the footer, that would generate a script tag with all data that is used by javascript. Another approach is to use AJAX and get a json response only when you need it, then you would feed that same json to the loop.
<?php
$q = $db->query("select * from tblUnit where unitStatus <> '2'");
$units = [];
while($r = $q->fetch(PDO::FETCH_ASSOC)){
$unit = [
'unitID' => $r['unitID'],
'unitStatus' => $r['unitStatus'],
'unitNumber' => $r['unitNumber'],
'floorNumber' => $r['floorCode'],
'unitType' => $r['unitType']
];
$units[] = $unit;
}
$units_json = json_encode($units);
?>
<script type='text/javascript'>
$(function() {
var units = '<?php echo $units_json ?>';
var units_array = JSON.parse(units);
// do some validation here
for (var i = 0; i < units_array.length; i++) {
// do some validation here
$("#editModal" + units_array[i].unitID).click(function(){
$("#editUnitNumber").val(units_array[i].unitNumber);
$("#editUnitType").val(units_array[i].unitType).material_select('update');
$("#editFloorNumber").val(units_array[i].floorNumber);
});
};
});
</script>
Related
What I want:
A list of links show events - a click on such a link shall show further details in a special DIV on the same page.
Idea:
I read from the database all events:
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
This gives me all available events in the DB that are not yet processed.
I assgin all found events identified by their UUID into a PHP array for further processing
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i",
$eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
Having that 2-dimensional array "eventInfo" I build the list
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
Last but not least I create a DIV to store the desired eventBody-Information:
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
To populate now the DIV when a link is clicked I tried this:
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
I wanted to pass the php-Array with JSON to make it available inside the function.
With the click-effect I wanted to load from this php-array the related array-element ['eventBody'] with the UUID given by the link-click.
Somehow I am stuck. I am able to pass the UUDI key to the javascript area and can write it into the DIV but I cannot identify a php-element by the given UUID and put the content into the DIV.
Any hint is appreciated, thank you.
As requested here is the code in total:
<?php
// Including jQuery
echo '<script src="http://code.jquery.com/jquery-1.11.3.min.js">/script>';
// Querying the Neo4J DB
$queryEventString = 'Match (e:Event) WHERE e.eventStatus = "not_processed"
RETURN e.UUID as eventUUID,
e.eventFrom as eventFrom,
e.eventType as eventType,
e.eventTime as eventTime,
e.eventSubject as eventSubject,
e.eventBody as eventBody';
$resultEvent = $client->run($queryEventString);
// Parsing result and build the 2-dimensional array $eventInfo
foreach ($resultEvent as $eventDetail)
{
$eventInfo[$eventDetail['eventUUID']]['eventBody'] = html_entity_decode($eventDetail['eventBody']);
$eventInfo[$eventDetail['eventUUID']]['eventForm'] = $eventDetail['eventFrom'];
$eventInfo[$eventDetail['eventUUID']]['eventDate'] = date("d.m.Y H:i", $eventDetail['eventTime']);
$eventInfo[$eventDetail['eventUUID']]['eventSubject'] = $eventDetail['eventSubject'];
}
// Displaying list of events with UUID as forwarded parameter (-> JS)
echo '<div class="event-panel">';
echo '<ul id="event-column" style="list-style: none;">';
foreach($eventInfo AS $eventKey => $eventDetail)
{
echo '<eventlink data-id="'.$eventKey.'">'.$eventKey.'</eventlink><br>';
}
echo '</ul>';
echo '</div>';
// Creating a DIV Container to hold $eventInfo[eventUUID][eventBody]
echo <<<EOT
<div id="info-div">
<div id="info"></div>
</div>
EOT;
// JavaScript Part
echo <<<EOT
<script type="text/javascript">
$(document).ready(function (){
var passedArray = <?php echo json_encode($eventInfo); ?>;
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
$('#info').html().passedArray[p];
});
});
</script>
EOT;
?>
2nd EDIT:
I have stripped down everything to this functioncode, which is at the end of the php-file and no longer wrapped in the php-tags. So its like standard html. This way I avoid the uncaught syntax error.
<script type='text/javascript'>
$(document).ready(function (){
var passedArray = '<?php echo json_encode(array($test_array)); ?>';
console.log(passedArray);
$('#event-column eventlink').click(function (){
var p = $(this).attr('data-id');
console.log(p);
console.log(passedArray[p]['eventBody']);
$('#info').text(passedArray[p]);
});
});
</script>
Outcome:
I can console.log the array, which shows as a test:
[[{"UUID":"60762d3eb9949596701a2dfb700cd2c9","eventBody":"Hallo"},{"UUID":"620c16ced5097bf60f718abca7d979f8","eventBody":"Ciao"}]]
I see also that when I click a link that the UUID key is passed to the Javascript-Script:
60762d3eb9949596701a2dfb700cd2c9
But when I want to assign the related eventBody-element I receive this error:
Uncaught TypeError: passedArray[p] is undefined
As I have the array and the key I assume it must be a syntax error in this line:
console.log(passedArray[p]['eventBody']);
So two questions left:
How would I access one element of the given array?
How can I then populate the DIV with the element ['UUID']['eventBody']? Not sure if this is the way to go: $('#info').html().passedArray[p];
Resolution (with Uwe's help):
function findme(p) {
var passedArray = '<?php echo json_encode($test_array); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
thanks to your support here (Kudos to Uwe) here is the solution:
As we use jQuery we need to include this in the head:
echo '<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.3.min.js"></script>';
The Javascript-Function (written in HTML, not in PHP tags):
function findme(p) {
var passedArray = '<?php echo json_encode($eventInfo); ?>';
passedArray = JSON.parse(passedArray);
// here we search that object in your array which has the key value pair of
// UUID : p
var result = passedArray.find((obj) => {
return obj.UUID === p;
});
document.getElementById("result").innerHTML = result.eventBody;
}
I was not able to find a way to write the whole code within PHP tags, as the double echo (Start and inside the array handover) and the additional PHP?-tags always generates syntax errors - thus the JS function is written as HTML-code outside the PHP code.
In the PHP the UUID of the array is passed onClick to the JS function - looks like
echo ' Find the element by UUID Brackets -- '.$UUID.'';
Please pay attention to the escaped quotation marks - important to avoid an error in JS that allows no identifiers starting with a number.
The DIV is marked by
echo '<p id="result"></p>';
For testing I made an array like this:
$eventInfo= array();
$eventInfo[] = array('UUID' => '60762d3', 'eventBody' => 'Text 1');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 2');
$eventInfo[] = array('UUID' => '6076299', 'eventBody' => 'Text 3');
$eventInfo[] = array('UUID' => '620c16c', 'eventBody' => 'Text 4');
i'm currently learning javascript through my school and I'm completely stuck on trying to make a search form work.
The problem I have is that I can't get it to show all results from the sql query.
The code looks like this:
$(document).ready(function(){
var searchfield = document.getElementById("searchfield");
var searchresult = document.getElementById("searchresult");
$(searchfield).on("keyup", function(){
var q = this.value;
console.log(q +"'This value'");
var str = "";
var url = "searchscript.php?q="+q;
$.ajax({
url:url,
type:'post',
dataType: 'json',
success: function(resultat){
console.log("resultatet är:" + resultat.ProduktNamn);
for(var i = 0; i < resultat.ProduktNamn.length; i++) {
str += resultat.ProduktNamn + "<br>";
}
searchresult.innerHTML = str;
}
})
});
});
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
while ($row = $resultat->fetch_assoc()) {
echo json_encode($row);
}
}
?>
As soon as the result of the query has more than 1 property, no matter how I do it it won't show any results, only when I narrow down the search so that only one product is found it shows it.
I'm new to javascript, but I'm pretty sure this has to do with the fact that the way I'm doing it on the PHP side makes it so it returns every product as a single object, not within an array or anything, so when I get the data back on the javascript side I have trouble looping through it.
So basically, say I have these products
"Banana Chiquita"
"Banana Chichi"
"Banana"
I will only get a result on the javascript side once I've written atleast "Banana chiq" in the search field so the php side only returns 1 object.
Sorry for my terrible explaination :/
Well, first you should make a 2D array and then encode it to JSON. Currently, you are writing out each record as a JSON string which will work for a single record but not for multiple records. See the corrected PHP code.
<?php
$str = $_GET['q'];
if (!empty($str)) {
$query = "SELECT ProduktNamn FROM Produkter WHERE ProduktNamn LIKE '%$str%'";
$resultat = mysqli_query($dbconnect, $query);
$rows = array();
while ($row = $resultat->fetch_assoc()) {
array_push($rows,$row);
}
echo json_encode($rows);
}
?>
So I am trying to make a simple academic system.
I made dynamic boxes which show course information.
Core code looks like this
function addcourses(){ //(numcourses)
var num_courses= <?php echo $_GET['num']?>; //=numcourses
var newdiv;
var divIdName;
var i=0;
for(i=1;i<=num_courses;i++){
var divtoadd = document.getElementById('courselist');
newarticle = document.createElement('article');
divIdName = 'course'+i;
newarticle.setAttribute('id',divIdName);
newarticle.innerHTML ='<div class="box"><h2><?php echo $course_num_arr[i]?></h2><div class="content"><p>Credit Hours: <?php echo $credit_arr[0]?> </p><p>Professor: <?php echo $prof_arr[0]?></p><p>Average GPA: <?php echo $avg_arr[0]?></p><p>GPA: <?php echo $gpa_arr[0]?></p></div></div>';
call_course();
divtoadd.appendChild(newarticle);
}
}
The problem is with <?php echo $course_num_arr[i]?> since i is the variable from javascript, I don't know how to deal with this.
I want to echo $course_num_arr[1] when i = 1 and $course_num_arr[2] when i = 2 and so on.
If you don't want to use ajax call and wants to place the code in the PHP file, your can use json_encode() function. Please refer below code.
<?php
$cources = array( "0" => array ("name" => "maths","credits" => 30),"1"
=> array ("name" => "physics","credits" => 30));
?>
<script>
data=<?php echo json_encode($cources); ?>;
for(i=0;i<data.length;i++){
alert(data[i].name)
var h = document.createElement("H1");
var t = document.createTextNode(data[i].name);
h.appendChild(t);
document.body.appendChild(h);
}
</script>
I am working on a project that requires create hundreds of variables in javascript with PHP values. I can write each one line by line like so:
var M1 = <?php echo json_encode($$mn[0]); ?>;
var M2 = <?php echo json_encode($$mn[1]); ?>;
var M3 = <?php echo json_encode($$mn[2]); ?>;
As I said there are hundreds of these though and if it is possible to do in a loop I would be very interested in learning. I have searched all over and can't find a direct answer. It may very well be that this is not possible. I am new to coding and still learning what certain code can and cannot do.
Any insight or direction on this topic would be greatly appreciated!
If this is not an option is it possible to use an array index for the javascript variable name? I have created an array for the JS and PHP. The PHP works fine above but if I try to use an array index for the JS like below, it breaks:
var mcirc[0] = <?php echo json_encode($$mn[0]); ?>;
I have output the array and the values are coming up correctly but when I run this I get the message:
[object HTMLDivElement]
instead of the actually value that should show up.
UPDATE
$mn array:
for ($m1 = 1; $m1 < 6; $m1++) {
$mn[] = 'M'.$m1;
}
UPDATE
Select SQL creating array:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$$row["mcID"]= $row["mcName"];
}
The array for mcID looks like this:
M1 = "text1"
M2 = "text2"
M3 = "text3"
M4 = "text4"
M5 = "text5"
UPDATE
end result desired:
var M1 = "text1";
var M2 = "text2";
var M3 = "text3";
var M4 = "text4";
var M5 = "text5";
Where "text1, ...2, ...3, ...4, ...5" are coming from the MySQL database.
UPDATE
Here is the final code that got this working:
$sqlMC = "SELECT mcID, mcName FROM tblmaincircles";
$result = $conn->query($sqlMC);
while($row = $result->fetch_assoc()) {
$mcID[] = $row["mcID"];
$mcName[] = $row["mcName"];
}
<?php for ($m1 = 0; $m1 <5; $m1++) { ?>
var <?php echo $mcID[$m1]; ?> = <?php echo json_encode($mcName[$m1]); ?>;
<?php } ?>
Simply put JSON into variable
var json = <?php echo json_encode($$mn); ?>;
And then process the JSON way you want:
eg.
var json=[{key:someValue},
{key:someValue2},
{key:someValue3}
];
json.forEach(function(a){
console.log(a.key);
})
First in your query part, declare a variable to hold the result that you want. I'm assuming the M1 is mcID in your table and text1 is the mcName. For example:
$sqlMC = "SELECT * FROM tblmaincircles";
$result = $conn->query($sqlMC);
$mac = [];//or $mac = array(); Depends on your PHP version.
while($row = $result->fetch_assoc()) {
$mac[$row["mcID"]] = $row["mcName"];
}
And then, iterate through the $mac array with foreach loop. I'm assuming you are using PHP codes within HTML. The $key will be the mcID and the $value will be the mcName.
//php tag for the foreach opening
<?php foreach ($mac as $key => $value) { ?>
var <?php echo $key; ?> = <?php echo "'$value';"; ?>
//php tag for the foreach closing
<?php } ?>
OR, if you want to use javascript associative array.
var macJs = {};
<?php foreach ($mac as $key => $value) { ?>
macJs.<?php echo $key; ?> = <?php echo "'$value';"; ?>
<?php } ?>
And you can access the element like this in javascript macJs.M1.
You should use JSON to 'export' your objects/array through different languages, in that case:
var json = '<?= json_encode($your_array); ?>';
After this you can parse this Json, what should return your array:
var your_array = JSON.parse(json);
i want to pre-poulate my fullcalendar instance via a php json feed.
The page is loading fine (no 404 or sth like that) but the calendar is not showing any of the events.
generating the json:
<?php
require("../config/config.php");
$uid = $_SESSION['uid'];
$res = $db->query("SELECT * FROM slots WHERE tid = '$uid'");
$data = array();
while($row = $res->fetch_assoc())
{
$event = array();
$event['editable'] = false;
$event['id'] = "fixE_".$row['id'];
$event['title'] = getSlotStatus($row['status']);
$event['sid'] = $row['sid'];
$event['status'] = $row['status'];
$event['start'] = $row['start'];
$event['end'] = $row['end'];
$event['standby'] = $row['standby'];
if(strpos($data['status'],"_old"))
{
$event['textColor'] = '#000000';
$event['color'] = '#cccccc';
$event['className'] = 'lessonSlotOld';
}
else
{
$event['color'] = getColorCode($row['status']);
if($row['standby'])
{
$event['borderColor'] = '#0000FF';
}
}
$data[] = $event;
}
echo json_encode(array("events"=>$data));?>
and here's the part of the fullcalendar code where i am inserting the feed:
events:
{
url: 'include/fetchSlots.php',
type: 'POST',
error: function(){alert("There was an error fetching events")}
},
the json output of the php looks like the following (this is just a part because the whole response would be too much ;) )
{"events":[{"editable":false,"id":"fixE_164","title":"Slot is closed","sid":"0","status":"closed","start":"2015-06-06T04:00:00+08:00","end":"2015-06-06T04:30:00+08:00","standby":"0","color":"#B20000"}]}
Ok so here's the solution/the mistake.
The only problem that fullcalendar has is the line where the actual json is posted:
echo json_encode(array("events"=>$data));
fullcalendar doesnt want the "events" and it doesnt want the twice wrapped array. so the solution to this is simply to output the data-array directly:
echo json_encode($data);
then, the events are all loaded correctly.
ah and for all watchmen out there, yes i found the mistake with the wrong named variable ;)
if(strpos($data['status'],"_old"))
to
if(strpos($row['status'],"_old"))