AJAX not passing variable to PHP

Hello,
below i have the 2 scripts that im having problems with.

  1. the javascript seems to be in a loop and not sure why.
  2. sec. the ajax isnt displaying resluts sent from testData.php

testData.php itself works it pulls a set of data from the db but cant pass the the results over to display from the calling script.
any help you can give would be greatly appreciated.
thanks


<div id="questiondev-wrapper">	<div id="questiondev" >	</div> </div>	
		
	<!-- ******************************************************************************* -->		
		<div id="questionButton">
			<form method="POST" name="form_questions" action="">
				<label class="error" for="saveqa" id="question_error"><p>This field is required.</p></label>
				<hr>
				<TEXTAREA NAME="saveqa" ROWS="3" COLS="50" MAXLENGTH="256" id="saveqa"></TEXTAREA>
				<BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>			
			</form>
		</div>	
		<!--*** reload the question and answer div tag # id/ . class *******-->
			<script src="http://code.jquery.com/jquery-latest.js"></script>
	 	<script>		
			$(document).ready(function() {
			$('#btn_save').on('click', function() {
			$.ajax({
				type: "POST",
				cache: false,
				url: "testData.php",
				data:$("form").serialize(),
				dataType: "json",
				success:function(info)
				{	$('#questiondev').html(info[0]);
					console.log(" reponse :"+ info);
				}
			});
			});
			$('#btn_save').trigger("click");
         });
 		</script>

testData.php


<?php
require_once('../../include/connectionv2.php');
$projectId = '096675edc895d5d03667e15c47d94e6651559e5e8ec36';
$dbcon1 = Connection::getConnection();
	try {	$stmt = $dbcon1 ->query("SELECT
						  tbl_questions.projectid,
						  tbl_questions.question,
						  tbl_questions.date
					 FROM tbl_questions
		  			WHERE tbl_questions.projectid = '$projectId' ");				
				$questionArray = $stmt->fetchAll(PDO::FETCH_ASSOC);			
			}
			catch(PDOException $e)
			{    echo $e->getMessage(); }	
echo ' <br />';
echo $questionArray;
?>


Hi,

This is because you are triggering a click on the submit button, the form is submitting to itself, the page is reloading, you are triggering a click on the submit button, the form is submitting to itself, the page is reloading and so on …
What you need to do is to prevent the form’s default submit action before you do anything else:

$('#btn_save').on('click', function(e) { 
  e.preventDefault()
  ...
}

In your PHP script you are doing this:

echo $questionArray;

However in your JavaScript you are specifying your dataType as JSON :

dataType: "json",

Either specify your dataType as “html” or use json_encode() to return JSON to your page.

Hope this helps.

Hello,
Im still struggling with the script…I changed parts of the code with no success and lost at fixing this problem. any ideas??


<!DOCTYPE html>
	<head>
		<title> Table: HTML testing</title>
		<meta http-equiv="content-type" content="text/html; charset=utf-8" />	
	</head>

<html>
	<body class="body">
		<br /><br />
		<!--  START: Q& A - startes displaying from here -->
		<div id="questiondev-wrapper">	<div id="questiondev" >	</div> </div>	
		
	<!-- ******************************************************************************* -->		
		<div id="questionButton">
			<form method="POST" name="form_questions" action="">
				<label class="error" for="saveqa" id="question_error"><p>This field is required.</p></label>
				<hr>
				<TEXTAREA NAME="saveqa" ROWS="3" COLS="50" MAXLENGTH="256" id="saveqa"></TEXTAREA>
				<BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>			  
			</form>
		</div>	
		<!--*** reload the question and answer div tag # id/ . class *******-->
			<script src="http://code.jquery.com/jquery-latest.js"></script>
	 	<script>		   
			$(document).ready(function() { 
			$('#btn_save').on('click', function(e) { 
			e.preventDefault();
			$.ajax({
				type: "POST",
				cache: false, 
				url: "testData.php",
				data:$("form").serialize(),
				dataType: "json",
				success:function(info)
				{	$('#questiondev').html(info[0]);
					console.log(" reponse :"+ info);
				}
			});
			}); 
			$('#btn_save').trigger("click");
         });                  
 		</script> 
<!-- ******************************************************************************* -->							
		<br /><br />
	</body>
</html>

testData.php


<?php
header('Content-type: application/json');
require_once('../../include/connectionv2.php');
$projectId = '096675edc895d5d03667e15c47d94e6651559e5e8ec36';
$dbcon1 = Connection::getConnection();
	try {	$stmt = $dbcon1 ->query("SELECT 
						  tbl_questions.projectid, 
						  tbl_questions.question, 
						  tbl_questions.date
					 FROM tbl_questions
		  			WHERE tbl_questions.projectid = '$projectId' ");				
				$questionArray = $stmt->fetchAll(PDO::FETCH_ASSOC);			
			} 
			catch(PDOException $e) 
			{    echo $e->getMessage(); }	
//var_dump($questionArray); // tested ok
echo json_encode($questionArray);
?>

Hi there,

Did preventing the form’s default action at least help with the infinite loop?

It shouldn’t be hard to sort this out, but one thing I cannot reproduce at my end are calls to your database.
Could you therefore, please post the contents of $question_array.

If this is a very long array, please just post a small sample of some data it is likely to contain.

Once I have this, I will be able to use your HTML and make you a working example.

Thanks for your help.

the results from var_dump($questionArray);


array(11) {
  [0]=>
  array(3) {
    ["projectid"]=>
    string(45) "096675edc895d5d03667e15c47d94e6651559e5e8ec36"
    ["question"]=>
    string(27) "1-0How big is your room test"
    ["date"]=>
    string(19) "2013-04-26 11:14:00"
  }
  [1]=>
  array(3) {
    ["projectid"]=>
    string(45) "096675edc895d5d03667e15c47d94e6651559e5e8ec36"
    ["question"]=>
    string(76) "2-1 more test questions and answers ?"
    ["date"]=>
    string(19) "2013-04-29 11:14:22"
  }
  [2]=>
  array(3) {
    ["projectid"]=>
    string(45) "096675edc895d5d03667e15c47d94e6651559e5e8ec36"
    ["question"]=>
    string(102) "3-2 more test questions and answerthere "
    ["date"]=>
    string(19) "2013-04-27 11:14:41"
  }
  [3]=>

Hi there,

So I changed your HTML to this:

<!DOCTYPE HTML>
  <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Simple AJAX example</title>
  </head>

  <body>
    <div id="questiondev-wrapper">
      <div id="questiondev"></div>
    </div>

    <!-- ******************************************************************************* -->
    <div id="questionButton">
      <form method="POST" name="form_questions" action="">
        <label class="error" for="saveqa" id="question_error"><p>This field is required.</p></label>
        <hr>
        <TEXTAREA NAME="saveqa" ROWS="3" COLS="50" MAXLENGTH="256" id="saveqa"></TEXTAREA>
        <BUTTON class="btn_save" id ="btn_save" NAME="btn_save">Ask</BUTTON>
      </form>
    </div>
    <!--*** reload the question and answer div tag # id/ . class *******-->

    <script src="http://code.jquery.com/jquery-latest.js"></script>
    <script>
      $(document).ready(function() {
        $('#btn_save').on('click', function(e) {
          $.ajax({
            type: "POST",
            cache: false,
            url: "testData.php",
            dataType: "json",
            success:function(info){
              console.log(info);
              console.log(info[0]);
              console.log(info[0].question);
            }
          });
          e.preventDefault();
        });
        //$('#btn_save').trigger("click");
      });
    </script>
  </body>
</html>

And I changed the PHP to this:

<?php
  $questionArray = array(
    array(
      "projectid" => "096675edc895d5d03667e15c47d94e6651559e5e8ec36",
      "question" => "1-0How big is your room test",
      "date" => "2013-04-26 11:14:00"
    ),
    array(
      "projectid" => "096675edc895d5d03667e15c47d94e6651559e5e8ec36",
      "question" => "2-1 more test questions and answers ?",
      "date" => "2013-04-29 11:14:22"
    ),
    array(
      "projectid" => "096675edc895d5d03667e15c47d94e6651559e5e8ec36",
      "question" => "3-2 more test questions and answerthere ",
      "date" => "2013-04-27 11:14:41"
    )
  );

  echo json_encode($questionArray);
?>

Now when you press the “Ask” button, the JavaScript fires off an AJAX request and logs the response to the console.

info => [Object, Object, Object]
info[0] => Object {projectid: "096675edc895d5d03667e15c47d94e6651559e5e8ec36", question: "1-0How big is your room test", date: "2013-04-26 11:14:00"}
infor[0].question => 1-0How big is your room test 

I hope that helps you.

how does the script know which div tag to display the information?

Hi,

First off, could you do me a favour and not quote my entire answer back at me.
It makes the thread very long and difficult to read.

At the moment we’re not displaying it anywhere, we’re just logging it to the console.
Just in case, here’s a short tutorial on what the console is and how to read what is logged there.

Before you start manipulating the result, it would be better if you could:

a) Make sure that your PHP script is returning something sensible
b) Understand what it is returning.

Then, to insert part or all of the response into a <div> element, just do (for example):

$("#myDiv").html(info[0].question);

inside the success callback.