hello friends may peace on you !
I have a little problem in my code.i want display the fetch value from db in a textfield after pressing load button.i am using ajax post method for it but cant figure it out what the problem.please help me !

Thanks,

Index.php

<html>
<head>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajax.js"></script>
</head>

<body>


   
    
    <input type="text" id="name" /> 
    <input type="submit" value="load" id="submit" />
    
     


</body>
</html>

test.php

<?php

if(isset($_POST))
{

mysql_connect("localhost","root","");
mysql_select_db("project");


$sql = mysql_query("SELECT `class_name` FROM `classes` WHERE `id` = '316'");

while($test = mysql_fetch_assoc($sql))
{

echo $show  = $test['class_name'];
	
}

}

?>

ajax.js

$(document).ready(function(){
			
$("#submit").click(function(){
		

		function show(post){
		$.post('[B]test.php[/B]', {post:post}, function(data){
			$("#name").html(data)					});
		
		}
		
				show($("#name").val());
						  });
			});

Recommended Answers

All 8 Replies

try this

index.html
    <html>
    <head>
     
    <script type="text/javascript" src="jquery-1.4.3.min.js"></script>
    <script type="text/javascript" src="ajax.js"></script>
    </head>
     
    <body>
     
     
     
    <form id="myform" action="test.php"> 
    <input type="text" id="name" />
    <input type="submit" value="load" id="submit" />
	<div name="result" id="result"></div>
    </form>
     
     
     
    </body>
    </html>
Ajax.js
$(document).ready(function(){
  /* attach a submit handler to the form */
  alert('hell called');
  $("#myform").submit(function(event) {
	alert('submit called');
    /* stop form from submitting normally */
    event.preventDefault(); 
        
    /* get some values from elements on the page: */
    var $form = $( this ),
        term = $form.find( 'input[name="id"]' ).val(),
        url = $form.attr( 'action' );

    /* Send the data using post and put the results in a div */
    $.post( url, { s: term },
      function( data ) {
		$("#result").html(data); 
          //var content = $( data ).find( '#content' );
          //$( "#result" ).empty().append( content );
      }
    );
  });
});		
==========
test.php
<?php
if(isset($_POST)) {
mysql_connect("localhost","root","");
mysql_select_db("test");
$id = $_POST['id'];
$html = '';
$sql = mysql_query("SELECT `class_name` FROM `classes` WHERE `id` = '$id'");
while($test = mysql_fetch_assoc($sql)) {

	$html .= $test['class_name'] . "<br />";	
}
echo $html; 
?>

oops, left a couple of alerts in there, and I may have changed the name of your db.

i have done it but got a query again that i am fetching multiple values from db and want to display into different field using ajax i did it for one field but i am not able to do it for multiple value here is my js file and the post file from i am fetch data to ajax.thanks


test.php

<?php

if(isset($_GET['name']))
{
mysql_connect("localhost","root","");
mysql_select_db("project");

$name =  $_GET['name'];

$sql = mysql_query("SELECT `id` FROM `classes` WHERE `class_name` = '$name'");

//$json=array();

while($test = mysql_fetch_assoc($sql))
{

echo $show  = $test['id'];
echo $show2  = $test['class_name'];
//$json[]= $test['id'];
//$json[] = $test['class_name'];

	
}
//echo json_encode($json[0]);
}

?>

ajax.js

$(document).ready(function(){
        	
		
		$("#form2").hide().addClass('form');	
		
		 $("#heads").keyup(function(){
									
		
					
			  show = $(this).val();
			  //var head = $("#head").val();
		     
			  var name = $("#heads").val();
			  
			    $.ajax({
		
	type: 'GET',	
	url: 'test.php',
	dataType: 'json',
	cache: false,
	data: { name: name},
	success: function show(data)
	
	{
	   // use json function but could set it properly
	
		$("#head").val(data[0]);   // field first
		$("#head2").val(data[1]); // field second
	 	 
	 
		
	}
		
		
		});
			
		      if(jQuery.trim(show)!="")
			   
			   {  
			   
			   $("#form2").show(function(){}).$("#head").addClass('form');
	//		   $("#form2").("#head").val().hide();
			   }
			    
				else
			   
			   { 
			   
			  
			   $("#form2").hide(1000);
			   }
			   
			  
			   
			   }); 
		        });

in test.php instead of

echo $show = $test['id'];
echo $show2 = $test['class_name'];

you'll want to do something like this:

$show = $test['id'].",".$test['class_name'];

and when your while statement is done:

echo $show;

back in your ajax.js you will want to do something like this.
when you get the $result of $show returned to your javascript page...

var result = data; (data would be what is in your $show variable returned from the php query page.)
var mySplitResult = result.split(",");
var1 = mySplitResult[0];
var2 = mySplitResult[1];
where var1 should now be $test['id']
and var2 should now be $test['class_name']

idid the changes but nothing happens

$(document).ready(function(){
        	
		
		$("#form2").hide().addClass('form');	
		
		 $("#heads").keyup(function(){
									
		
					
			  show = $(this).val();
			  //var head = $("#head").val();
		     
			  var name = $("#heads").val();
			  
			    $.ajax({
		
	type: 'GET',	
	url: 'test.php',
	dataType: 'json',
	data: { name: name},
	success: function show(data)
	
	{
	
		    //var result = data;
            //var mySplitResult = result.split(",");
          //  var1 = mySplitResult[0];
            //var2 = mySplitResult[1];
			//alert(data);
            $("#head").val(data);

		
	}
		
		
		});
			
		      if(jQuery.trim(show)!="")
			   
			   {  
			   
			   $("#form2").show(function(){}).$("#head").addClass('form');
	//		   $("#form2").("#head").val().hide();
			   }
			    
				else
			   
			   { 
			   
			  
			   $("#form2").hide(1000);
			   }
			   
			  
			   
			   }); 
		        });

test.php

<?php

if(isset($_GET['name']))
{
mysql_connect("localhost","root","");
mysql_select_db("project");

$name =  $_GET['name'];

$sql = mysql_query("SELECT  `id`,`class_name` FROM `classes` WHERE `id` = '$name'");

//$json=array();

while($test = mysql_fetch_assoc($sql))
{

//echo $show  = $test['id'];
$show = $test['id'].",".$test['class_name'];


	
}
echo $show;
}

?>

thanks friend i figure it out the problem was in dataType: json while i removed it the code worked.may i asked you that why it doesnt work with dataType:json. i think i didnt declare json nor in ajax file nor i used in php thats why it was casing error.am i write let me know.

2. second question is that if i would use json how could i do that with that.

ok... json.
the easiest thing I found to read it on the javascript side is a sample here:
http://code.google.com/p/json-sans-eval/
note the jsonParse call is incorrect if you are using json_parse.js.

I downloaded the zip from this site:
https://github.com/douglascrockford/JSON-js
in index.php I changed this:
(I renamed the zip folder to json...)

<script type="text/javascript" src="jquery-1.4.3.min.js"></script>
	<script type="text/javascript" src="json/json2.js"></script>
	<script type="text/javascript" src="json/json_parse.js"></script>	
    <script type="text/javascript" src="ajax.js"></script>

Note, I have only worked with json recently and did not know these existed until today.
in ajax.js I changed this, mind you I was only testing, I don't know how you want to use your returned data, so I set up 2 variables, f402, and f101, (because I named the expected stuff coming back 402 and 101 respectively) anyway:

alert('create object');
		var myJsonObj = json_parse(data);   /***  this line was jsonParse in the sample page, needs to be json_parse like your json_parse.js file. ***/
		alert('return from jsonParse');
		// lets set some variable to hold our returned data.
		var f402 = '';
		var f101 = '';		
		for (var k in myJsonObj) {
		// alerts x=Hello, World!  and  y=1,2,3
			//alert(k + '=' + myJsonObj[k]);
                        // in your code k will = 'id'; and 'class_name'.
			if (k == '402') {
				f402 = myJsonObj[k];
				alert('402 = ' + f402);
			}				
			if (k == '101') {
				f101 = myJsonObj[k];
				alert('101 = ' + f101);
			}							
		}

in test.php
you need to set up an array. I gave it a key/value pair, the keys in this case were '402' and '101' (you would want to set this to 'id', and 'class_name')
this is not ideal, just an example you could do something like this:

$show = array();
while($test = mysql_fetch_assoc($sql)) {
	$show['id'] = $test['id'];
	$show['class_name'] = $test['class_name'];
}	
// you must encode it, luckily php has a special function:
$html = json_encode($show);
// finally echo back your array.  
(mine looked like this:   {"402":"American History","101":"Calculus 101"} 
(yours should look like this:  {"id":"316","class_name":"Calculus 101"}   or close to it.
echo $html;

in ajax.js, code above, that code should go in your
function(data) call.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.