Go Back   CodingForums.com > :: Client side development > JavaScript programming > Ajax and Design

Before you post, read our: Rules & Posting Guidelines

Reply
 
Thread Tools Rate Thread
Enjoy an ad free experience by logging in. Not a member yet? Register.
Old 01-26-2012, 04:25 PM   PM User | #1
coding_begins
Regular Coder

 
Join Date: Aug 2011
Posts: 134
Thanks: 20
Thanked 0 Times in 0 Posts
coding_begins is an unknown quantity at this point
ajax display form fields from database

I want to automatically genereate the form posts field and the joindate field from the database when the user enters the username and presses tab or some button called fetch in the form. Here is my code so far..i am new to ajax ..so need some help..

Code:
<form action="<?php echo $PHP_SELF;?>"  method="POST">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>

<input type="text" id="username"  name="username" /> 

<input type="text" id="posts" name="posts"  size="20"/></p>

<input type="text" id="joindate" name="joindate"  size="20"/></p>

<p><input type="submit" name="submitBtn" value="Submit" /></p>

</fieldset>
</form>
Code:
<script type="javascript/text>
var name = $('.username').val();
$.ajax({
method: "GET",
url: "http://url.com/test/autofill.php",
dataType: 'json',
data: {
username: username
}).success(function( responseObject ) {
// assuming you have an array of stuff like name, id, email, etc.
// now i populate another field from the ajax response
$('.posts').val( responseObject.posts );
});
</script>
PHP Code:
//connect to database
$name $_GET['username'];
$return mysql_query("SELECT * FROM user WHERE username = '$name' LIMIT 1");
$rows mysql_fetch_array($return);
$formattedData json_encode($rows);
print 
$formattedData
coding_begins is offline   Reply With Quote
Old 01-26-2012, 09:25 PM   PM User | #2
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
Your javascript code automatically starts as soon as it is loaded. There is no "pressing tab or some button called fetch" action here.

Even more: If the javascript code is in the head section of your code, it will not work, because the referred elements (like .username) have not yet been loaded

So put the javascript code into a function and only call it on (let's say) a button click
Code:
function myrequest() {
   var name = $('.username').val();
   $.ajax({
      method: "GET",
      url: "http://url.com/test/autofill.php",
      dataType: 'json',
      data: {
         username: username
      }).success(function( responseObject ) {
         // assuming you have an array of stuff like name, id, email, etc.
         // now i populate another field from the ajax response
         $('.posts').val( responseObject.posts );
   });
}

HTML:
<button onclick="myrequest()">fetch</button>
devnull69 is offline   Reply With Quote
Old 01-26-2012, 09:54 PM   PM User | #3
coding_begins
Regular Coder

 
Join Date: Aug 2011
Posts: 134
Thanks: 20
Thanked 0 Times in 0 Posts
coding_begins is an unknown quantity at this point
This is what i get in the url when i click on the fetch button..

http://url.com/test/%3Cbr%20/%3E%3Cb...b%3E%3Cbr%20/%

This is what i have in line 16:
<form action="<?php echo $PHP_SELF;?>" method="POST">
coding_begins is offline   Reply With Quote
Old 01-26-2012, 11:30 PM   PM User | #4
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
$PHP_SELF has been deprecated for quite a long time. Try $_SERVER['PHP_SELF'] instead
devnull69 is offline   Reply With Quote
Old 01-27-2012, 12:47 AM   PM User | #5
coding_begins
Regular Coder

 
Join Date: Aug 2011
Posts: 134
Thanks: 20
Thanked 0 Times in 0 Posts
coding_begins is an unknown quantity at this point
Thanks devnull..its not showing any error. But when i click the fetch button it does not populate the other fields..instead it refreshes the page..
coding_begins is offline   Reply With Quote
Old 01-27-2012, 06:54 AM   PM User | #6
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
Please come back with your code (as complete as possible)
devnull69 is offline   Reply With Quote
Old 01-27-2012, 04:49 PM   PM User | #7
coding_begins
Regular Coder

 
Join Date: Aug 2011
Posts: 134
Thanks: 20
Thanked 0 Times in 0 Posts
coding_begins is an unknown quantity at this point
This is my complete userdetails.php

Code:
<head>
<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js"></script>

</head>

<form action="<?php echo $_SERVER['PHP_SELF']; ?>"  method="POST">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>

<input type="text" id="username"  name="username" /> 
<button onclick="myrequest()">fetch</button>
<label for="posts">Posts: </label>
<input type="text" id="posts" name="posts"  size="20"/>
<label for="joindate">Joindate: </label>
<input type="text" id="joindate" name="joindate"  size="20"/>



<p><input type="submit" name="submitBtn" value="Submit" /></p>

</fieldset>
</form>
<script type="javascript/text>
function myrequest() {
var name = $('.username').val();
$.ajax({
  method: "GET",
  url: "http://url.com/test/autofill.php",
  dataType: 'json',
  data: {
    username: username
  }).success(function( responseObject ) {
    // assuming you have an array of stuff like name, id, email, etc.
    // now i populate another field from the ajax response
    $('.posts').val( responseObject.posts );
  });
}	 
} 
</script>
PHP Code:
this is my autofill.php
<?
//connect to db
$name $_GET['username'];
if((!empty(
$name))
{
   
$return mysql_query("SELECT posts FROM user WHERE username = '$name' LIMIT 1");
   
$rows mysql_fetch_array($return);
   print 
$formattedData;
 }
 else
 {
  echo 
"ERROR";
  }
?>
coding_begins is offline   Reply With Quote
Old 01-27-2012, 06:16 PM   PM User | #8
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
Wasn't your PHP supposed to output JSON format? There is no json_encode()
devnull69 is offline   Reply With Quote
Old 01-27-2012, 06:21 PM   PM User | #9
coding_begins
Regular Coder

 
Join Date: Aug 2011
Posts: 134
Thanks: 20
Thanked 0 Times in 0 Posts
coding_begins is an unknown quantity at this point
oops sorry..
I have updated my code:

PHP Code:
$name $_GET['username'];
 
$return mysql_query("SELECT posts FROM user WHERE username = '$name' LIMIT 1");
 
$rows mysql_fetch_array($return);
$formattedData json_encode($rows); 
   print 
$formattedData
it still doesnt work..could it be because the fetch button acts as a submit button?
coding_begins is offline   Reply With Quote
Old 01-27-2012, 09:31 PM   PM User | #10
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
In Germany we call that "not seeing the forest through all those trees"

The correct type for javascript is text/javascript and NOT javascript/text!
devnull69 is offline   Reply With Quote
Old 01-27-2012, 10:31 PM   PM User | #11
coding_begins
Regular Coder

 
Join Date: Aug 2011
Posts: 134
Thanks: 20
Thanked 0 Times in 0 Posts
coding_begins is an unknown quantity at this point
i really know how to mess up my code! thanks a lot.
but even after i have updated my code, when i click the ftech button the page simply refreshes.
coding_begins is offline   Reply With Quote
Old 01-27-2012, 11:26 PM   PM User | #12
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
Do you ever look for errors in your Javascript console?
Code:
missing } after property list
success is another option of the $.ajax() and NOT a chained method.
Code:
$.ajax({
  method: "GET",
  url: "http://url.com/test/autofill.php",
  dataType: 'json',
  data: {
    username: username
  },
  success:function( responseObject ) {
     ...
OR you have to close the data attribute AND the $.ajax() with a }
Code:
$.ajax({
  method: "GET",
  url: "http://url.com/test/autofill.php",
  dataType: 'json',
  data: {
    username: username
  }}).success(function( responseObject ) {
devnull69 is offline   Reply With Quote
Users who have thanked devnull69 for this post:
coding_begins (01-29-2012)
Old 01-29-2012, 10:40 PM   PM User | #13
coding_begins
Regular Coder

 
Join Date: Aug 2011
Posts: 134
Thanks: 20
Thanked 0 Times in 0 Posts
coding_begins is an unknown quantity at this point
Thanks...my code is working now..The only thing that is not workin is the $_GET['username'] variable in autofill.php. If i manually enter the username in the query, i get the expected results.

Code:
<html xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"><head>

<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/redmond/jquery-ui.css" type="text/css" rel="stylesheet">

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js" type="text/javascript"></script>

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1/jquery-ui.min.js" type="text/javascript"></script>

</head>

<body><form method="POST" action="/test/userdetails.php">
<fieldset>
<legend>Form</legend>
<label for="username">Username: </label>

<input type="text" name="username" id="username"> 
<button id="fetchFields">fetch</button>
<label for="posts">Posts: </label>
<input type="text" size="20" name="posts" id="posts">
<label for="joindate">Joindate: </label>
<input type="text" size="20" name="joindate" id="joindate">



<p><input type="submit" value="Submit" name="submitBtn"></p>

</fieldset>
</form>

<script type="text/javascript">
$(document).ready(function() {
    function myrequest(e) {
        var name = $('.username').val();
        $.ajax({
             method: "GET",
            url: "autofill.php",
			dataType: 'json',
			cache: false,
            data: {
                username: name
            },
            success: function( responseObject ) {
                alert('success');
                $('#posts').val( responseObject.posts );
                $('#joindate').val(responseObject.joindate);
                /*
                once you've gotten your ajax to work, then go through and replace these dummy vals with responseObject.whatever
                */
            },
            failure: function() {
                alert('fail');
            }
        });
    }
    
    $('#fetchFields').click(function(e) {
        e.preventDefault();
        myrequest();
    });
});

</script>
this is my autofill.php..
PHP Code:
$name $_GET['username'];

   
$return mysql_query("SELECT posts,joindate FROM user WHERE username = '$name' LIMIT 1");
   if(
mysql_num_rows($return) > 0)
   {
      
$rows mysql_fetch_assoc($return);
      
$formattedData json_encode($rows);
      echo    
$formattedData;  

    }
    else
    {
       echo 
json_encode("No results returned");
    }
?> 

Last edited by coding_begins; 01-29-2012 at 10:40 PM.. Reason: wrong filename
coding_begins is offline   Reply With Quote
Old 01-30-2012, 06:52 AM   PM User | #14
devnull69
Senior Coder

 
Join Date: Dec 2010
Posts: 2,245
Thanks: 10
Thanked 530 Times in 524 Posts
devnull69 will become famous soon enough
You messed up your jQuery/CSS selector.

Code:
var name = $('.username').val();
This means: Get the value of the first element with class "username" and assign it to "name". What you wanted to do is
Code:
var name = $('#username').val();
which will get the value of the element with id "username". Your input has an id attribute and no class attribute.
devnull69 is offline   Reply With Quote
Users who have thanked devnull69 for this post:
coding_begins (01-30-2012)
Old 01-30-2012, 03:33 PM   PM User | #15
coding_begins
Regular Coder

 
Join Date: Aug 2011
Posts: 134
Thanks: 20
Thanked 0 Times in 0 Posts
coding_begins is an unknown quantity at this point
Thanks again..its working fine now!
On another note, why am i not getting a failure, when i enter a incorrect username. It still returns me success with empty values.
coding_begins is offline   Reply With Quote
Reply

Bookmarks

Jump To Top of Thread


Thread Tools
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT +1. The time now is 10:38 PM.


Advertisement
Log in to turn off these ads.