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.
Page 1 of 2 12 LastLast
Results 1 to 15 of 16
  1. #1
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts

    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

  • #2
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    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>

  • #3
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts
    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">

  • #4
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    $PHP_SELF has been deprecated for quite a long time. Try $_SERVER['PHP_SELF'] instead

  • #5
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts
    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..

  • #6
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    Please come back with your code (as complete as possible)

  • #7
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts
    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";
      }
    ?>

  • #8
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    Wasn't your PHP supposed to output JSON format? There is no json_encode()

  • #9
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts
    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?

  • #10
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    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!

  • #11
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts
    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.

  • #12
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    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 ) {

  • Users who have thanked devnull69 for this post:

    coding_begins (01-29-2012)

  • #13
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts
    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

  • #14
    Senior Coder
    Join Date
    Dec 2010
    Posts
    2,396
    Thanks
    12
    Thanked 569 Times in 562 Posts
    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.

  • Users who have thanked devnull69 for this post:

    coding_begins (01-30-2012)

  • #15
    Regular Coder
    Join Date
    Aug 2011
    Posts
    134
    Thanks
    20
    Thanked 0 Times in 0 Posts
    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.


  •  
    Page 1 of 2 12 LastLast

    Posting Permissions

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