How to populate HTML select list using javascript - php

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.

Related

call php from ajax javascript

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.

Get all content from a file, including PHP code

I'm making a small CMS for practice. I am using CKEDITOR and is trying to make it avaliable to write something like %contactform% in the text, and then my PHP function will replace it with a contactform.
I've accomplished to replace the text with a form. But now I need the PHP code for the form to send a mail. I'm using file_get_contents(); but it's stripping the php-code.
I've used include(); to get the php-code from another file then and that works for now. I would like to do it with one file tho.
So - can I get all content from a file INCLUDING the php-code?
*UPDATE *
I'll try to explain in another way.
I can create a page in my CMS where I can write a header and some content. In the content I am able to write %contactform%.
When I get the content from the database I am replacing %contactform% with the content from /inserts/contactform.php, using file_get_contents(); where I have the form in HTML and my php code:
if(isset($_POST['submit'])) {
echo 'Now my form is submitted!';
}
<form method="post">
<input type="text" name="email">
<input type="submit" name="submit">
</form>
Now I was expecting to retrieve the form AND the php code active. But If I press my submit button in the form it's not firing the php code.
I do not wan't to show the php code I want to be able to use it.
I still have to guess, but from your update, I think you ultimatly end up with a variable, which contains the content from the database with %contactform% replaced by file_get_contents('/inserts/contactform.php').
Something like:
$contentToOutput = str_replace(
'%contactform%',
file_get_contents('/inserts/contactform.php'),
$contentFromDatabase
);
If you echo out that variable, it will just send it's content as is. No php will get executed.
Though it's risky in many cases, if you know what you're doing you can use eval to parse the php code. With mixed code like this, you maybe want to do it like the following.
ob_start();
eval('; ?>' . $contentToOutput);
$parsedContent = ob_get_clean();
$parsedContent should now contain the results after executing the code. You can now send it to the user or handle it whatever way you want to.
Of course you'll have to make sure that whatever is in $contentToOutput is valid php code (or a valid mixture of php with php-tags and text).
Here is a link to the symfony Templating/PhpEngine class. Have a look at the evaluate method to see the above example in real code.
yes...
$content = file_get_contents( 'path to your file' );
for printing try
echo htmlspecialchars( $content );
From reading the revised question, I think the answer is "You can't get there from here." Let me try to explain what I think you will encounter.
First, consider the nature of HTTP and the client/server model. Clients make requests and servers make responses. Each request is atomic, complete and stateless, and each response is complete and usually instantaneous. And that is the end of it. The server disconnects and goes back to "sleep" until the client makes a new request.
Let's say I make a request for a web page. A PHP script runs and it prepares a response document (HTML, probably) and the server sends the document to my browser. If the document contains an HTML form, I can submit the form to the URL of the action= script. But when I submit the form, I am making a new request that goes back to the server.
As I understand your design, the plan is to put both the HTML form and the PHP action script into the textarea of the CKeditor at the location of the %contactform% string. This would be presented to the client who would submit the form back to your server, where it would run the PHP script. I just don't think that will work, and if you find a way to make it work, you're basically saying, "I will accept external input and run it in PHP." That would represent an unacceptable security exposure for me.
If you can step back from the technical details and just tell us in plain language what you're trying to achieve, we may be able to offer a suggestion about the design pattern.

PHP $_GET and $_POST are returning empty arrays--trying to paginate SQL data

I have set up the following:
Database class ($db)
Pagination class ($paginator)
I am attempting to write a basic system to let me administrate pages. I have a page "page_manager.php" in which I include both my database class (database.php) and my pagination class (paginate.php).
In my pagination class I have a function which echoes my SQL data. I've come up with a way to echo an HTML < select > element with the necessary IDs, which allows me to successfully echo the corresponding results (10 per page), based on the value of the < select > element. So, "1" will echo the first 10 results in the database, "2" will echo from 11-20, "3" will echo from 21-30, etc., etc..
I have added an onChange event to the < select > element which will copy its value (using "this.value") to a hidden form field. I then submit this form using document.getElementById().submit();
This will then add the $_GET variable to the URL, so the URL becomes ".../?pagenumber_form=X". However, when I try to grab this value back from the URL, the $_GET['pagenumber_form'] is empty.
Some code:
<span style='font-family: tahoma; font-size: 10pt;'>Page #</span>
<select id="page_number_selection"
onchange='javascript: document.getElementById("pagenumber_form").value = this.value;
document.getElementById("pagenumber").submit();'>
<?php
for($i = 1; $i <= $this->num_pages; $i++)
echo"<option id='" . $i . "'>" . $i . "</option>";
?>
</select>
<form name="pagenumber" id="pagenumber" action="" method="get">
<input type="text" name="pagenumber_form" id="pagenumber_form" />
</form>
So, I've tried using $_POST as well, but the same thing happens. I want to use $_GET, for a couple of reasons: it's easier to see what is happening with my values and the data I'm using doesn't need to be secure.
To recap: the $_GET variable is being added to the URL when I change the < select > element, and the corresponding value gets added to the URL as: ".../?pagenumber_form=X", but when I try to use the value in PHP, for example...
$page_number = $_GET['pagenumber_form'];
... I get a NULL value. :-(
Can anybody help me out please? Thank you.
EDIT:
I've just made a discovery. If I move my print_r($_GET) to my main index page, then the superglobals are returning as expected. My site structure is like this:
index.php
- JavaScript buttons use AJAX HTTP requests to include the "responseText" as the .innerHTML of my main < div >. The "responseText" is the contents of the page itself, in this case page_manager.php, which in turn includes pagination.php.
So in other words, my site is built from PHP includes, which doesn't seem to be compatible with HTTP superglobals.
Any idea how I can get around this problem? Thank you :-).
+------------------------------------------------------------------+
I can't answer my own posts, so:
The problem is not solved, but has been worked around.
I am certainly not very knowledgeable when it comes to PHP, but I am of the impression that using AJAX requests to include a PHP file in a document, which itself includes other PHP files, is not a good idea. The problem, I believe, was being caused because PHP is executed before the document is loaded in to the browser. Therefore, dynamically including a PHP file in a document will result in the improper working of said file due to the fact that PHP must be executed by the server before the page is rendered, and not after.
As such, I have stopped using AJAX for my site and am simply using good old PHP instead. I don't know enough to carry on using the AJAX requests, so that's an end to that problem.
Thanks to those who replied.
You need to re-pass the superglobals to the AJAX calls. So where you would make a request to pagination.php you need to make it to pagination.php?pagenumber_form=<?php echo $_GET['pagenumber_form']; ?>.
the corresponding value gets added to the URL as: ".../pagenumber_form=X
You might wanna try
.../?pagenumber_form=X
Included files can access superglobals just fine (which is what makes them super). What can't be done is to access variables from one request in another. It isn't that clear what your code is doing (since the question doesn't include a proper minimal test case–a complete, concise, representative sample), but it sounds like loading a single page involves multiple requests, and only the first of these is given the form data. Each AJAX request involves a separate HTTP request, and (because HTTP is supposed to be stateless) has different request data, so any request that isn't explicitly given the data won't have access to it. After a request is handled, all data the script has access to is discarded. This is why if you need data to exist across requests, you need some form of persistence, such as sessions (which you should be careful of, in order not to break the HTTP stateless model) or databases.
Some of the difficulty may lie in a confusion over exactly what happens server-side, what happens client-side, what happens between the two and in what order it all happens. Before you go further, read up on HTTP (a web search should reveal countless documents on the topic). You can use debuggers (e.g. Firebug, XDebug+a client, Wireshark, Live HTTP Headers) to peer at what's happening as it happens.

Why is javascript not able to use a javascript variable I declared in a php file?

Hey everybody, this issue has had me stumped for the last week or so, here's the situation:
I've got a site hosted using GoDaddy hosting. The three files used in this issue are index.html , milktruck.js , and xml_http_request.php all hosted in the same directory.
The index.html file makes reference to the milktruck.js file with the following code:
<script type="text/javascript" src="milktruck.js"></script>
The milktruck.js file automatically fires when the site is opened. The xml_http_request.php has not fired at this point.
On line 79 out of 2000 I'm passing the variable "simple" to a function within the milktruck.js file with:
placem('p2','pp2', simple, window['lla0_2'],window['lla1_2'],window['lla2_2']);
"simple" was never initialized within the milktruck.js file. Instead I've included the following line of code in the xml_http_request.php file:
echo "<script> var simple = 'string o text'; </script>";
At this point I have not made any reference whatsoever to the xml_http_request.php file within the milktruck.js file. I don't reference that file until line 661 of the milktruck.js file with the following line of code:
xmlhttp.open('GET',"xml_http_request.php?pid="+pid+"&unLoader=true", false);
Everything compiles (I'm assuming because my game runs) , however the placem function doesn't run properly because the string 'string o text' never shows up.
If I was to comment out the line of code within the php file initializing "simple" and include the following line of code just before I call the function placem, everything works fine and the text shows up:
var simple = 'string o text';
Where do you think the problem is here? Do I need to call the php file before I try using the "simple" variable in the javascript file? How would I do that? Or is there something wrong with my code?
So, we meet again!
Buried in the question comments is the link to the actual Javascript file. It's 2,200 lines, 73kb, and poorly formatted. It's also derived from a demo for the Google Earth API.
As noted in both the comments here and in previous questions, you may be suffering from a fundamental misunderstanding about how PHP works, and how PHP interacts with Javascript.
Let's take a look at lines 62-67 of milktruck.js:
//experiment with php and javascript interaction
//'<?php $simpleString = "i hope this works"; ?>'
//var simple = "<?php echo $simpleString; ?>";
The reason this never worked is because files with the .js extension are not processed by PHP without doing some bizarre configuration changes on your server. Being on shared hosting, you won't be able to do that. Instead, you can rename the file with the .php extension. This will allow PHP to process the file, and allow the commands you entered to actually work.
You will need to make one more change to the file. At the very top, the very very top, before anything else, you will need the following line:
<?php header('Content-Type: text/javascript'); ?>
This command will tell the browser that the file being returned is Javascript. This is needed because PHP normally outputs HTML, not Javascript. Some browsers will not recognize the script if it isn't identified as Javascript.
Now that we've got that out of the way...
Instead I've included the following line of code in the xml_http_request.php file: <a script tag>
This is very unlikely to work. If it does work, it's probably by accident. We're not dealing with a normal ajax library here. We're dealing with some wacky thing created by the Google Earth folks a very, very long time ago.
Except for one or two in that entire monolithic chunk of code, there are no ajax requests that actually process the result. This means that it's unlikely that the script tag could be processed. Further, the one or two that do process the result actually treat it as XML and return a document. It's very unlikely that the script tag is processed there either.
This is going to explain why the variable never shows up reliably in Javascript.
If you need to return executable code from your ajax calls, and do so reliably, you'll want to adopt a mature, well-tested Javascript library like jQuery. Don't worry, you can mix and match the existing code and jQuery if you really wanted to. There's an API call just to load additional scripts. If you just wanted to return data, that's what JSON is for. You can have PHP code emit JSON and have jQuery fetch it. That's a heck of a lot faster, easier, and more convenient than your current unfortunate mess.
Oh, and get Firebug or use Chrome / Safari's dev tools, they will save you a great deal of Javascript pain.
However...
I'm going to be very frank here. This is bad code. This is horrible code. It's poorly formatted, the commenting is a joke, and there are roughly one point seven billion global variables. The code scares me. It scares me deeply. I would be hesitant to touch it with a ten foot pole.
I would not wish maintenance of this code on my worst enemy, and here you are, trying to do something odd with it.
I heartily encourage you to hone your skills on a codebase that is less archaic and obtuse than this one before returning to this project. Save your sanity, get out while you still can!
perhaps init your values like this:
window.simple = 'blah blah blah'
then pass window.simple
You could try the debugger to see what is going on, eg. FireBug

How to store search result?

I am working on my personal site, where I want to store my customers recent search result limited to that particular session.
I am using PHP platform and Javascripts.
Here is an example of what I am exactly looking at :
It stores your previously searched domain name for that particular session so that user can make decision by comparing those results.
Thanks.
EDIT- Well Thanks for all of your answers and suggestions.
But If you have noticed
above example
It looks like some kind of script loading a new content on the same page without refreshing it and keeping previous search content <div> as it is.
How to achieve this using javascripts or some sort of div layer ????
UPDATE START
This example uses page reload. If you want to do it without page reload, you can but you'll have to use AJAX to load new search results. But then, it's not a PHP question. I suggest looking at jquery library, as it makes it easy. Tutorials: http://docs.jquery.com/Tutorials and e.g. this one ( http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery#Rate_me:_Using_Ajax ).
When loading data via AJAX, the page rendering result (in my example search.php) should return only HTML for results part, not whole HTML page. This is generally a first part of my tutorial (without session).
But I really think that AJAX in here is not really needed. Session is more reliable and allows access to your page from older / mobile browsers where not always JS works correctly.
UPDATE END
Ok then. Let's try the simple tutorial then. Sorry if too simple, but I don't know your exact level.
PHP has mechanism called sessions. In reality they are just bytes stored on server. Server knows which session is for each client by reading session cookie from client browser.
Not every page uses sessions (not every page needs it, and session uses server space, even if only temporarily), session is not enabled by default. To turn on session you use command
<?php session_start(); ?>
In most cases this is either run by PHP framework you use, or put near the top of your site. Session is definitely needed if you want to authenticate user somehow. Or in your case :)
To access session you can use superglobal $_SESSION variable (superglobal means that you can access it anywhere). It's an array, so session element will be e.g. $_SESSION['search'] etc.
As example, let's assume that your page looks like that
<html>
...
<form action="search.php" method="post">
Search: <input type="text" name="searchQuery" />
<input type="submit" value="Search" />
</form>
...
</html>
this very form will send user search to file named search.php. It can be the same file where the form resides - in simplest case when you put both your code and HTML in one file. Beginners often use this schema, although it's not advisable as result is a mess and hard to further change.
In search.php then, you'll use similar code:
<?php
if (!empty($_POST['searchQuery'])) //we have a new search
{
$result = do_search($_POST['searchQuery']);
}
?>
Then, somewhere below you'll display your search result ($result variable). do_search() function is your search mechanism, I guess you have it somewhere. You may have it not 'wrapped' in a function, then I advise to create it like that, it's much more useful.
function do_search($searchQuery)
{
...
return $result;
}
mind it, the above code doesn't use sessions yet. Let's add saving previous search results in session. The code may then look like that:
<?php
session_start(); //Starting session
//let's create session variable used to store results
if (!isset($_SESSION['searches']))
$_SESSION['searches'] = array();
if (!empty($_POST['searchQuery'])) //we have a new search
{
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value, delete previous result from sesion
{
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
$result = do_search($_POST['searchQuery']);
//Let's add new search on the begining of session array to make iterations easier.
$result = array($_POST['searchQuery'] => $result); //convert result to same format as session table
$_SESSION['searches'] = array_merge($result, $_SESSION['searches']);
}
?>
In display you'll now not iterate on $result variable as before, but instead you will do something like
foreach ($_SESSION['searches'] as $query => $result)
{
...//display of single result
}
I haven't tested following code and it's not a full program. Parts to display result and to do actual search are not described but I guess you have them already prepared. Also, this is only one possible approach of countless possibilities. But I hope this helps :)
Possible modification - now I always perform search, even if user already searched on this term. You may want to receive the result from cache without second search. Then the code will look like
if (isset($_SESSION['searches'][$_POST['searchQuery']]) //User already searched on this value
{
$result = $_SESSION['searches'][$_POST['searchQuery']];
unset($_SESSION['searches'][$_POST['searchQuery']]);
}
else
{
$result = do_search($_POST['searchQuery']);
}
For more in-depth information about sessions and some other constructs used in my example I suggest PHP manual
http://pl.php.net/manual/en/book.session.php
and various tutorials over the network. Or you can add a comment here :)
Put this code near the beginning of your script(s):
if (!isset($_SESSION['previous_searches']) || !is_array($_SESSION['previous_searches'])) {
$_SESSION['previous_searches'] = array();
}
[edit]
This code snippet checks if if there is already an array with prevous searches and if not it will be created.
[/edit]
Then when the user hits the search page put this code in the receiving script of the search:
$_SESSION['previous_searches'][] = $_GET['what_ever_your_search_value_might_be'];
[edit]
This code snippet adds the current search value to the and of the array with previous search values
[/edit]
Now you have all previous search values in $_SESSION['previous_searches']
If your website is a web application where you never reload the page nor change the page, you can keep it JavaScript in a global store (declare at top level something like var StoredSearch = []; and use it). If not, then use $_SESSION to store this and AJAX to save/load searches from JavaScript to PHP.

Categories