Writing PHP variable based on jQuery calculations and displaying predetermined value - php

Context:
I'm trying to make an automatically generated list that has a different amount of items on each page. Each item needs a name and a link, based on its place on the list. Here's an example with two items for the problematic part:
PHP variables:
$item_link_1 = "link1";
$item_name_1 = "first item";
$item_link_2 = "link2";
$item_name_2 = "second item";
jQuery:
$("#items").each(function(i) {
$(this).find("a").attr("href", "<?php echo $item_link_"+ ++i +";?>");
});
$("#items").each(function(i) {
$(this).find("a").text("<?php echo $item_name_"+ ++i +";?>");
});
HTML output:
<div id="items">
first item
second item
</div>
Problem:
Obviously, $item_name_"+ ++i +"; will never work. I need a way to add the number generated by jQuery to the end of the variable and echo this new variable.
So, if it's the 4th item, the variable will be $item_name_4. The value of this variable (set manually) will be displayed by jQuery with the text() function.
At least that's my idea for how to automate the process. If there's a way to do this, please tell me. If you know a better way, please tell me.

The problem your having is the difference between server-side processing and client-side processing.
An easy way to think about this is that PHP is handled before the HTML is even put on the screen replacing all the PHP parts with their variable contents. meaning that adding that php text with a client-side language like javascript won't be able to execute the php code and achieving the results you're after.
Luckily your example can be done explicitly in php:
<?php
$links = array(
array('link' => "Link1", 'name' => "first item"),
array('link' => "Link2", 'name' => "second item")
);
?>
<div id="items">
<?php for($i = 0; $i < count($links); $i++){ ?>
<?php echo $links[$i]['name']; ?>
<?php } ?>
</div>

Related

Accessing HTML unordered list elements in PHP

I'm trying to access unordered list elements in php so I can insert them in a database, I need to be able to access them via position but I'm not sure how to do this in PHP. I'm using jQuery so that the list is sortable on the client side.
In Javascript it would be accessed with
alert($("#sortable li:first").text() + ' is first ' + $("#sortable li:eq(1)").text() + ' is second ' + $("#sortable li:eq(11)").text() + ' is last');
The list I'm using is on http://jsfiddle.net/mMTtc/
I'm simply looking for help as for how to store those list items in a php variable i.e. lets say I wanted the 6th element based on how the user had ordered the list.
How would I do this?
Thanks
Using the following code you can send updates to the PHP backend as the user changes the order of elements in the front-end:
$("#sortable").on("sortupdate", function() {
var dataArr = [];
$("#sortable li").each(function(idx, elem) {
dataArr[idx] = $(elem).html();
});
var dataStr = '{"newOrder":' + JSON.stringify(dataArr) + '}';
$.ajax({
url: "<url_to_php_file>",
data: dataStr
});
// alert(dataStr);
});
Live example (frontend part): here
You'll have to replace <url_to_php_file> with the path to your PHP file that does the processing of the elements order (i.e. saving them in the DB). The file will be able to access the user-defined order in a normal PHP Array, using json_decode($_POST["newOrder"]), i.e.
...
$newOrder = json_decode($_POST["newOrder"]);
for ($i = 0; $i < count($newOrder); $i++) {
echo("The item labeled '" . $newOrder[$i] . "' is placed by the user at index " . $i . ".\n";
/* 1st item: index 0 */
/* 2st item: index 1 */
/* ... */
}
Example:
You present a sortable list to the user, containing items: item1, item2, item3 (in this order).
The user places item2 before item1, at which point an AJAX call is made passing to the server the array ["item2", "item1", "item3"] (note the order). The above snippet would echo:
The item labeled 'item2' is placed by the user at index 0.
The item labeled 'item1' is placed by the user at index 1.
The item labeled 'item3' is placed by the user at index 2.
(Of course, instead of echoing anything, you would update the value of an index-field in the DB for each item or do something useful.)
You can use DomDocument to parse your HTML. This can be done either via a string using loadHTML(), or loading an external HTML file using loadHTMLFile().
This example uses loadHTML():
<?php
$html = '<html>
<body>
<ul id="sortable">
<li class="ui-state-default">1</li>
<li class="ui-state-default">2</li>
<li class="ui-state-default">3</li>
<li class="ui-state-default">4</li>
<li class="ui-state-default">5</li>
<li class="ui-state-default">6</li>
<li class="ui-state-default">7</li>
<li class="ui-state-default">8</li>
<li class="ui-state-default">9</li>
<li class="ui-state-default">10</li>
<li class="ui-state-default">11</li>
<li class="ui-state-default">12</li>
</ul>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
</body>
</html>';
$dom = new DomDocument;
$dom->loadHTML($html);
$li = $dom->getElementsByTagName('li');
// Print first item value
echo $li->item(0)->nodeValue;
// Print third item value
echo $li->item(2)->nodeValue;
Here's what I'd do, and it's certainly not the cleanest way, but it should work.
This assumes you're working with your own pages, and not the scenario where you're getting the page html via http request to some external site (e.g. via CURL) and needing to parse it. DOMDocument serves just fine for the latter case. This solution is for the former, as I'm assuming that since you're working with javascript on the client-side of it, it's probably your own page (unless you're injecting that javascript into the page after it's loaded).
First of all, inside each list item, I'd include a server-side accessible input tag. It will serve to keep track of the position and value, and pass it to the server-side script on form submission.
<form method="POST">
<ul id="sortable">
<li class="ui-state-default">1
<input id="the_list_item_1" name="the_list_item[]" type="text" value="1_0" style="display: none;">
</li>
...
</ul>
</form>
The value is the item's actual value (the example had them ranged 1 - 12) and it's position separated by an underscore (value + "_" + position);
The list needs to be inside a form variable if you only need to submit the list to the server for processing when the user's done. However, if you intend to only use Ajax to get that data to the server, this solution isn't really necessary (as you'd simply just use jquery to get each position and value pair and send them directly in your ajax call).
You'll need to handle updating these input tags as the user drags items and changes the ordering of the list. See here if you need to know how to work with the sortable events. Perhaps, on update, for each list item call this function with the new position:
function update_pos(value,pos)
{
$("#the_list_item_"+value).val(value+"_"+pos);
}
So on form submit, we're now on the PHP side.
$list_items = $_POST["the_list_item"]; // This is basically an array of all the list_items, thanks to naming all the list items with "the_list_item[]", note the empty subscript (square braces).
$ordered_list_items = array(); // Let's push them into an associative array.
foreach($list_items as $li)
{
$li_split = explode("_",$li);
if(count($li_split) <= 0)
continue; // maybe you'd want to handle this situation differently, it really shouldn't happen at all though. Here, I'm just ignoring nonsensical values.
$item_id = $li_split[0];
$pos = $li_split[1];
$ordered_list_items[$item_id] = $pos;
}
// Then later you can shoot through this list and do whatever with them.
foreach($ordered_list_items as $item_id => $pos)
{
// postgres perhaps. Insert if not already there, update regardless.
pg_query("insert into the_list_item (item_id,position) select '$item_id','$pos' where '$item_id' not in (select item_id from the_list_item where '$item_id' = item_id limit 1));
pg_query("update the_list_item set position = '$pos' where item_id = '$item_id'");
}
Of course, all that said, depending on your needs you may need to be reloading this data onto the page. So looping through your db results (perhaps, for that user), you'd output each list_item into place.
$list_items = pg_fetch_all(pg_query($sql)); // $sql needs to be the query to get the results. Probably should order by position ascending.
$lic = count($list_items);
?>
<html> and stuff
<form method="POST">
<ul id="sortable">
<?php
for($i = 0; $i < $lic; $i++)
{
$li = $list_items[$i];
echo "<li class=\"ui-state-default\">".$li["item_id"]."<input id=\"the_list_item_".$li["item_id"]."\" name=\"the_list_item[]\" type=\"text\" value=\"".$li["item_id"]."_".$li["position"]."\" style=\"display: none;\"></li>";
}
?>
</ul>
</form>

php countering in javascript doesn't work

okay here is my code :
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php $i++; ?>
}
i'm still learning about this whole php and javascript thing, and i know there are many things that i still had to work to to improve my understanding to this both language. that's why i really need your help in this
i'm trying to get the while iteration to work so i can compare the variable from javascript with variable from php which took the value from database. the php variable ('$mfr' and '$mto'), as you can see, is an array. now i want it to look at every element of both and if it meets the condition then it will update the variable 'comp' and stop the whole while iteration
but the problem is the '$i' variable doesn't do the iteration thing. it runs only once so my '$mfr' and '$mto' value doesn't go anywhere. how can i fix this so i can compare the javascript value with the php '$mfr' and '$mto' value?
your help would be much appreciated, thank you :)
EDIT
well, it is actually a function of custom validation for jqgrid.
and i do know that php is a server-side and javascript is a client-side language theoretically, though i don't really know it is practically
what i'm actually trying to do is when a user input a value and submit it, the system will check whether the value that was entered are between value of 'fromid' and 'toid' column of a table in database
here is my full code of the function
function checkid(value)
{
var co = 0;
var comp = '';
<?php $i = 0;?>
while (co < <?php echo $db->count_rows(); ?>)
{
if ((parseInt(value) >= <?php echo $mfr[$i] ?>) && (parseInt(value) <= <?php echo $mto[$i] ?>))
{
comp = 'T';
break;
}
co++;
<?php echo $i++; ?>
}
if (comp != 'T')
{
return [true, "", ""];
}
else
{
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
while this is how i got the '$mfr' and '$mto' variable
<?php
$db=new database($dbtype, $dbhost, $database, $dbuser, $dbpassword, $port, $dsn);
$db->query("select fromid, toid from CORE_ID");
$i = 0;
while($row = $db->get_row())
{
$mfr[$i] = $row[fromid];
$mto[$i] = $row[toid];
$i++;
}
?>
if theres any better way to do this, then please do tell me
Typically, PHP is for server side logic and JS is for client side logic. If you want to send a value from JS to be processed in PHP, you'll probably need to use something like AJAX, which jQuery makes pretty easy with jQuery.ajax().
Getting the client value to be processed is the difficult part. Once you can do that, rewriting your code logic in full PHP should not be difficult.
EDIT: If I'm misunderstanding where variable value comes from, please say so!
EDIT 2: It looks like you want to have client input compared to server side data. JS will not have access to your PHP variables unless they are specifically sent there. Likewise, you can send your JS value to the server for validation in the PHP.
In your case, you could use JSON to send send the JS your validation dates. Assuming you don't have too many dates, it will probably be faster than sending a value to the server and waiting for a response.
I found a good example of using JSON at another post. You can send an array like:
<?php
$xdata = array(
'foo' => 'bar',
'baz' => array('green','blue')
);
?>
<script type="text/javascript">
var xdata = <?php echo json_encode($xdata); ?>;
alert(xdata['foo']);
alert(xdata['baz'][0]);
// Dot notation can be used if key/name is simple:
alert(xdata.foo);
alert(xdata.baz[0]);
</script>
For your code, you could put $mfr and $mto into a single 2D array. Here is how your new JS might look, assuming xdata contains $mfr and $mto:
function checkid(value) {
var co = 0, comp = '', i = 0, nrows = xdata.mfr.length;
while (co < nrows) {
if ((parseInt(value) >= xdata.mfr[i]) && (parseInt(value) <= xdata.mto[i])) {
comp = 'T';
break;
}
co++;
i++;
}
if (comp != 'T') {
return [true, "", ""];
} else {
return [false, "Value entered is already between a range. Please try again!", ""];
}
}
You have a loop in your Javascript, not your PHP. So the PHP is only going to get executed once. You need to rethink your approach. Without knowing what the script is supposed to actually achieve it's difficult to provide working code, but you at least need to put the loop into the PHP instead of the Javascript.
Before I can answer you should understand what's going on exactly:
PHP is being executed on the server, then sends back the result (HTML and Javascript) to the client (the browser).
Javascript is being executed on the client side. So this only starts after PHP is completely done. For this reason you can't mix Javascript and PHP.
Check the source of the page, then you'll see exactly what the server returns (what HTML/Javascript PHP generates) and you'll get a better insight of what happens.
Now, if you understand this, you may be able to solve your own problem. I don't exactly know what you want to do, but I can advice you that if you need Javascript to check values from the database, you should generate Javascript using PHP that defines these values in the Javascript like for example this:
var my_js_var = <?=$my_php_var?>
var another_var = <?=$another_one?>
Now they are defined in Javascript and you can use them (and check them).
When you have a large database it can become inefficient to do it like this and you might want to look into a technology called AJAX, which allows Javascript to do a request to the server and get back data from a PHP script.
You would also want to do this if there's data involved you don't want to be publicly viewable (because everyone can look into the source of your page.

Only add item as needed in PHP array

I have bits of code I want to throw in to my site, and provisioned a space right after <body> using 'flairs' (divs) that sit outside the design. Here's the code:
//Add Flair Containers as needed
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
It prints correctly, where content = $flair1, $flair2, and so on.
<div id="flair-1">Content1</div>
<div id="flair-2">Content2</div>
<div id="flair-3">Content3</div>
But if $flair2/$flair3 is empty, it still prints a div. How can I fix this?
Within your foreach loop you can check if the value is empty and continue (i.e. skip) to the next value if it is.
Like so:
if($flairs>0){
echo "<!--Flair Graphics (if needed)-->\n";
while($fQty = --$flairs+1){ //-- subracts 1, +1 accounts for 1 being 0
$flair = array($flair1, $flair2, $flair3);
foreach($flair as $flairCode){
if (empty($flairCode)) continue;
echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
};
};
I suspect that you could simply prepend if($flairCode) to your echo statement. That would make your inner loop:
foreach($flair as $flairCode){
if($flairCode) echo "<div id=\"flair-".$fQty++."\">".$flairCode."</div>\n";
};
Some points to note:
Since the $flair array will always be the same, construct it outside of the loop (this will let you evaluate the condition only once too.
Using $fQty++ is not enough to guarantee unique ID's, especially since every time it hits the while the value is reset. I suggest $fQty should not be part of the while condition and simply stay as an independent tally.
Stop using double-quotes. They're slow.

output mysql data into variables for jquery

I have a 2 field database (daynumber & datavalue), the data of which I am retrieving with php then creating and passing variables into jquery for use with a graph.
I am not doing this as an array because I need to apply a formula to the datavalue field. The formula can be altered by the user.
In jquery, I need to be able to do this:
cday_1 = <?php echo $day_1?>;
cday_2 = <?php echo $day_2?>;
tday_1 = (<?php echo $day_1 ?> * formula1 / formula2;
tday_2 = (<?php echo $day_2 ?> * formula1 / formula2;
The cday series and the tday series will be plotted separately on the graph.
My problem is that I could manually name each var in php, ie:
$day_1=mysql_result($result,$i,"datavalue");
but I have 30 rows and I'd prefer to do it with a loop. So far, I've got this far:
$i=0;
while ($i < $num) {
$datavalue=mysql_result($result,$i,"datavalue");
echo "\$day_";
echo $i;
echo " = ";
echo $datavalue;
echo "<br>";
$i++;
}
So there are a couple of problems I'm having with this.
The first problem is that while everything is echoing, I'm not sure how to actually create variables like this(!).
The second problem is that there are only 30 rows in the db, but 34 are actually outputting and I can't work out why.
I'm self-taught, so apologies for clumsy coding and/or stupid questions.
You could just store them in a PHP-side array:
$days = array(
'cday' => 'the cday value',
'dday' => 'the dday value',
etc...
);
and then via json_encode() translate them to a Javascript array/object automatically. This object could be sent to your page as an AJAX response, or even embedded into the page directly:
<script type="text/javascript">
var days = <?php echo json_encode($days) ?>;
</script>
after which you just access the values as you would any other array in JS.
Have ended up doing this:
$i=0;
while ($i < $num) {
${"day_$i"}=mysql_result($result,$i,"datavalue");
$i++;
}
I have a feeling this was a basic issue and I just didn't explain myself properly. I am unable to use an array as I needed to fiddle with formulas so this solution worked fine.

Something is making my page perform an Ajax call multiple times... [read: I've never been more frustrated with something so 'simple' in my life]

NOTE: This is a long question. I've explained all the 'basics' at the top and then there's some further (optional) information for if you need it.
Hi folks
Basically last night this started happening at about 9PM whilst I was trying to restructure my code to make it a bit nicer for the designer to add a few bits to. I tried to fix it until 2AM at which point I gave up. Came back to it this morning, still baffled.
I'll be honest with you, I'm a pretty bad Javascript developer. Since starting this project Javascript has been completely new to me and I've just learn as I went along. So please forgive me if my code structure is really bad (perhaps give a couple of pointers on how to improve it?).
So, to the problem: to reproduce it, visit http://furnace.howcode.com (it's far from complete). This problem is a little confusing but I'd really appreciate the help.
So in the second column you'll see three tabs
The 'Newest' tab is selected by default. Scroll to the bottom, and 3 further results should be dynamically fetched via Ajax.
Now click on the 'Top Rated' tab. You'll see all the results, but ordered by rating
Scroll to the bottom of 'Top Rated'. You'll see SIX results returned.
This is where it goes wrong. Only a further three should be returned (there are 18 entries in total). If you're observant you'll notice two 'blocks' of 3 returned.
The first 'block' is the second page of results from the 'Newest' tab. The second block is what I just want returned.
Did that make any sense? Never mind!
So basically I checked this out in Firebug. What happens is, from a 'Clean' page (first load, nothing done) it calls ONE POST request to http://furnace.howcode.com/code/loadmore .
But every time you load a new one of the tabs, it makes an ADDITIONAL POST request each time where there should normally only be ONE.
So, can you help me? I'd really appreciate it! At this point you could start independent investigation or read on for a little further (optional) information.
Thanks!
Jack
Further Info (may be irrelevant but here for reference):
It's almost like there's some Javascript code or something being left behind that duplicates it each time. I thought it might be this code that I use to detect when the browser is scrolled to the bottom:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
So what I thought was that code was left behind, and so every time you scroll #col2 (which contains different data for each tab) it detected that and added it for #newest as well. So, I made each tab click give #col2 a dynamic class - either .newestcol, .featuredcol, or .topratedcol. And then I changed the var col=$('.newestcol');dynamically so it would only detect it individually for each tab (makin' any sense?!). But hey, that didn't do anything.
Another useful tidbit: here's the PHP for http://furnace.howcode.com/code/loadmore:
$kind = $this->input->post('kind');
if ($kind == 1){ // kind is 1 - newest
$start = $this->input->post('currentpage');
$data['query'] = "SELECT code.id AS codeid, code.title AS codetitle, code.summary AS codesummary, code.author AS codeauthor, code.rating AS rating, code.date,
code_tags.*,
tags.*,
users.firstname AS authorname,
users.id AS authorid,
GROUP_CONCAT(tags.tag SEPARATOR ', ') AS taggroup
FROM code, code_tags, tags, users
WHERE users.id = code.author AND code_tags.code_id = code.id AND tags.id = code_tags.tag_id
GROUP BY code_id
ORDER BY date DESC
LIMIT $start, 15 ";
$this->load->view('code/ajaxlist',$data);
} elseif ($kind == 2) { // kind is 2 - featured
So my jQuery code sends a variable 'kind'. If it's 1, it runs the query for Newest, etc. etc.
The PHP code for furnace.howcode.com/code/ajaxlist is:
<?php // Our query base
// SELECT * FROM code ORDER BY date DESC
$query = $this->db->query($query);
foreach($query->result() as $row) {
?>
<script type="text/javascript">
$('#title-<?php echo $row->codeid;?>').click(function() {
var form_data = {
id: <?php echo $row->codeid; ?>
};
$('#col3').fadeOut('slow', function() {
$.ajax({
url: "<?php echo site_url('code/viewajax');?>",
type: 'POST',
data: form_data,
success: function(msg) {
$('#col3').html(msg);
$('#col3').fadeIn('fast');
}
});
});
});
</script>
<div class="result">
<div class="resulttext">
<div id="title-<?php echo $row->codeid; ?>" class="title">
<?php echo anchor('#',$row->codetitle); ?>
</div>
<div class="summary">
<?php echo $row->codesummary; ?>
</div>
<!-- Now insert the 5-star rating system -->
<?php include($_SERVER['DOCUMENT_ROOT']."/fivestars/5star.php");?>
<div class="bottom">
<div class="author">
Submitted by <?php echo anchor('auth/profile/'.$row->authorid,''.$row->authorname);?>
</div>
<?php
// Now we need to take the GROUP_CONCATted tags and split them using the magic of PHP into seperate tags
$tagarray = explode(", ", $row->taggroup);
foreach ($tagarray as $tag) {
?>
<div class="tagbutton" href="#">
<span><?php echo $tag; ?></span>
</div>
<?php } ?>
</div>
</div>
</div>
<?php }
echo " ";?>
<script type="text/javascript">
var newpage = <?php echo $this->input->post('currentpage') + 15;?>;
</script>
So that's everything in PHP. The rest you should be able to view with Firebug or by viewing the Source code. I've put all the Tab/clicking/Ajaxloading bits in the tags at the very bottom. There's a comment before it all kicks off.
Thanks so much for your help!
I think you're right to suspect this code block:
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
My take on this is that you keep adding additional event handlers (duplicates, essentially) each time you run this code. You need to remove (unbind) the existing event handlers with every tab click so that you can be sure that it's only firing once:
$('#col2').unbind();
var col = $('#col2');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
Or some such thing. See http://api.jquery.com/unbind/
$('.featurecol'); , $('.topratedcol'); and $('.newestcol'); all refer to the same column and division (<div>). As such, whenever you switch pages, you need to unbind the old scroll before rebinding the new scroll handler. (Or else you'll be appending another scroll handler and getting multiple requests sent, like now)
You can do this by adding an unbind as follows:
var col = $('.newestcol');
col.unbind('scroll');
col.scroll(function(){
if (col.outerHeight() == (col.get(0).scrollHeight - col.scrollTop()))
loadMore(1);
});
You need to do this for all of the columns as they load (code/newest, code/toprated and code/featured).
It could also be
$('#col3').fadeOut('slow', function() {
as the ajax loads there... n number of times as it fades out it calls another ajax request.
not saying its the defenet answer but something looking into...

Categories