Rendered first Javascript before PHP - javascript

Assuming in PHP file there're :
function printAllRows(){
for( everyrows in db){
echo "<tr>";
echo "<td> $_POST['..'] <td>";
echo "<td> $_POST['..'] <td>";
echo "<tr>";
}
}
function printSpecifRows($keyword){
.....
}
// When the page loads for the first time
if ($db->preRow() >0){ // count rows in DB , if there already show them as table
printAllRows();
}
At the same time , there is
<input type="text" name="keywoard" />
<input type="submit" name="find" value="search" />
If the user enter the keyword press the button , then just show the rows match the keyword!
so :
if( $_POST["find"]){
?>
<script>
// first clear the current DOM table
document.getElementById("myTable").innerHTML="";
</script>
<?php
// then print again! according to printSpecifRows($keyword)
function printSpecifRows($keyword){
.....
}}
But the problem here is that JS is rendered first before PHP , so printSpecifRows($keyword) won't never be reached , any idea. I really appreciate your help. Thanks.

You are massively over-complicating things. Get rid of the <script> entirely. There is no need or point in involving JS here.
Just change the PHP so it doesn't output all the data in the first place if you don't want it on the page.
if ($_POST["find"]){
printSpecifRows($_POST["find"]);
} else {
printAllRows();
}

Related

javascript call inside php where loop not working and breaks query

I am attempting to call a javascript function inside a php where loop. I've succeeded in calling the variable, however the function only works on the first line, and then breaks a subsequent query.
The javascript is a simple show/hide of a div or span tag with a specific id. I'm trying to have this appear for every instance of a variable, but only open the span associated with that entry, so I used a php variable from the query.
The javascript code is contained in the header; it works fine without the php, and the php works fine without the javascript but I can't seem to make them work together.
Here's the code:
while($row = mysqli_fetch_array($qir)) {
$ingredient_id = $row['ingredient_id'];
echo '<input type="checkbox" value="' . $ingredient_id . '" name="markdelete[]">';
echo $row['amt'] . ' ' .$row['ingredient_name']; ?> <button onclick="showHide('<?php echo $row['ingredient_id']; ?>'); return false">Edit amount</button> <br />
<span id="<?php echo $row['ingredient_id']; ?>" class="hide">
<?php include_once('amt.php');
echo '</span> ';
// }
echo '<br />';
}
echo '<input type ="submit" name="remove" value="Remove">';
First of all, the showHide is only working on the first record
It is also making this query not respond at all.
if (isset($_POST['remove'])) {
iF (!empty($_POST['markdelete'])) {
foreach ($_POST['markdelete'] as $delete_id) {
// remove specific source from source_subject
$rem_ing = "DELETE from dish_ingredient
where ingredient_id = $delete_id
and dish_id = $dish_id ";
mysqli_query($dbc, $rem_ing)
or die ('Error removing ingredient: '.mysqli_error($dbc));
}
}
}
I tried removing the return false;, to no avail. Please let me know if I need to show more of the code (e.g. the javascript itself)
Edit:
I've tried working within the php string (this is actually what I had tried first) but it seems to break everything (no javascript, no php)
echo $row['amt'] . ' ' .$row['ingredient_name'] . '<button onclick="showHide(\''. $row['ingredient_id'] .'\') return false">Edit amount</button> <br />';
echo '<span id=" '. $row['ingredient_id'] .' " class="hide">';
include_once('amt.php');
echo '</span> ';
Edit: I am open to other solutions if this is not something that is possible. I'm feeling a bit stumped. Realistically I just want to have a list of items called from a mysql database, and have a field appear onclick to edit an associated variable if desired without having to send it to another page or reload the script for usability (hence the javascript piece).
Thanks again, anyone who can assist.
Note: this is the script that I am calling:
<script language="JavaScript" type="text/JavaScript">
menu_status = new Array();
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(menu_status[theid] != 'show') {
switch_id.className = 'show';
menu_status[theid] = 'show';
}else{
switch_id.className = 'hide';
menu_status[theid] = 'hide';
}
}
}
</script>
You don't need tag there as you are already in php block.Try it without and use
showHide(\''.$row['ingredient_id'].'\')
and change
<?php include_once(....);
to
include_once(........);
Hopefully that would work
===========
try this for you javascript
<script language="JavaScript" type="text/JavaScript">
function showHide(theid){
if (document.getElementById) {
var switch_id = document.getElementById(theid);
if(!switch_id) {
switch_id.className = (switch_id.className.indexOf("show") > -1) ? "hide" : "show"
}
}
}
Okay after a long time on this, I finally figured out what was going on. Part of the issue was that I was trying to call a form inside a form, which I had forgotten is not permitted in HTML, so this required some redesign.
Other issues involved calling loops within inside loops, which caused problems where the first record would work, but not for the remaining records.
The javascript above did not need to be modified, only the way that it was called.
Here is what worked. The main key was using include() instead of include_once().
while($r = $qir->fetch_assoc()) {
$ingredient_id = $r['ingredient_id'];
$amt = $r['amt'];
$ingredient_name = $r['ingredient_name'];
echo $r['amt'] . ' ' .$r['ingredient_name'];
if ($row['user_id'] == $user_id) {
echo ' <span class="openlink"><button onclick="showHide(\''.$ingredient_id. '\')">edit amount</button></span><br/>';
echo '<div id="'.$ingredient_id.'" class="hide">';
include('amt1.php');
echo '</div>';
}
}

How to dump every Flickr photo url from a set?

I'm not sure if this question is possible but what I want is to take a set of photos from Flickr and dump every url into a file (text is fine). Dumping them within anchor tags would be plus. So far I've seen this and I looked through the Galleria viewers JavaScript code but no luck. I'm expecting a simple few lines of code to do this because Galleria does it but I'm not really sure where in their code Flickr is accessed to get the image urls.
I think this might be the answer actually but if someone else comes along and has another answer I'll of course accept theirs instead of just mine.
It seems that phpflickr has this example which should work:
<?php
require_once("phpFlickr/phpFlickr.php");
// Create new phpFlickr object
$f = new phpFlickr("[API Key]");
$f->enableCache(
"db",
"mysql://[username]:[password]#[server]/[database]"
);
$i = 0;
if (!empty($_POST['username'])) {
// Find the NSID of the username inputted via the form
$person = $f->people_findByUsername($_POST['username']);
// Get the friendly URL of the user's photos
$photos_url = $f->urls_getUserPhotos($person['id']);
// Get the user's first 36 public photos
$photos = $f->people_getPublicPhotos($person['id'], NULL, NULL, 36);
// Loop through the photos and output the html
foreach ((array)$photos['photos']['photo'] as $photo) {
echo "<a href=$photos_url$photo[id]>";
echo "<img border='0' alt='$photo[title]' ".
"src=" . $f->buildPhotoURL($photo, "Square") . ">";
echo "</a>";
$i++;
// If it reaches the sixth photo, insert a line break
if ($i % 6 == 0) {
echo "<br>\n";
}
}
}
?>
<h3>Enter a username to search for</h3>
<form method='post'>
<input name='username'><br>
<input type='submit' value='Display Photos'>
</form>
<p>View Source</p>

AJAX: Replace a div's content with a specific div from the collected data

To me that looks correct, but i'm not experienced with AJAX in the slightest, been stuck at it for hours trying many variations including filter and it's all been useless. This is currently what i have and i can't see anything wrong with it.
What is happening is that no chat messages are showing up like they usually do, if i was to just refresh the page.
What i am simply trying to accomplish is a chat interface if that has any relevance.
Here is a live example of what is happening: http://www.mixpix.eu/chat/chat.php?r=G97NxXy4exbLQPFU
$(document).ready(function() {
var interval = setInterval(function() {
$.ajax({
dataType: "html",
url: 'chat.php?r=' + <?php echo "'" .$_GET['r']. "'"; ?> ,
success: function(data) {
var trim = $(data).find('.message_window');
$('.message_window').replaceWith(trim);
}
});
}, 1000);
});
Here's the contents of my body tag:
<div class="wrapper">
<div class"inbox_window" id="style-3">
</div>
<div class="message_window" id="style-3">
<table width="100%">
<p class="talking_to"><?php echo getFirstnamebyID($_GET['r']); ?></p>
<?php echo displayMessages(); ?>
</table>
</div>
<form class="submit_form" method="post" <?php echo 'action="chat.php?r='.$_GET['r'].'"' ?>>
<input type="text" name="message" placeholder="Type message here" />
<input type="submit" value="Send" name="s_say"/>
</form>
</div>
displayMessages() function in php:
function displayMessages() {
$user_id = getUserID();
$sql = mysql_query(strip_tags("SELECT * FROM inbox WHERE (send_id='".$user_id."' OR send_id='".$_GET['r']."') AND (rec_id='".$_GET['r']."' OR rec_id='".$user_id."') ORDER BY timestamp;"));
if (mysql_num_rows($sql) != 0) {
while($row = mysql_fetch_assoc($sql)) {
if ($row['send_id'] == $user_id) {
echo '<tr><td><p class="sm">'. $row['messages'] .'</p></td></tr>';
} else if ($row['send_id'] == $_GET['r']) {
echo '<tr><td><p class="rm">'. $row['messages'] .'</p></td></tr>';
} else {
echo "Unable to display messages.";
}
}
} else {
echo "Be the first to say hello!";
}
}
I would be highly thankful for any ones help as it's driving me a bit insane.
You've got a few things happening here that are going to cause you problems...
On the JavaScript side, setInterval is a hacky way to keep your content current, this could better be achieved with sockets. If you really want to do it this way, returning the whole document (including the HTML head) is not your best option -- maybe send an extra query param that tells your PHP to only send the messages section, or better yet, the messages that have been added since the timestamp you last checked.
In your markup, you can't put a paragraph tag directly inside your table, or raw text, as can come back from your PHP. You're not really using it as a table anyway, a list would probably be more semantic.

Ignoring links, checkboxes.. in an editable html field using jquery

Sorry for the constant question!! I have a table that displays records of data from my database. To make life easier, I have make it editable using jquery so that a user can click right an area an edit right away without redirecting to a different page.
A couple of questions.. how can i refine the below code so that when an area on the table with checkboxes and links is clicked, it will not respond/not editable?
Also, the editing function does not fully work at the moment and im having problems trying to figure out where the problem is. The table responds to everything defined in the jquery below but does not update my database.
There is my jquery code edit.js
$(function() {
$('tbody').on('click','td',function() {
displayForm( $(this) );
});
});
function displayForm( cell ) {
var column = cell.attr('class'),
id = cell.closest('tr').attr('id'),
cellWidth = cell.css('width'),
prevContent = cell.text()
form = '<form action="javascript: this.preventDefault"><input type="text" name="newValue" value="'+prevContent+'" /><input type="hidden" name="id" value="'+id+'" />'+'<input type="hidden" name="column" value="'+column+'" /></form>';
cell.html(form).find('input[type=text]')
.focus()
.css('width',cellWidth);
cell.on('click', function(){return false});
cell.on('keydown',function(e) {
if (e.keyCode == 13) {//13 == enter
changeField(cell, prevContent);//update field
} else if (e.keyCode == 27) {//27 == escape
cell.text(prevContent);//revert to original value
cell.off('click'); //reactivate editing
}
});
}
function changeField( cell, prevContent ) {
cell.off('keydown');
var url = 'edit.php?edit&',
input = cell.find('form').serialize();
$.getJSON(url+input, function(data) {
if (data.success)
cell.html(data.value);
else {
alert("There was a problem updating the data. Please try again.");
cell.html(prevContent);
}
});
cell.off('click');
}
And in my edit.php I have the following:
<?php
include ("common.php");
if (isset($_GET['edit'])){
$column = $_GET['column'];
$id = $_GET['id'];
$newValue = $_GET["newValue"];
$sql = 'UPDATE compliance_requirement SET $column = :value WHERE ComplianceID = :id';
$stmt = $dbh ->prepare($sql);
$stmt->bindParam(':value', $newValue);
$stmt->bindParam(':id', $id);
$response['success'] = $stmt->execute();
$response['value']=$newValue;
echo json_encode($response);
}?>
and finally my html..
<div class="compTable">
<table>
<thead><tr><th>Compliance Name</th><th>Compliance Goal</th><th>Compliance Description</th><th>Opions</th><th>Invite</th></tr></thead>
<tbody>
<?php
$sql = 'SELECT * FROM compliance_requirement';
$results = $db->query($sql);
$rows = $results->fetchAll();
foreach ($rows as $row) {
echo '<tr id="'.$row['ComplianceID'].'">';
echo '<td class="crsDesc">'.$row['ComplianceName'].'</td>
<td >'.$row['ComplianceGoal'].'</td>
<td >'.$row['ComplianceDescription'].'</td>
<td ><a href =inviteObstacle.php?action=invite&id=name1> InviteObstacle </a></td>
<td style="text-align: center; vertical-align: middle;"> <input type="checkbox" name="query_myTextEditBox">
</td>';
echo '</tr>';
}?>
</tbody>
</table>
</div>
Your help is much appreciated. thanks in advance
Simplest solution for identifying editable cells would be give those cells a class editable in your php output, then change your selector for td click handler to
$('tbody').on('click','td.ditable',function() {
As for updating database...need to determine if the ajax request from $.getJSON is being made. You can inspect this within browser console network tab. Also look for errors in console. Request ( if made) will show status, what is sent, what is returned etc
Need to use that as start point to help determine if preoblem lies in server code ( would get a 500 status) or in browser code.
If you provide live html sample ( not php ) from browser source view can create test demos to see what your javascript code is doing . Putting the html and javascript into jsfiddle.net and saving creates a demo that anyone can test out

JavaScript setTimeout function not executing as expected

I'm driving myself crazy here trying to figure out why this script is no longer executing as expected (it was working great yesterday, but I made a few minor changes and didn't back it up...now I can't figure out what the problem is).
<form method="POST" name="inventory_check" id="inventory_check">
<input type="text" name="stock_part" id="part_input">
<input type="hidden" name="site" value="2">
<input type="submit" value="Check Stock" id="submit">
</form>
<?php
if(isset($_POST['stock_part'])) {
$part = strtoupper($_GET['stock_part']);
$site = $_POST['site'];
$filename = 'system/inventory/'.$part.'.txt';
if(file_exists($filename)) {
$handle = fopen($filename, 'r');
$content = fread($handle, filesize($filename));
$content = trim($content, '&l0O(10U');
$content = trim($content, 'E');
fclose($handle);
date_default_timezone_set('UTC');
$mod_date = (filemtime($filename));
$current_date = time();
$subtract_date = ($current_date - $mod_date);
$subtract_date = ($subtract_date/3600);
if ($subtract_date <= 12) {
$stock = number_format($content);
echo '<script>document.inventory_check.style.display="visible";</script>';
echo '<div id="stock_results">There are '.$stock.' '.$part.' in stock.</div>';
}
else {
echo 'File too old.';
}
}
else {
echo '<iframe src="http://example.com/inventory_check.php?part='.$part.'&site='.$site.'" height="50" width="150"></iframe>';
echo '<script>document.inventory_check.style.display="none";</script>';
echo '<div align="center"><img src="http://www.aifittingsproto.com/images/load.gif"><br /><br />Searching</div>';
echo '<script>setTimeOut("recheck()", 2000);</script>';
}
}
?>
<script>
function recheck() {
document.inventory_check.stock_part.value="<?php echo $part ?>";
document.inventory_check.site.value="<?php echo $site ?>";
document.inventory_check.submit();
}
</script>
Basically this checks stock of a certain item on our internal servers (different domain than web server). What I'm trying to accomplish is the user keys in the part number...first it checks if the ftp-ed file exists on our server..if so, it checks the time it checks if its fresher than 12hrs, and then displays it if so. If not, it opens an iframe and sends the variables to our internal server for processing, which all works as expected. My issue is, I need to be able to have it recheck if the file exists after variables are passed through the iframe. I attempted to set this up by resending the variables and submitting the form every 2 seconds. Looking at the source, all the variables are populating as expected, etc. but it is not looping through and resubmitting the form. Any suggestions why this is failing, or a better approach? Thanks in advance.
You should try replacing setTimeout("window.reload()", 2000) with setTimeout("window.reload", 2000). My understanding is that you need to pass functions without the brackets for timeouts.

Categories