2

I am creating one admin page where I have multiple textboxes.when I enter the userid in one textbox I want to display user name in next textbox when admin moves to next text box.for this I can use ajax or javascript? which one will be better?how can I do it through javascript.

6
  • 2
    AJAX via JavaScript, obviously... Commented Jun 7, 2010 at 6:22
  • by the way, direct access via JS to your database is very dangerous unless filtering is done. this means that users can modify your entire database. Commented Jun 7, 2010 at 6:25
  • @thephpdeveloper: correct me if I'm wrong, but I don't think you can actually directly access the DB via JS, no? Commented Jun 7, 2010 at 6:28
  • no you can't. but as giving it direct access. Commented Jun 7, 2010 at 6:38
  • @thephpdeveloper: ah OK! I thought I'd missed some hidden JS capability :) Of course to avoid disaster the server side backend should make all the necessary permission controls and input sanitization Commented Jun 7, 2010 at 6:52

8 Answers 8

3
<script>
    function showUser(str) {
        if (str=="") {
          document.getElementById("spName").innerHTML="";
          return;
        } 

        if (window.XMLHttpRequest) {
          // code for IE7+, Firefox, Chrome, Opera, Safari
          xmlhttp=new XMLHttpRequest();
        } else {
          // code for IE6, IE5
          xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
        }

        xmlhttp.onreadystatechange=function() {
          if (xmlhttp.readyState==4 && xmlhttp.status==200) {
            document.getElementById("spName").innerHTML=xmlhttp.responseText;
          }
        }

        xmlhttp.open("GET","getUserName.php?q="+str,true);
        xmlhttp.send();
    }
</script>

getUsreName.php

<?php

$q=$_GET["q"];

$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password=""; // Mysql password 
$db_name="pnpdb"; // Database name 

// Connect to server and select databse.
$link = mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name",$link)or die("cannot select DB");


$sql="SELECT name FROM tblprofile WHERE userId = '".$q."'";

$result = mysql_query($sql);

$row = mysql_fetch_array($result);

$name =$row['name'];

if($name == '' || empty($name)) {
  echo "<b>ID not found.</b>";
} else {
  echo "<b>".$name."</b>";
}

mysql_close($link);
?>
Sign up to request clarification or add additional context in comments.

Comments

2

You cannot access the DB directly through Javascript.

You can use AJAX to call a serverside (e.g. PHP) page that queries the DB though

Comments

2

The answer it's AJAX, but first of all it's better if you understand what AJAX is: Asynchronous JavaScript And XML. Then, for simplify your task it's better if you use a javascript framework like jQuery or mootools.
I personally suggest jQuery.

4 Comments

NO! Please people, stop telling that jQuery will solve all of his problems. DO NOT use jQuery (immediatly): first learn AJAX, code it by yourself, read tutorials, run into errors, understand what's behind it. Then, if you like, switch to jQuery but don't just blindly use tools without knowing what they do. EDIT: of course this is a comment directed to all the answers about jQuery, not just this particular one
@nico, I disagree. The whole point of a library like jQuery is to protect you from all the ugly browser-specific details. It helps to understand them eventually, but I don't think it's a prerequisite. That's why jQuery is so great, it gets you doing advanced stuff in a fast and (generally) safe manner. You don't think every programmer should learn assembler first, do you? :)
@Ian Varley: No, although I think at some point every programmer should at least learn the basis of assembler. I'm not saying that he should rewrite jQuery, God no! Just that he can write a simple "AJAX library" not even cross-browser, just for whatever browser he uses. In this way he will learn how the process works and what are the problems with it. I have done it and it did not take more than a couple of days to get something functional. Then of course you can start with JQuery, have it working and then understand how it works, but personally I find it difficult to do afterwards.
to be honest I was coding in Javascript BF (before Firefox ^_^), and I'm absolutely with @nico. If you want use AJAX learn at least the basis of javascript first, then try to call the XML async methods and then enjoy the jQuery framework (if you want consider yourself a developer)
0

Use an AJAX-Call to get the data you need from a server side script (here php) and insert the result of the call in the desired textbox.

Comments

0

Better use Mootools, jQuery, YUI or any other js framework to perform Ajax requests. This will reduce your development time. For more info check apis of jQuery:

http://api.jquery.com/category/ajax/

Comments

0

You will need to use ajax which is 9/10ths javascript anyway. I suggest using a JS framework so that you don't have to code for different browsers. Then you will need something on the server side that will process the request and spit the required data back at you. Popular formats are XML (the x in ajax), JSON, or just plain ol' HTML. Either way you will need a javascript callback to process the result (or error condition, don't forget that) and populate your textbox. Personally I prefer just returning HTML fragments but if you've got a framework chances are you'll find XML and JSON handling in it so go crazy.

Comments

0

No ajax or javascript needed.
Just make alphabetical listing of all users with links to edit page. You can also add to this page a form with a single textbox to enter userid manually.
Both links and form leads to the edit page that use userid from the query string to retrieve users detais.

Comments

0

The first step is to create a PHP script which will send parse-able data to JavaScript. Do not allow JavaScript to pass raw SQL queries to your PHP.

<?php
$sqlGetName = $mysqli->prepare("SELECT id, name FROM users WHERE id=?");
$sqlGetName->bind_param("i", $_GET['id']);
$sqlGetName->execute();

$result = array('success' => false, 'id' => null, 'name' => null);

$sqlGetName->bind_result($result['id'], $result['name']);

if($sqlGetName->fetch()) {
  $result['success'] = true;
}

echo json_encode($result);

Then use JavaScript to fetch the values. The example below uses the MooTools library for simplicity's sake, but could be done with another library or in plain old regular JavaScript.

var jsonRequest = new Request.JSON({url: 'get_user.php',
  onSuccess: function(result) {
    if(result.success) {
      alert(result.id + ': ' + result.name);
    } else {
      alert('Not Found');
    }
  }
});

jsonRequest.get({'id': 3});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.