Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    New to the CF scene
    Join Date
    May 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts

    Using Jquery Ajax to pull questions and answers from php

    I am attempting to pull the questions and answers from the php database, but the variables (like answ1) keep coming up undefined.

    Code:
    <!DOCTYPE html>
    <title>Thomas</title>
    <body>
    
    	<div id="nameTop">
    	<h1>I am going to make a quiz using JQuery and AJAX</h1>
    		<div>
    			<span id="questionTxt"><h2>Insert question here.</h2></span>
    			<p id="hintTrigger">Need help?  Click me.<span id="hintTxt"></span></p>
    			<div id="answers">
    				<form>
    					<input type="radio" name="ansRadio"><span id="ans1">Ans1</span>
    					<input type="radio" name="ansRadio"><span id="ans2">Ans2</span><br />
    					<input type="radio" name="ansRadio"><span id="ans3">Ans3</span>
    					<input type="radio" name="ansRadio"><span id="ans4">Ans4</span>
    				</form>
    			</div>
    		</div>
    		<div>
    			<p>Submit.  Next page.  Something.</p>
    		</div>
    	</div>
    
    <!-- Loading my js scripts-->
    	<script src="jquery-2.0.0.min.js"></script>
    	<script src="tryme.js"></script>
    </body>
    </html>
    Code:
    $(document).ready(function(){
    	
    	function getQuestions(){
    		//In the php database, they are called answer1, answer2...
    		//On this script, they are called answ1, answ2...
    		//On the html, they are called ans1, ans2...
    		
    		//var quest = $('#questionTxt').val();
    
    	
    		//var questNum = $('pid').val();
    		var questNum = 1;
    		
    		$.ajax({
    			type:	"POST",
    			url:	"questionDB.php",
    			data:	{pid:questNum},
    			}).done(function(result){
    			
    					/*var answ1 = $('#answer1').val();
    		var answ2 = $('#answer2').val();
    		var answ3 = $('#answer3').val();
    		var answ4 = $('#answer4').val();
    		var hint = $('#hint').val(); This is where I try to assign the php variables to ajax*/
    				$("#questionTxt").text(quest);
    				$("#ans1").text(answ1);
    				$("#ans2").text(answ2);
    				$("#ans3").text(answ3);
    				$("#ans4").text(answ4);
    				$("#hintTxt").text(hint);
    			});
    	}
    
    	//var hint = "Whaaaaat";
    	
    	//function Question(questionTxt, questionAns);
    	getQuestions();
    	$("#hintTxt").fadeOut();
    	$("#hintTrigger").click(function(){
    		$(this).fadeOut(); //It seems to be skipping this animation.
    		$("#hintTxt").text(hint);
    		$("#hintTxt").fadeIn();
    		$(this).remove();
    	})
    
    				
    	console.log(questionTxt); // I get <div id="questionTxt"> in the console.
    	console.log(answ1);
    });
    Code:
    <?php
    	/* I don't think I need this code
    	$_POST['questionTxt'];
    	$_POST['answer1'];
    	$_POST['answer2'];
    	$_POST['answer3'];
    	$_POST['answer4'];
    	$_POST['hint'];
    	*/
    	// Check if post is empty
        if (!empty($_POST))
    	{
    	    $questNum = $_POST['pid'];
    	}
    	// check if pid in post param
        if (empty($questNum))
    	{
    		die('No pid provided');
    	}
    	
    	//echo '$questNum = ' . $questNum;
    	
        //connects to our database
        $con = mysql_connect("localhost","root","");
    	if (!$con)
    	{
    		die('error connecting to database server' . mysql_error());
    	}
    	
    	// Check if there's a database named databasehelloz
    	if (!mysql_select_db("databasehelloz", $con))
    	{
    		die('error connection to database' . mysql_error());
    	}
    	
    	// TODO 
    	$result = mysql_query("SELECT * FROM questionTable WHERE pid = ".$questNum."");
    	// TODO
       	$row = mysql_fetch_array($result);
    		echo $row['questionTxt'] . $row['answer1'] . $row['answer2'] . $row['answer3'] . $row['answer4'] . $row['hint'];
    	
    ?>

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,398
    Thanks
    12
    Thanked 570 Times in 563 Posts
    Your PHP output is raw text (exactly the way you output it ... no separating characters, no key/value pairs etc).

    Example: Let's say
    $row['questionText'] = "Question"
    $row['answer1'] = "Answer1"
    $row['answer2'] = "Answer2"
    $row['answer3'] = "Answer3"
    $row['answer4'] = "Answer4"
    $row['hint'] = "Hint"

    Then the output of your PHP would be
    QuestionAnswer1Answer2Answer3Answer4Hint

    How shoud Javascript know how to separate those values??

    Possible solutions:
    1) Output a separator like | (the pipe symbol)
    Code:
    		echo $row['questionTxt'] . '|' . $row['answer1'] . '|' . $row['answer2'] . '|' . $row['answer3'] . '|' . $row['answer4'] . '|' . $row['hint'];
    Then you can use Javascript .split() method to split the string at this character
    Code:
    var theArray = result.split('|');
    // theArray[0] will have the questionTxt, theArray[1] will have answer1 etc.
    2) Use some structured output format like JSON
    Code:
    echo '{"questionTxt" : "' . $row['questionTxt'] . '", "answer1" : "' . $row['answer1'] . '"}';
    Then you can turn this string into a native Javascript object and use the .dot notation (property chaining) for this
    Code:
    var theJSONObject = JSON.parse(result);
    // theJSONObject.questionTxt will have the questionTxt, theJSONObject.answer1 will have answer1 etc

  • #3
    New to the CF scene
    Join Date
    May 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts
    Thanks for that input. I've decided to go with json. I needed to learn that eventually, and now is a good time.

    I've added
    Code:
    DataType: 'json',
    to the ajax() and got
    Code:
    {"questionTxt" : "What is 2 + 2?", "answ1" : "1", "answ2" : "2", "answ3" : "3", "answ4" : "4", "hint" : "What is 2?"}
    echoing fine, but where would I put
    Code:
    var theJSONObject = JSON.parse(result);
    ?

    I put it right after .done's function, but this error comes up.
    SyntaxError: JSON.parse: unexpected character

    I tried JSONLint to validate the echoed JSON I got from the php and it's green.

  • #4
    New to the CF scene
    Join Date
    May 2013
    Posts
    8
    Thanks
    2
    Thanked 0 Times in 0 Posts
    I can't seem to stop getting stuck with my code, even after so much research.

    Maybe the problem lies in the echo after all. It's quote overkill, but I thought since it's validated and Firebug says nothing about it, it should work.
    Code:
    		echo '{"questionTxt" : "' . $row['questionTxt'] . 
    		'"'.', "answ1" : "' . $row['answer1'] .
    		'"'.', "answ2" : "' . $row['answer2'] .
    		'"'.', "answ3" : "' . $row['answer3'] .
    		'"'.', "answ4" : "' . $row['answer4'] .
    		'"'.', "hint" : "'. $row['hint'] .
    		'"}';


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •