PDA

View Full Version : AJAX Button, how can I pass a var? Help appreciated.



clowes
08-08-2008, 07:28 PM
Ok I am new to javascript, and AJAX and am literally playing around to get things to work for specific things.

My setup is as follows.
I have a list of items which I have grabbed from a mysql database, e.g apple, pear, banana, orange, lemon. Each is a button, with the image of the respective item.

I have set up the javascript so that onclicking the button a php file called deleteitem.php is called which contains the code to delete the item.

deleteitem.php literally has a mysql query DELETE where ID='1' it works perfectly , and deletes the item with ID 1 on clicking one of the buttons.

What I want is to pass a variable to the deleteitem.php script containing the ID of the item I want to delete. The intention is that each button deletes its respective item, whereas at the moment all the buttons delete the same item (and the ID has to be set in deleteitem.php).

Is this doable? and how?

Many Thanks
T

Dal
08-08-2008, 08:37 PM
be aware that IE doesnt pass values if your using image buttons.

clowes
08-08-2008, 08:55 PM
Well Im just not sure how to do it in general... Ill simply use images (<img tags ) but how can I tell the PHP script WHICH image ive clicked on?

Dal
08-08-2008, 09:04 PM
You need to use AJAX to pass the id. I would recommend just using the $_GET method, its easier to setup. AJAX is called via a js function you place on the button either by an event listener or by the old method of onclick. Ive used onclick and it works fine but its much easier to script than the event listener method.

In your php script your just need to test for the query string coming through and then perform the action based on the id number you've sent.

So your ajax might point to the script deleteitem.php with the id from one of the click button. eg. deleteitem.php?id=12

inside the php script deleteitem.php you would have;

if(isset($_GET['id'])) calldelete($_GET['id']);

function calldelete($id2delete)
{
...your code...
}

clowes
08-08-2008, 10:12 PM
You need to use AJAX to pass the id. I would recommend just using the $_GET method, its easier to setup. AJAX is called via a js function you place on the button either by an event listener or by the old method of onclick. Ive used onclick and it works fine but its much easier to script than the event listener method.

In your php script your just need to test for the query string coming through and then perform the action based on the id number you've sent.

So your ajax might point to the script deleteitem.php with the id from one of the click button. eg. deleteitem.php?id=12

inside the php script deleteitem.php you would have;

if(isset($_GET['id'])) calldelete($_GET['id']);

function calldelete($id2delete)
{
...your code...
}


I completely understand the latter part of your explanation, I.E how to use the id when you have it in the php script as .php?id=12

Ive been using this tutorial to guide me:
http://www.tizag.com/ajaxTutorial/ajaxxmlhttprequest.php

Each button is <input type='button' onclick='ajaxFunction()'>
That runs the ajax which in turn calls deleteitem.php
I still dont understand however how I pass a specific ID to the php file

Thanks

Dal
08-08-2008, 10:20 PM
thats because you havent got to that part yet in the tutorial;

http://www.tizag.com/ajaxTutorial/ajax-mysql-database.php

at this point is where you can call ur script and apply the query string;

var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);

clowes
08-09-2008, 09:58 AM
thats because you havent got to that part yet in the tutorial;

http://www.tizag.com/ajaxTutorial/ajax-mysql-database.php

at this point is where you can call ur script and apply the query string;

var queryString = "?age=" + age + "&wpm=" + wpm + "&sex=" + sex;
ajaxRequest.open("GET", "ajax-example.php" + queryString, true);


No, I have gotten that far, Ive read the whole thing.
Its just that Im using a php while loop to output all the items, and each of the buttons are named as part of an array e.g item[0].

In the example there is a set field called age, and you get the value of the field... in my case there are numerous fields, and you dont know which one is being clicked...

Dal
08-09-2008, 12:41 PM
In that case, why dont you paste your code so I can see whats going on?

Thanks
Dal

clowes
08-09-2008, 04:13 PM
Ok this is the main page which grabs the items from a database using the a PHP object previously defined ($battle).



if($batt["playerstage$battle->userplayer"]=='TURN'){
$battle->location='HAND';
$yours=$battle->getallcards();
echo"<div id='ajaxDiv'>";
while($yourhand=mysql_fetch_array($yours)){
$name=$battle->getdetails($yourhand[cardid]);
echo"<form name=hand><input type=hidden name=cid value=$yourhand[ID]><input type=button name='card' value='$yourhand[ID]' onclick='ajaxFunction();'></FORM>";
}

if ($battle->count>'7'){echo"<br>You can only have 7 cards in your hand at any one time.";}
}
echo"</div>";

?>
<html>
<body>

<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(){
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}



ajaxRequest.open("GET", "discardcard.php", true);
ajaxRequest.send(null);
}

//-->
</script>




The deleteitem.php page looks like this


<?php
include"cards2.php";
$b=rand(1,100);
echo"Card Discarded $b";

$battle=new battle;
$battle->ucardid='1';
$battle->location='DECK';
$battle->movecard();
$battle->location='HAND';
$yours=$battle->getallcards();
echo"<div id='ajaxDiv'>";
while($yourhand=mysql_fetch_array($yours)){
$name=$battle->getdetails($yourhand[cardid]);
echo"<form name=hand><input type=hidden name=cid value=$yourhand[ID]><input type=button name='card' value='$yourhand[ID]' onclick='ajaxFunction();'></FORM>";
}

if ($battle->count>'7'){echo"<br>You can only have 7 cards in your hand at any one time.";}
echo"</div>";

?>
<html>
<body>




This works in that onclicking a button it deletes the item from the database with id 1 per this line:

$battle->ucardid='1';

What I want however is to pass a variable so that onclicking a specific button, it deletes that specific item.

Cheers

Dal
08-09-2008, 11:58 PM
value='$yourhand[ID]' onclick='ajaxFunction({$yourhand[ID]});'>

then

function ajaxFunction(CardID){
...

var QString = "?card"+CardID;
ajaxRequest.open("GET", "discardcard.php"+QString, true);


Then in your php


collect the value by running a $_GET['card']; this will equal the id passed

Pass this value along to the delete function which I havent looked for but Im sure you'll be on the right track after this.

:)
Best of luck
Dal

clowes
08-10-2008, 10:25 AM
value='$yourhand[ID]' onclick='ajaxFunction({$yourhand[ID]});'>

then

function ajaxFunction(CardID){
...

var QString = "?card"+CardID;
ajaxRequest.open("GET", "discardcard.php"+QString, true);


Then in your php


collect the value by running a $_GET['card']; this will equal the id passed

Pass this value along to the delete function which I havent looked for but Im sure you'll be on the right track after this.

:)
Best of luck
Dal



Absolutely brilliant. First Class.
If possible I have a few further questions.


<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function ajaxFunction(CardID){
var ajaxRequest; // The variable that makes Ajax possible!

try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}


var QString = "?card="+CardID;
//document.write(QString);
ajaxRequest.open("GET", "discardcard.php"+QString, true);
ajaxRequest.send(null);
}

//-->
</script>

That is my code, I can put an onclick on each button and then it is processed. Perfect.

That part of my code is done. I now want to do something completely different whereby again I click a button but this time it sends a request to a different php file, and is processed in a different way.

Do I simply copy and paste the above code again and change the line

ajaxRequest.open("GET", "discardcard.php"+QString, true); to my new processing page, or is there any way of recycling the browser check part of the ajaxFunction() function?

Many Thanks

Dal
08-10-2008, 03:28 PM
If you want to use a function to do all the checking then this would be cleaner, however, you could fine tune later anyway, the important thing here is to learn and experience ajax in all its beauty and querks so just hard code the second task then you can worry about fine tuning it when its working, this is easier to id the problem - if you know its working in the first place.

You werent far off with your original request, you just obvously got lost in the ajax, thats all, so Im sure you'll manage to understand it.

Kind regards
Dal

PS, ajax for me is a pain and Im still trying to fine tune it so that I can create a function to do all my tasks on my website, however, be warned that I started making everything ajax which I realised was unecessary. Dont get pulled into over-use of this technology, its harder to build and maintain and so far my code for ajax is sloppy.

clowes
08-10-2008, 03:37 PM
Thanks very much Dal for all your help.

Ive got my original request sorted, and everything is fitting into place with my other little attempts.

I dont like having long scripts, thats my problem :)

Out of interest say in a long complex script I have 500 lines of ajax, 300 of which are just repeating the same thing. What effect will that have on script performance??

Also I appreciate that too much ajax can be bad. I am only using it at all because thescript Im coding would have like a zillion page refreshes otherwise, and AJAX makes it work more seamlessly. Again how does AJAX relate into resources?

Finally security.

ajaxRequest.open("GET", "discardcard.php"+QString, true);

That seems to be the main source of a security vulnarability.
If the user accesses discardcard.php directly and I havnt put security measures in place, then there could be problems.

Say I code into discardcard.php that only requests made from this script should be processed, is there any other ways that the code can be exploited?

Thanks again

Dal
08-10-2008, 03:49 PM
Wells theres a thing, users can bypass the ajax if they understand the code but heres where the security come in;

For instance;

a user wants to update their first name using ajax, it would be the php side that says to the database

update firstname where userindex = loggedindex (the loggedindex would be that of the logging in stage so for example 10)

so even if the user hardcoded the query in then they could still only just change their own account. Its char validation that you really need to check for for example someone trying to punch in a script instead of a firstname entry is where you have the protection.

As for resources, its the same as hitting a submit button, it just sends it to the server asynchronous.

As for the script being longer, well its just characters so the download time will not be effected.

Thanks
Dal

clowes
08-10-2008, 04:07 PM
Right awesome, youve answered all my questions perfectly.
Thanks again

Dal
08-10-2008, 04:09 PM
No problem clowes, all the best in your developments.

Kind regards
Dal