• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 320
  • Last Modified:

Ajax, PHP, Javascript... having trouble getting simple function to work.

I am looking for someone to steer me in the correct direction on this. I am working on a project which is purely academic. I am trying to learn to use PHP, Ajax, MySQL and javascript. The issue I am having is this:

The user is presented with a photograph and a form. One of the form items is 'people' and next to the form input is a button labeled 'add'. The user is able to put a name in and click 'add', the name shows up below the input box. At this point the user can add or remove items from the list until they get the desired names of people represented in the photo. Then they will hit the 'submit' button to send the information to the PHP code to be added into the database. So it seems to me that it would be best to do the add/remove in a client side situation.

I have used hidden input fields to get the names on the screen but I am unsure of where to go from there.  I need the items that are in the hidden inputs to be in an array. Should I use SESSIONS? That doesn't seem right either.

I feel that I am missing something here. The hidden inputs idea for this application seems to be cumbersome and messy. Is there a better method to achieve this? Can I use ajax to make this more streamlined and easier to interact with? Point me in the right direction!

Thanks!
0
farroar
Asked:
farroar
  • 7
  • 5
1 Solution
 
gam3r_3xtr3m3Commented:
there are actually a lot of different ways you can do this, but a few solutions could be:

1) use JavaScript and limit each names with a semi-colon for example, then send the list through a hidden input form, delimiting the string afterward in PHP.

<script>
...
var names = "";
function addName(name) {
    names += name + ";";
}
function submitMe() {
    name_list.value=names;
}
...
</script>
...
<form onSubmit="submitMe();">
<input type="hidden" name="name_list" />
</form>
...

2) use AJAX and PHP (with a database, like MySQL) with a temporary database table to add / remove names.

for every names added, do an INSERT INTO temp_names and return the record key in the XMLHTTP response text. make sure to include an identifier (session key, user id, etc.) for all of these temporary records.
for every names removed, do a DELETE FROM temp_names WHERE id = <the record key>.

on submit, SELECT * temp_names WHERE identifier = <identifier key> and move them to the actual permanent table.


Hope that helps,

Andrew
0
 
farroarAuthor Commented:
The temporary database seems like a nice idea. I need to learn more about AJAX, but from what I understand I can use it to link to a PHP page with the appropriate function to add names into this temporary database and return them to display on the page without having to reload the page?
0
 
gam3r_3xtr3m3Commented:
exactly. here's a small snipplet to give you a sort of idea how they work out:
// script.js
 
if( typeof XMLHttpRequest == "undefined" ) XMLHttpRequest = function() {
	try { return new ActiveXObject("Msxml2.XMLHTTP.6.0") } catch(e) {}
	try { return new ActiveXObject("Msxml2.XMLHTTP.3.0") } catch(e) {}
	try { return new ActiveXObject("Msxml2.XMLHTTP") } catch(e) {}
	try { return new ActiveXObject("Microsoft.XMLHTTP") } catch(e) {}
	throw new Error( "This browser does not support XMLHttpRequest." )
};
 
function addNew(name) {
 
	var request =  new XMLHttpRequest();
	request.onreadystatechange = function() {
		if(request.readyState == 4 && request.status == 200) {
 
			// grab the ID in (request.responseText)
			// and add the corresponding fields here
			// (dynamic div's, remove link, etc.)
 
		}
	};
	request.open("POST", "add.php");
	request.send("name=" + name);
 
}
 
function remove(id) {
 
	var request =  new XMLHttpRequest();
	request.onreadystatechange = function() {
		if(request.readyState == 4 && request.status == 200) {
 
			// check if successful (1 or -1)
			// and then remove the corresponding
			// display elements (div's, links, etc.)
 
		}
	};
	request.open("POST", "remove.php");
	request.send("id=" + id);
 
}
 
// add.php
 
<?php
	session_start();
 
	$host = 'my.domain.com';
	$port = '3306'
	$user = 'username';
	$pass = 'password';
	$name = 'database';
 
	$conn = mysql_connect($host.":".$port, $user, $pass) or die("-1");
	mysql_select_db($name) or die("-1");
 
	if(!empty($POST["name"])) {
 
		// additional checks might be handy here
 
		// insert into temporary database
		$sql = "INSERT INTO temp(ident, name) VALUES (".$session_id.", ".$_POST["name"].")";
 
		mysql_query($sql);
 
		// output auto-generated row ID
		echo(mysql_insert_id($conn));
 
	// return -1 for errors
	} else echo("-1");	
 
 
	mysql_close($conn);
 
?>
 
// remove.php
 
<?php
	session_start();
 
	$host = 'my.domain.com';
	$port = '3306'
	$user = 'username';
	$pass = 'password';
	$name = 'database';
 
	$conn = mysql_connect($host.":".$port, $user, $pass) or die("-1");
	mysql_select_db($name) or die("-1");
 
	if(!empty($POST["id"])) {
 
		// additional checks might be handy here
 
		// insert into temporary database
		$sql = "DELETE FROM temp WHERE id = " . $_POST["id"];
 
		mysql_query($sql);
 
		echo("1");
 
	// return -1 for errors
	} else echo("-1");	
 
 
	mysql_close($conn);
 
?>

Open in new window

0
What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

 
gam3r_3xtr3m3Commented:
oh no, $session_id must be session_id() .. sorry about that and for any other typos unaccounted for (if there are still some left). I was too excited to submit the code. =))

Hope that helps,

Andrew
0
 
farroarAuthor Commented:
Looks about right! I'll give it a go, you pointed me in the right direction.
0
 
gam3r_3xtr3m3Commented:
thank you, points well appreciated. i'm glad to have helped.

Andrew
0
 
farroarAuthor Commented:
I am another question for you! My temporary database will have the fields 'id' (auto increment), 'ident' for the session id of current user, and 'name' for the name added. On the add.php page we are going to echo the insert id, where does this echo to? I guess I'm not understanding javascript that well yet, I am assuming that we want to capture that id and use it as an identifier for the name that is displayed on the page.

Since I am new to AJAX and javascript, perhaps you could give me a quick "order of operations". I understand the code, I am just not following the path of processing. I would really appreciate it!

Thanks
0
 
gam3r_3xtr3m3Commented:
well, the echo statement just acts like printf, or the sort. so basically we need that information to relay to the JavaScript side of things, which is taken from request.responseText (which actually contains any output of the add.php, so for example if php had an internal error or sorts, the responseText would contain them, or if you want to load another HTML page dynamically on JavaScript, you can try replacing add.php to another page and do a document.write(request.responseText)), this is how AJAX basically works.

for the order of operations, well:

1) you should have the input box for the name and an add button
2) the add button would receive the event to call addNew(input.value)
3) the addNew function send the POST request with the name to the add.php
(this is very similar to submitting a form with a POST action, only this one is done in the background, JavaScript style)
4) add.php will output the corresponding ID for the record, or -1 for an error
5) we then use the ID to build a dynamic remove button, having the pre-made remove(ID) function
6) once remove(ID) is called (or remove button is pressed), we will then again send a POST request to remove.php, this time requesting to delete the ID sent on the request
7) remove.php will then output 1 for success, -1 for an error
8) and there you have it, after all add/removes are done, simply move all the records with the same session identifiers to the permanent database table

Hope that helps,

Andrew
0
 
farroarAuthor Commented:
Great. That helps a lot. Thanks again.
0
 
gam3r_3xtr3m3Commented:
With pleasure. Good luck on that.

Andrew
0
 
farroarAuthor Commented:
I have been working through the code you explained to me and I am having some trouble. If you wouldn't mind helping me out again.

In this addNew function I doesn't the request.open and request.send need to come before the request.responseText? I see that the idea is to establish the communication state at ready with AJAX then we want to get the id number of the value we just entered into the temporary database, then add the name to the page with a remove button next to it. Am I correct?

Oh, and i call the addName function like this, <a href="" onclick="addName(personName.value);">add</a> where personName is the id of the input field.. is this correct? Thanks
function addNew(name) {
 
        var request =  new XMLHttpRequest();
        request.onreadystatechange = function() {
                if(request.readyState == 4 && request.status == 200) {
 
                        // grab the ID in (request.responseText)
                        // and add the corresponding fields here
                        // (dynamic div's, remove link, etc.)
 
                }
        };
        request.open("POST", "add.php");
        request.send("name=" + name);

Open in new window

0
 
gam3r_3xtr3m3Commented:
request.onreadystatechange is actually an event handler. we check the readyState and the status to make sure everything is loaded in the responseText (or it has finished the transaction successfully). if it's not working, try to remove the condition request.status == 200, this may be because you are testing locally on opened HTML files.

yes, the other inquiries are correct.
0

Featured Post

Industry Leaders: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 7
  • 5
Tackle projects and never again get stuck behind a technical roadblock.
Join Now