I am extremely new to PHP and, although I am quite familiar to javascript, I am learning how to use the massive jqGrid plugin right now. I am trying to understand how jqGrid serializes the grid data and how PHP parses this data. Currently, I am not even connecting to MySQL, but I am simply trying to echo the serialized jqGrid data as "fake" results. I have the following code for js in the head of my PHP file:
<script type='text/javascript'>
$(function(){
$('#list').jgGrid({
url:'grid.php',
mtype:'POST',
colNames:['json'],
colModel:[{name:'j',index:'j',searchoptions:{sopt:['eq']},search:true}],
pager:'#pager',
rowNum:10,
viewrecords:true,
gridview:true,
serializeGridData:function(postData){
return postData;
}
})
});
</script>
I then send this information to my 'grid.php' file, which has the following code:
<?php
$jason = $_POST['postData'];
$page = $jason->{'page'};
echo '<rows>';
echo '<page>1</page>';
echo '<total>1</total>';
echo '<records>1</records';
echo '<row id="1">';
echo '<cell>'.$page.'</cell>';
echo '</row>';
echo '</rows>';
?>
When I remove the serializegriddata option from the JS, everything works fine (I also add in the default $_POST['page'], $_POST['rows'], $_POST['sidx'], $_POST['sord'] back into the PHP). The problem comes in when I add the serializegriddata.
I am looking for any examples of how to use the postData on the client side (are the any other functions I need to add to the serializegriddata or can I just return the postData) and how to properly parse this in PHP (how to $_POST the data and then how to parse and use this data). I know this is probably an extremely simple solution, but everything I find just talks about the client and says nothing about the server side. Thanks in advance.
Okay, I am a little slow, but I partially answered my own question. All of the jqGrid documentation read as if your entire postData was parsed as a JSON string if you set multipleSearch:true. I thought that I had to parse every variable into a postData JSON variable, then pass this to PHP. Although the solution took a little work to properly implement, the thing that I was missing was the fact that with multipleSearch:true, this adds just a 'filter' variable to the AJAX call. This filter variable is parsed as follows:
$filters = $_POST['filters'];
$json = json_decode($filters,true);
and the result of $filters is:
{"groupOp":"AND","rules":[{"field":"Customer","op":"eq","data":"eosp"}]}
This is as opposed to the multipleSearch:false option of:
$sField = $_POST['sField'];
$sValue = $_POST['sValue'];
$sOper = $_Post['sOper'];
Once I got this, I was able to loop through all instances of my search parameters and create my $where variable. One thing that almost became a big problem for me was the old example I was able to find about properly constructing a (link below) is that you can only have WHERE is a mysql_query only 1 time.
http://blog.brzezinka.eu/webmaster-tips/jquery/how-to-enable-the-search-functionality-in-jqgrid
I hope this might help someone in the future (it drove me crazy for almost 2 days straight).
Related
what i'm trying to do is get a variable to update every 5 seconds doing this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>",5000);
but what happens is the inner html is set but doesn't update every 5 seconds like it should.
my guess is that the php only executes once, but i have no idea if that's the case or not.
and i'm aware i should make a function to do the stuff inside setInterval... i'll clean up the code once i figure out how to make it work.
thanks in advance.
ok... ajax was 'the best' answer since no more than 2 people would be logged in at a time here so server requests isn't such a big deal.
here's how i got it to work:
function lCount(){
$.get("../includes/shoutcaststuff.php",{Count: "TRUE"}, function(data){
document.getElementById('listeners').innerHTML = data;
});
}
setInterval(lCount,5000);
and added this to the end of the php:
if(isset($_GET["Count"])){
echo $dnas_data['CURRENTLISTENERS'];
}
now it works fine.
thanks for the suggestions guys :)
<?php include('../includes/shoutcaststuff.php');
echo $dnas_data['CURRENTLISTENERS']; ?>
This code only executes once when the page is built. For the rest of the times this javascript is called whatever is first echoed will be the value.
Instead of using a static value here, you are going to need to use an ajax request (or a websocket if you want to use html5). The request will then hit your server once every 5 seconds. Keep in mind that this can cause undue load on your server.
Ratchet is a commonly used PHP WebSocket implementation that allows for data to be sent to the client using push technology. This is probably more preferable than using your polling approach.
PHP code is run on the server generating the HTML/JS. Use ajax if you need to run php code once the page has loaded.
Take a look at this for example;
Using this:
setInterval(document.getElementById("listeners").innerHTML =
"<?php echo "1";?>",5000);
Will output this to the browser:
setInterval(document.getElementById("listeners").innerHTML =
"1",5000);
I have a PHP-based template website that has been heavily modified.
I am in the process of adding some RSS feeds, most of which are easy to "interpret" and display satisfactorily but one is in caps with "pre" formatting as well.
I want to modify the content. I look at all the mods I make as education and invariably am able to google satisfactory solutions to the problems I come across but, despite an earlier extensive programming background, without a thorough grounding in Javascript, Ajax, PHP, CSS and HTML, there are sometimes things that just frustrate the hell out of me.
All I want to do is pass a block of text from javascript code to PHP code, massage it and get the result back.
I am at a point in a ajax/jscript function where...
items[i].content
...contains the block of text that I want massaged and I have a piece of code that I got from here, I think, that ostensibly calls the PHP code...
function compute() {
var params="session=123";
$.post('wxspellch.php',params,function(data){
alert(data);//for testing if data is being fetched
var myObject = eval('(' + data + ')');
document.getElementById("result").value=myObject(addend_1,addend_2);
});
...and, unfortunately, it isn't documented so I don't have a clue what has to be customized. All I have done so far is enter the name of my PHP script.
The PHP script is written like this...
$pspell = pspell_new('en','american','','utf-8',PSPELL_FAST);
function spellCheckWord($word) {
global $pspell;
$autocorrect = TRUE;
// Take the string match from preg_replace_callback's array
$word = $word[0];
etc......
}
function spellCheck($string) {
return preg_replace_callback('/\b\w+\b/','spellCheckWord',$string);
}
echo spellCheck("...... the data .......")
The PHP tests out fine with hard-coded data.
I just need to know what further customizing I have to do to the javascript and php in order to facilitate the passing and recovery of the block of text.
I have one line of JavaScript that I'd appreciate help with.
req.open("GET", 'update.php?id=<?php $id ?>', true);
Where $id = 12345, I am trying to get the contents of update.php?id=12345.
Using PHP inside this JavaScript doesn't seem to be working for me.
Any suggestions?
First, make sure that you are actually inside a PHP file, or have your server configured to process whatever file extension you are using with PHP.
Then, you can echo data directly into the JavaScript. For best compatibility and to avoid potential XSS vulnerabilities, always JSON-encode the data.
req.open('GET', 'update.php?id=' + <?php echo json_encode($id); ?>, true);
Personally, I prefer to have a block of variables that are assigned over from PHP. this keeps your JavaScript cleaner.
<?php
$options = new stdClass();
$options->id = 12345;
$options->dinnerSelection = 'pizza';
echo 'var options = ', json_encode($options), ';'
?>
// Then later on in your JS...
req.open('GET', 'update.php?id=' + options.id, true);
You have some way to do this.
First one make your javascript file in .php file(be carrefull you need to include it and not to link it in the begin of file.
Second one, in php, you can wrote
<?php
echo '
<script type="text/javascript">
id="'.$id.'";
</script>';
?>
with this, you define a global variable in javascript who take the good value.
Then you just have to wrote after this :
req.open("GET", 'update.php?id='+id, true);
if you have to change the id after requied the page, you just have to change the id javascript value
I believe it would be a very poor design decision to use PHP to format your javascript in this way. You should provide more info about what you're trying to do because I can almost guarantee you that there is a better way to do this.
If you are trying to, for instance, do a javascript call to a URL (clearly), then apply that data to an attribute in the HTML document:
<div id="someExample">
Item 12345
</div>
And then use unobtrusive javascript to access that item when clicked, cancelling the link's default action if necessary. The benefits of this approach are many- you can write reusable code, and you don't have extra PHP parsing to do in a javascript that is going to be extremely hard to understand later.
Adding JS hardcoded data via PHP to a javascript object is a very poor design decision. If you need more help on this let me know, but try researching it more first!
I'm pretty new to HTML and javascript. I know this code already exist on internet but I can't have it working for me. I'm stuck on this issue for 2-3 days. I would be really glad if you could help me out.
Here is my problem
I want to populate the optCategory select list based on the selected entry of optPostAppliedFor. For that I called a function change_categoriees(key) when I click the optPostAppliedFor list. The code is here as follows
<tr>
<td width="40%" align="right" nowrap>
<strong>
Post Applied for<span class="text11red">*</span> :
</strong>
</td>
<td width="60%">
<select name="optPostAppliedFor" class="flat" onclick="change_categories(0);" />
<option value="">--Select--</option>
<?php
foreach($App['post_applied_for'] as $key => $val){
echo '<option value="'.($key).'">'.$val.'</option>';
}
?>
</select>
</td>
</tr>
Here is php code for default enteries of optPostAppliedFor and optCategory
$App['post_applied_for'] = array(
'Lecturer' => 'Lecturer',
'Business Analyst' => 'Business Analyst',
'Deepender good' => 'Deepender good'
);
$App['category'] = array(
'Category1' => 'Category1',
'Category2' => 'Category2',
'Category3' => 'Category3'
);
Please tell me how can I make this function, so that my purpose is achieved. I tried this but all in vain.
function change_categoriees(key) {
alert('asdasd');
var z = document.getElementById('optCategory');
var x = document.getElementById('optPostAppliedFor');
var y = document.createElement('option');
var display = x.options[x.selectedIndex].text;
var option = x.options[x.selectedIndex].value;
y.text = display;
y.value = option;
try {
z.add(y,null);
} catch(ex) {
z.add(y);
}
z.options[0].text = '* '+(z.length-1)+' selected *';
}
I'm not really sure, but...
These two lines in your change_categoriees method look problematic:
var z = document.getElementById('optCategory');
var x = document.getElementById('optPostAppliedFor');
For these statements to return some value, your HTML needs to have id attributes with the names optCategory and optPostAppliedFor:
<select id="optPostAppliedFor">
Also note that the PHP code runs on the back end, in the server. There's no way that the javascript running in the browser can call PHP directly.
If I interpret your code correctly, you do have a slight problem : you're putting variable in the PHP code, that you'd like the client (the browser) to use. It's not the way it works. Variable in PHP are only stored on the server-side. So the Javascript (which is on the browser side) cannot use it in any way, if you only store them as variables : they'll be on the server memory, not on the client's. There are two solutions here :
1°) You put the variable you're going to use in the web page that PHP generates. You could go with hidden fields, for instance, and then "unhide" the relevant fields. But if you got a lot of variables, it's not very practical.
2°) You could go with an AJAX solution : basically, the idea is that through Javascript, you call a PHP script that is going to send back information (formatted as pure text, XML or JSON). Here, when the user clicks on the first list, you send a request (POST or GET) where you'll inform the server about the choice of the user. For instance, you'll ask for the categories connected to the "Business Analyst" choice. The PHP script we'll analyse the "post applied for" and send the content of the category list accordingly. Since everything is done through Javascript & PHP, the page will not be reloaded during this time, so it's relatively fluid.
I would recommend the use of a Javascript library to make things a bit easier. JQuery being one of the most popular choice, you will find a lot of help and example on the web.
May be you are searching for AJAX methods? E.g. you send request to some of your PHP files with GET or POST variable for your key (which user selects in optPostAppliedFor) and that PHP script echo'es the needed result, so JS could use it.
For example, with jQuery this would look like this:
$("select[name=optCategory]").load("myUberScript.php", { key: $("select[name=optPostAppliedFor]").attr("selected") });
myUberScript.php:
<?php
$key = $_POST['key'];
if (isset($key))
{
if ($key == 'moo')
echo "<option>moo</option>"; else
if ($key == 'foo')
echo "<option>foo</option>";
}
?>
I think this would be the best way, but i'm really not sure with my .attr("selected") selector. And i recommend you to read something 'bout AJAX and jQuery - these are very useful when web-developing =)
So, what does this JS do? It finds your select tag with name optPostAppliedFor, gets all its 'selected' items (be sure to verify that code - i am not sure about it), sends POST request to myUberScript.php passing that values as $_POST['key'] argument, gets response, finds div named optCategory and sets its inner HTML code to PHP's response. Pretty nice, huh? =)
I recommend this way beacause it is not always good for user to get all the internal data within javascript - user could see that data and if there is a lot of data, the page would load slooowly. Second: you can manage/edit/update/modify (choose the right one) your PHP code whenever you want. Third: PHP code has more features for secure verifying user' data and lots more. But there is one great disadvantage: if user disables JS support in his browser, you would not be able to do this sort of trick. Notice: this is a very rare case when user disables JS =)
As a first problem, in your PHP code, you improperly close the select tag, like this,
<select ... />
...
</select>
That will probably cause some errors. It should be like this, without the extra /,
<select ... >
...
</select>
As another problem, you spell your function call like this,
onclick="change_categories(0);"
but you misspell your function name like this,
function change_categoriees(key) {...}
Notice the extra "e" in "categoriees". So you're not actually calling the function properly.
It looks like other people have some answers too, so I'll just finish by offering some suggestions for dev tools and documentation. For development tools, Firefox Firebug is excellent, it will let you debug css, html, and javascript. I've also heard good things about the development tools in Chrome. In fact, all the newest browser versions have development tools of some sort, and they're all pretty good.
Next, the Mozilla docs are a good resource for web-development. You might also be interested in checking out the resources mentioned at w3fools.com.
Also, in the future, when sharing code on Stack Overflow, you should consider sharing a live example with jsFiddle.
Oh wait, before I forget, you should also use a text editor or an IDE that does syntax highlighting, and maybe even syntax correction, for you. I use a simple text-editor called Notepad++ for Windows, though there are many others.
I was wondering if there was any possible way to keep track of JavaScript variables within a for loop inside PHP.
I definitely know that this is not good design. However, I'm trying to hack some existing code. If I am able to make this work, I may not have to dump the existing code...
Thanks you guys. Any hacks, tips, tricks will work!!
Example:
//JavaScript for loop
for (var i = 0; i <4; ++i) {
//Echo the JavaScript variable "i", the iteration of the loop
<?php echo /*JavaScript var i */ ; ?>
}
EDIT: More background info
I'm working on a project where the data is supplied through XML and the API is written in PHP and returns an PHP array. The front end is designed whilst using a lot of JavaScript. I'm going to need to populate JavaScript fields with fields from my PHP object through multiple iterations. Hence, the PHP inside the JavaScript for loop.
Neither the front end nor the back end is written by me, mind you. :P
You fundamentally misunderstand how PHP and Javascript work. PHP is executed on the server, while the page is being generated, BEFORE the page is sent to the client.
Javascript kicks in afterwards, after the page has been generated and received by the client.
What you're trying to do is getting a driver to change the radio station in a car while the car's still on the assembly line in the factory. Not possible.
That will definitely not work.
The JavaScript loop's body will be whatever PHP echoes, and in your example, that is not valid PHP syntax.
Example
Imagine this is a HTML view...
for (var i = 0; i < 4; ++i) {
<?php echo 'a'; ?>
}
...the output would be...
for (var i = 0; i < 4; ++i) {
a
}
You cant mix server side scripting and client side scripting.
For this purpose only AJAX is made. :)
You can go with jquery, mootool, closure... etc
I think I understand what you are trying to do. If on a basic level, you want to use the value from a PHP variable within the javascript on your client side, they you need to echo out a whole section and 'print' the php value and assign it to a javascript variable.
This post talks about it: http://www.daniweb.com/web-development/javascript-dhtml-ajax/threads/290401
If I'm on the wrong track, then have a read anyway :)