elexion Posted April 16, 2012 Report Share Posted April 16, 2012 hello everyone, I'm trying to make a guessing system. Basically the user is on page1, A simple HTML page that displays an input window for text and a button "guess". The idea is that the user fills some text in hits the guess button and the page fetches a PHP script that looks into a database to find the name it's going to reveal. What would I use for this? I've been using Jquery to make it look appealing to the eye. I thought about jquery - AJAX but I'm not sure how to or what function to use for it. Could anyone give me some insight on the mater and push me in the right direction to what I need to do/use. thanks in advance. Link to comment Share on other sites More sharing options...
thescientist Posted April 16, 2012 Report Share Posted April 16, 2012 what part are you having trouble with? You seem to have the basic pseudo code down. * Basically the user is on page1, A simple HTML page that displays an input window for text and a button "guess".* The idea is that the user fills some text in hits the guess button* and the page fetches a PHP script that looks into a database to find the name it's going to reveal. you are aware that AJAX is the technique you want to use. Do you know how to use AJAX (i.e XMLHttpRequest object)? Have you looked into jQuery.ajax? http://www.w3schools.com/ajax/default.asphttp://api.jquery.com/jQuery.ajax/ So far I'm not seeing a specific problem as it relates to anything you've tried. All I would say it continue in the step by step list for each thing you want to do, as it relates to getting the information out of the database back to the user, and how you want to validate it. Link to comment Share on other sites More sharing options...
elexion Posted April 16, 2012 Author Report Share Posted April 16, 2012 alright I bumped into a (probably very simple) problemI'm using this piece of code for the HTML page <script type="text/javascript"> function submit_guess(string){ xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) {document.getElementById(".window").innerHTML=xmlhttp.responseText;}} xmlhttp.open("POST", "guess.php?search="+string,true);//xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send();}</script> <div class='window'>guess what it is?<br /><form><input type='text' name='guess'/><br /><button onclick="submit_guess(guess)">guess</button></form><br /></div> note that I cut this code out of the whole thing I'm sure there are no missing tags in the code above.Below is the PHP page I'm requesting <?phpinclude("connect.php"); $get_guess = $_POST["guess"];$query = "SELECT * FROM guess WHERE product_name = '".$get_guess."'";$result = mysql_query($query);while($row = mysql_fetch_array($result)) {echo "hello moon";echo $row['product_name']; }?> basically this code does nothing except add to the URL extension. What did I do wrong? the URL does change when I hit the button and it does fill with text "?guess=" Link to comment Share on other sites More sharing options...
thescientist Posted April 16, 2012 Report Share Posted April 16, 2012 you should be debugging earlier than that. Figure out why "guess" is not being passed correctly to your submit guess function. i.e. output string when the submit_guess function runs onclick="submit_guess(guess)" //guess is undefined, what did you expect to be passing using guess? what you should be doing in the submit guess function is getting a reference to the element that will contain the text (string) you want to pass to the script Link to comment Share on other sites More sharing options...
elexion Posted April 17, 2012 Author Report Share Posted April 17, 2012 (edited) you should be debugging earlier than that. Figure out why "guess" is not being passed correctly to your submit guess function. i.e. output string when the submit_guess function runs onclick="submit_guess(guess)" //guess is undefined, what did you expect to be passing using guess? what you should be doing in the submit guess function is getting a reference to the element that will contain the text (string) you want to pass to the script How do I make that reference? I based this code on the AJAX example with the select drop down menu, I did read the entirety of the tutorials. The idea is that <button onclick="submit_guess(guess)">guess</button> gets the value of the above text type. The strange thing is that the URL does change when I click the button to example.php?guess...whatever I fill in. Also when I click the button now it resets all my Jquery elements is this because the script is broken or is it the jquery itself? I've added this line of code now hopefully it's somewhat better, but it still doesn't quite work if (xmlhttp.readyState==4 && xmlhttp.status==200) {document.getElementById("guess");document.getElementById("window").innerHTML=xmlhttp.responseText;}} Edited April 17, 2012 by elexion Link to comment Share on other sites More sharing options...
elexion Posted April 17, 2012 Author Report Share Posted April 17, 2012 (edited) I've been troubleshooting this code some more and have come up with a new version of it function submit_guess(){ var xmlhttp; var str = document.getElementById("guess").value; if (str=="") { document.getElementById("place_it").innerHTML="the string is empty"; return; } xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200){var x=document.getElementById("guess").value;document.getElementById("place_it").innerHTML=xmlhttp.responseText;}else{alert("this is an error");}}xmlhttp.open("POST", "guess.php?search="+str,true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send();} the ID "guess" is the input field simply <input type='text'...etcthe ID place_it is a span elementalso the Alert triggers twice for some reason....could this mean it fails in 2 stages of the readystate? Edited April 17, 2012 by elexion Link to comment Share on other sites More sharing options...
es131245 Posted April 17, 2012 Report Share Posted April 17, 2012 >> xmlhttp.open("POST", "guess.php?search="+str,true);>> $get_guess = $_POST["guess"];are you using GET or POST form?looks like POST but 'guess.php?search="+str' is a get method Link to comment Share on other sites More sharing options...
elexion Posted April 17, 2012 Author Report Share Posted April 17, 2012 >> xmlhttp.open("POST", "guess.php?search="+str,true); >> $get_guess = $_POST["guess"]; are you using GET or POST form? looks like POST but 'guess.php?search="+str' is a get method Thank you, I changed the code a little to fit the POST xmlhttp.open("POST", "guess.php",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("search="+str); But it's not what's bugging me(it would've but we caught it beforehand )I've tried this line of code if(xmlhttp.readyState==1 && xmlhttp.status==200) {alert("this works"); } else {alert("cannot initilaze request"); } and it tells me it can't initialize the request so is this accurate and if so what did I do wrong? Link to comment Share on other sites More sharing options...
thescientist Posted April 17, 2012 Report Share Posted April 17, 2012 can you show the complete code as you have it now? properly formatted and indented? Link to comment Share on other sites More sharing options...
elexion Posted April 17, 2012 Author Report Share Posted April 17, 2012 alright; <!DOCTYPE html public "-//W3C//DTD XHTML 1.0 strict //EN""http://www.w3.org/TR/xhtmll/DTD/xhtmll-strict.dtd"><html><head><script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script><script type="text/javascript" src="jquery.js"></script><script type="text/javascript"> function submit_guess(){ var xmlhttp; var str = document.getElementById("guess").value; if (str=="") { document.getElementById("place_it").innerHTML="the string is empty"; return; } xmlhttp=new XMLHttpRequest(); xmlhttp.onreadystatechange=function() { if(xmlhttp.readyState==1 && xmlhttp.status==200) {alert("this works"); } else {alert("cannot initilaze request"); } if (xmlhttp.readyState==4 && xmlhttp.status==200){var x=document.getElementById("guess").value;document.getElementById("place_it").innerHTML=xmlhttp.responseText; }else{alert("this is an error");}}xmlhttp.open("POST", "guess.php",true);xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");xmlhttp.send("search="+str);} $(document).ready(function(){ $('#present').hide(); $(".flip").click(function(){ $(".panel").slideToggle("slow"); }); $(".show_present").click(function(){$("#present").fadeIn("slow"); }); });</script></head><body><div class="panel"> </div><p class="flip">pull the ribbons</p><div class='window'>guess what it is?<br /><form><input type='text' id='guess' placeholder='guess what it is?'/><br /><button onclick='submit_guess()'>guess</button><span id='place_it'></span></form><br />Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus arcu turpis, gravida non lacinia sed, facilisis non lorem. Quisque non purus in ligula tincidunt tincidunt. Nunc in mattis purus. Sed mauris dolor, ullamcorper sit amet commodo tristique, vehicula ut libero. Etiam et est massa. Phasellus et elit sit amet urna imperdiet sodales. Mauris mollis orci eget leo mattis pellentesque. Aliquam velit massa, lacinia ac fringilla et, gravida vitae sem. Sed gravida nibh ac magna hendrerit consequat eget sit amet ipsum. Vestibulum vitae dolor a libero congue ornare vitae a nisl. Nam ac est ante. Morbi sed ipsum purus, ut vestibulum libero. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nam cursus nisi ut massa sodales bibendum. Vivamus leo enim, consectetur sed lacinia a, tristique rutrum libero.</p><button class='show_present'>reveal</button><img height=200 width=200 src='image.jpg' alt='wrapit' id='present'/><br /> </div></body></html> Link to comment Share on other sites More sharing options...
thescientist Posted April 17, 2012 Report Share Posted April 17, 2012 (edited) hmm. maybe it's cause you are checking for a status of 200 before the readyState is at 4, where status would actually be determined. Try something like this: xmlhttp.onreadystatechange=function(){ console.log('readyState is => ' + xmlhttp.readyState); if (xmlhttp.readyState==4 && xmlhttp.status==200){ console.log('SUCCESS'); console.log(xmlhttp); document.getElementById("place_it").innerHTML=xmlhttp.responseText; }else{ console.log("ERROR"); console.log(xmlhttp); } } Edited April 17, 2012 by thescientist Link to comment Share on other sites More sharing options...
justsomeguy Posted April 17, 2012 Report Share Posted April 17, 2012 The readystate function gets called several times, every time the ready state changes (hence the name). You can look up a reference of the various readyState codes to see what each value means. It will get called when the request is being initialized, again when it gets sent, if there's an error, on success, etc, every time the state changes. Link to comment Share on other sites More sharing options...
elexion Posted April 18, 2012 Author Report Share Posted April 18, 2012 hmm. maybe it's cause you are checking for a status of 200 before the readyState is at 4, where status would actually be determined. Try something like this: xmlhttp.onreadystatechange=function(){ console.log('readyState is => ' + xmlhttp.readyState); if (xmlhttp.readyState==4 && xmlhttp.status==200){ console.log('SUCCESS'); console.log(xmlhttp); document.getElementById("place_it").innerHTML=xmlhttp.responseText; }else{ console.log("ERROR"); console.log(xmlhttp); } } I've run this code and it tells me there's a problem on line 7<script type="text/javascript" src="jquery.js"></script> further when I call the function it tells me this readyState is => 1ERRORXMLhttprequestreadyState is => 4ERRORXMLhttprequest Link to comment Share on other sites More sharing options...
thescientist Posted April 18, 2012 Report Share Posted April 18, 2012 what's line 7? that would be of help to those who don't have the code in front of them. also, my if/else was a little too greedy. this would be more appropriate. xmlhttp.onreadystatechange=function(){ console.log('readyState is => ' + xmlhttp.readyState); if (xmlhttp.readyState === 4 && xmlhttp.status === 200){ console.log('SUCCESS'); console.log(xmlhttp); document.getElementById("place_it").innerHTML=xmlhttp.responseText; }else if(xmlhttp.readyState === 4 && xmlhttp.status !== 200{ console.log("ERROR"); console.log(xmlhttp); } } So clearly though from the above, you are never reaching success. This is when it is time to start debugging in your browsers console. I personally use Chrome, and included with it are Developer Tools, and specifically a network tab. (I'm sure you can find something similar for your browser of choice). With that tab open, load your page and execute the AJAX function. You should be able to see the request on the left run, and on the right you should have tabs for review the request/response headers. Check the request headers to make sure the data being sent is what you expect it to be. Check the response headers to see what is coming back. PHP errors would show up there, so you can debug your scripts that way. Typically, I like to test my PHP scripts first on their own, using GET (if applicable) query string on the PHP script itself first, and verify that everything is working using a simple proof of concept test case. Once that is outputting the correct data, then I go into my JS code and make the requests that way replicating the test requests I was just making. It usually helps iron out a lot of bugs beforehand. Link to comment Share on other sites More sharing options...
elexion Posted April 19, 2012 Author Report Share Posted April 19, 2012 Yes; sorry for the confusing bit; Line 7 was a pointless reference to a file that didn't exist so I removed that. When I run my code with the google chrome network tab in front of me it never seems to reach the php file...also it identifies the method as get rather than post. Link to comment Share on other sites More sharing options...
thescientist Posted April 19, 2012 Report Share Posted April 19, 2012 time to debug. log every step of the process in your script. make sure the path to the file is correct. make sure you are looking at the right request in the network tab. Verify everything about the request before it gets made. method, action, params, etc. I'm sure you are overlooking something simple. the best way for us to help would if you could put the code up somewhere live for us to see and test. Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now