/    Sign up×
Community /Pin to ProfileBookmark

Hi all. I am trying to pass values from a form through a “url query string” to update.php (using Ajax). ‘update.php’ retrieves the string and copies it to a database. Should I be using Get or Post for this?

I have created some code that sends the query string, but it will not post to the database. Can someone run through this simple code real quick and help me find the (probably) simple solution?

example.html:

[CODE]<html>

<head>

<script type=”text/javascript”>

function showCustomer()

{

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject(“Microsoft.XMLHTTP”);

}

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById(“txtHint”).innerHTML=xmlhttp.responseText;

}

}

var match = document.getElementById(‘match’).value;

var score = document.getElementById(‘score’).value;

var queryString = “?match=” + match + “&score=” + score;

xmlhttp.open(“GET”, “update.php” + queryString,true);

xmlhttp.send();

}

</script>

</head>

<body>

<form action=””>

<select name=”match” id=”match”>

<option value=”Eng1 ChelseaLiverpool”>Chelsea – Liverpool</option>

<option value=”EngFACup ArsenalWigan”>Arsenal – Wigan</option>

<option value=”Eng2 WatBromley”>Watford – Bromley</option>

<option value=”Sing1 SAFGombak”>SAF – Gombak United</option>

</select>

<select name=”score” id=”score”>

<option value=”00″>0-0</option>

<option value=”10″>1-0</option>

<option value=”01″>0-1</option>

<option value=”11″>1-1</option>

</select>

<input type=”submit” onclick=”showCustomer()” value=”Submit Pick” />

</body>

</html> [/CODE]

update.php:

[CODE]<?php

$match = $_GET[‘match’];

$score = $_GET[‘score’];

mysql_connect (‘localhost’, ‘admin’, ‘password’) or die (‘Error: ‘ .mysql_error());

mysql_select_db (“example_db”);

$query=”INSERT INTO user (FirstName, Lastname)VALUES (‘”.$match.”‘, ‘”.$score.”‘)”;

mysql_query($query) or die (‘Error submitting’);

?>

[/CODE]

to post a comment
PHP

19 Comments(s)

Copy linkTweet thisAlerts:
@aj_nscApr 29.2011 — Both will do the trick....but think of it this way...are you [B]GET[/B]ting data from the server, or are you [B]POST[/B]ing data to the server? ?
Copy linkTweet thisAlerts:
@rproctor83Apr 29.2011 — I agree with AJ, I only use post when I am actually posting data to the server. Post is also more obtrusive than get, however in an ajax type environment both get and post are about the same.
Copy linkTweet thisAlerts:
@inplaytodayauthorApr 29.2011 — I agree with AJ, I only use post when I am actually posting data to the server. Post is also more obtrusive than get, however in an ajax type environment both get and post are about the same.[/QUOTE]

thanks for your responses guys.

Even after changing the above code to POST (in both html and php file), the data will not post to the database. It must be something simple I'm missing here..
Copy linkTweet thisAlerts:
@aj_nscApr 29.2011 — Are you getting a response back from the server? I'd recommend using a browser where you can watch the Network requests (using firebug, or chrome developer tools and click on "Network")
Copy linkTweet thisAlerts:
@inplaytodayauthorApr 29.2011 — I've used the following code and added at the bottom "echo $score;" that should change 'ajaxDiv' in the html page, but it still returns nothing and is not submitting to database. I assume that means I'm not getting a response from the server?

example.html:
[CODE]
<html>

<head>
<script type="text/javascript">
function showCustomer()
{
var xmlhttp;

if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = xmlhttp.responseText;
}
}
var match = document.getElementById('match').options[document.getElementById('match').selectedIndex].value;
var score = document.getElementById('score').options[document.getElementById('score').selectedIndex].value;
var queryString = "?match=" + match + "&score=" + score;

xmlhttp.open("POST", "update.php" + queryString,true);
xmlhttp.send();
}
</script>
</head>


<body>

<form action="">
<select name="match" id="match">
<option value="Eng1 ChelseaLiverpool">Chelsea - Liverpool</option>
<option value="EngFACup ArsenalWigan">Arsenal - Wigan</option>
<option value="Eng2 WatBromley">Watford - Bromley</option>
<option value="Sing1 SAFGombak">SAF - Gombak United</option>
</select>


<select name="score" id="score">
<option value="00">0-0</option>
<option value="10">1-0</option>
<option value="01">0-1</option>
<option value="11">1-1</option>
</select>

<input type="submit" onclick="showCustomer()" value="Submit Pick" />

<div id='ajaxDiv'>Your result will display here</div>

</body>
</html>
[/CODE]


update.php:
[CODE]
<?php

$match = $_POST['match'];
$score = $_POST['score'];


mysql_connect ('localhost', 'admin', 'password') or die ('Error: ' .mysql_error());
mysql_select_db ("example_db");

$query="INSERT INTO user (FirstName, Lastname)VALUES ('".$match."', '".$score."')";
mysql_query($query) or die ('Error submitting');

echo $score;

?>

[/CODE]
Copy linkTweet thisAlerts:
@themartyApr 29.2011 — As said before, try analyzing what happens. The LiveHttpHeaders addon for firefox is a good tool for doing this for example.

What you can also do is recreate the form you're trying to submit in a static html file that posts it to the update-script. In this script you can then echo all the debug-information you want. Once you got that working you'll know that the update script is working fine so you can concentrate on the ajax mechanism.

btw: The guidelines state that GET is to retrieve data from a server and POST is for modifying data on the server. And although it would be good practice to follow those guidelines, you don't have to.
Copy linkTweet thisAlerts:
@DasherApr 29.2011 — You may need to add to your form tag;

<form method="GET" action = "$_SERVER['PHP_SELF']" >

or

<form method="POST" action = "$_SERVER['PHP_SELF']" >
Copy linkTweet thisAlerts:
@inplaytodayauthorApr 29.2011 — As said before, try analyzing what happens. The LiveHttpHeaders addon for firefox is a good tool for doing this for example.

What you can also do is recreate the form you're trying to submit in a static html file that posts it to the update-script. In this script you can then echo all the debug-information you want. Once you got that working you'll know that the update script is working fine so you can concentrate on the ajax mechanism.

btw: The guidelines state that GET is to retrieve data from a server and POST is for modifying data on the server. And although it would be good practice to follow those guidelines, you don't have to.[/QUOTE]


when analysing using LiveHttpHeaders, the script comes up with the following requests/responses after loading the page and clicking submit:

[CODE]
#request# GET http://example.com/example.html
#request# POST http://example.com/update.php?match=Eng1&#37;20ChelseaLiverpool&score=00
#request# GET http://example.com/lsl4.html?match=Eng1+ChelseaLiverpool&score=00
[/CODE]


why does it appear to be using GET And POST?
Copy linkTweet thisAlerts:
@aj_nscApr 29.2011 — It's not using a GET and a POST. Look at the URL's they're different

POST - http://example.com/update.php?match=Eng1&#37;20ChelseaLiverpool&score=00

GET - http://example.com/lsl4.html?match=Eng1+ChelseaLiverpool&score=00.php?match=Eng1%20ChelseaLiverpool&score=00

So, it appears that another AJAX request is getting made, perhaps at the same time. It's in your code somewhere...go find it!!

I've never used LiveHTTPHeaders...but if they have an option, click on the request to see the raw response that comes back when you make that request. Also, at this time, make sure error reporting is turned on in the PHP scripts so that if the script dies for some reason, you still get an error returned back to your AJAX request.
Copy linkTweet thisAlerts:
@inplaytodayauthorApr 30.2011 — hehe..don't i feel silly. i forgot to close the form.

I have changed from POST to GET as this seems to be returning data to my div in addition to posting to the database, while POST only submits to database.

thank you all for your help, especially Jaks.

This issue is resolved, at least for me. ?
Copy linkTweet thisAlerts:
@aj_nscApr 30.2011 — 
I have changed from POST to GET as this seems to be returning data to my div in addition to posting to the database, while POST only submits to database.
[/quote]


While, in terms of AJAX, I don't think POST vs GET really makes that much of a difference (I encourage people who know more about this to me to disagree with me and make me more informed), I like to use POST or GET depending on the MAIN functionality of the request. If the MAIN function is to post info to the database, then I use POST. If the MAIN function is to request data from the server, then I use GET.

I would say 90&#37; of the time, your AJAX functions will ALWAYS have information returned to them (indicating some sort of success vs failure, aside from the readyState and status properties), but that's not to alter the main function of your application is to GET information.
Copy linkTweet thisAlerts:
@DariaMay 02.2011 — OK guys, maybe I'm throwing a monkey wrench in here... In addition to the above conversation... There is a school of though out there that POST is safer then GET in terms of sql-injection-proofing it. (I'd like to hear NogDog's take on it!)
Copy linkTweet thisAlerts:
@aj_nscMay 02.2011 — Well, you can get whomever's take you want on it. It's FALSE.

GET and POST variables, as well as any other user-input variables need to be sanitized before you can put their input into any form of SQL query. NO DIFFERENCE.

I'm not going to say here that GET and POST are equal in terms of resources, methods of processing, etc, because 1) they are not and 2) I don't know what the differences actually are but I do know that there is NO DIFFERENCE in terms of SQL-injection proofing user input data....it's the same no matter what method your form uses.


I'd really like to be directed to a "school of thought" regarding this....I really think you may be mistaken on what the two camps on GET vs POST are actually divided on, I can assure you it's not SQL-injection related.
Copy linkTweet thisAlerts:
@svidgenMay 02.2011 — This is a pretty non-critical issue. You use one or the other and be done with it. You just have to be aware of a few considerations:

[B]GET's are often much easier to test than POST's.[/B]

You open a tab/window, drop the request in the address bar and hit ENTER. You get the results back and you can see whether they're correct. POST's, on the other hand, require you to build a form, echo request/response data on-page, or use a tool like Fiddler (or telnet ?).

[B]Script kiddies will more likely play with your GET's than your POST's.[/B]

When some young pup stumbles onto your site and looks at your source or page request history, he might notice some "unprotected" GET's. Since they're so easy to reproduce, he might play around until he breaks something -- or post a link in his FB feed that causes other users to perform actions they didn't intend to perform.

This is much less likely to occur if you use POST's. That young pup will A) be more interested in playing WoW than futzing with POST's and ? not be able to drop a link in his FB feed to do malicious things with your AJAX requests. He could still, of course, put a link to a form that resides on HIS site and POSTs to yours -- or toy with your non-AJAX links.

[B]GET's make for some really elegant JSONP.[/B]

Outside of my real job, where I'm a Business Systems Developer who works extensively with Dynamics CRM, I have managed to use use GET's for asynchronous actions exclusively. And I'm well pleased with that, because it spares me [B]entirely[/B] from all cross-browser compatibility issues. I dynamically add SCRIPT tags to the end of my document body, respond with JSONP, and it works [B]everywhere[/B]. Recently, I even attempted to remove "used" SCRIPT tags (those over N seconds old) to reduce memory leakage and found that even that appears to work quite well.

It's really elegant, really easy, and really comforting to have a solution which every browser deals with correctly -- and has done so (to the best of my knowledge) long before anyone used the term "AJAX."

[B]GET's are more often cached than POST's.[/B]

This isn't usually a significant issue either. You just need to remember to add a timestamp (or something) to your GET's to force the browser to make the request, rather than using the cached version (unless you want the cached version). POST's on the other hand, tend to avoid the cache -- the POST method indicates to the browser that this request isn't about GETting data, it's about POSTing it.

[B]GET's have a relatively low data limit.[/B]

I think the limit is 2kb in IE, including the base URL. So, if you need to "post" more than 1.9kb, you need to use a POST or [I]multiple[/I] GET's. Generally speaking, since you're not an idiot, you've protected yourself against the aforementioned script kiddie and duplicate requests, and [B]it really comes down to this issue[/B]: whether your requests contain less than 2kb of data, including the base URL, but excluding cookies.


[I]... to name a few.[/I] [U]Now, one last point:[/U]


[B]All HTTP requests must be treated with suspicion.[/B]

Injection can occur equally easily under each method. Really, the only distinction I see from a malicious perspective is the lack of motivation most folks will have to sit and play with large POST's -- as opposed to GET's, which they can simply copy/paste/edit right in their browser's address bar. On the other hand, it's not terribly difficult to open Fiddler and ... umm ... [I]fiddle around[/I] in there either.
Copy linkTweet thisAlerts:
@NogDogMay 03.2011 — Basically, I follow the HTML specification recommendation:

The "get" method should be used when the form is idempotent (i.e., causes no side-effects). Many database searches have no visible side-effects and make ideal applications for the "get" method.

If the service associated with the processing of a form causes side effects (for example, if the form modifies a database or subscription to a service), the "post" method should be used.
[/quote]

The one exception would be if the above pointed toward using GET, but for some reason a large amount of data needs to be passed as part of the request, and as such may not fit within the max size allowed for a GET request (which can vary, there is not a specificied limit), in which case I'll then use POST. However, off-hand, I can't think of a situation where this was the case. ?
Copy linkTweet thisAlerts:
@svidgenMay 03.2011 — Is your adherence to the recommendation for the sake of semantics? (which I respect, even though my own preference differs for purely practical reasons) Or is there a practical reason?
Copy linkTweet thisAlerts:
@NogDogMay 03.2011 — The main practical reason I know of is that you can bookmark a get request (since it's just a URL query string), but you cannot bookmark a post request (and by definition you don't normally [I]want[/I] things that have side-effects to be bookmarked).

So if you fill out a form to search for and display all widgets based on some criteria and it uses the GET method, you can then bookmark the results page and access it at any time to get the latest info. On the other hand, if you fill out a form to purchase one of those widgets for $999, you probably don't want to be able to bookmark that page and then accidentally order another one (as an extreme example).

I'm sure you can come up with exceptions, and it's really only a guideline, but a good starting point, at least.
Copy linkTweet thisAlerts:
@svidgenMay 03.2011 — Gotcha. Thanks for the input.
Copy linkTweet thisAlerts:
@DariaMay 03.2011 — OK, thanks you guys. Re: "school of thought" officially - I am not quite sure, - it's just something that I've repeatedly came across in my younger years bedtime reading... And it stuck to my brain as a "given". So I may need to stay corrected on it. Also, I should've probably phrased it "GET is easier to abuse", exactly for the "Script kiddies will more likely play with your GET's than your POST's" reason. I guess GET would be more of the crime of opportunity kinda case. If someone really stakes to rob your place, it really wouldn't matter if you locked your front door or not (i.e. use GET or POST) - and if someone REALLY, REALLY wants to rob your place and they REALLY REALLY know what they are doing... you get (no pun intended) my point; so absolutely - you must sanitize your values regardless of method you use.
×

Success!

Help @inplaytoday spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...