简体   繁体   中英

php ajax display data from database in multiple textboxes

Every one am new to php and ajax.
Am writing a code to fetch data from mysql database and display them in textboxes but is not working.

Here is my code.
I need your help please.
Thanks in advance

    $('#btn_get').on('click', function(){
     $.ajax({
       type    : "get",
       url     : '/path/to/php/file',       
       success : function(data)
       {
         $('#input-box1').val(data);
         $('#input-box2').val(data);
       }
     });
    });
    <input type="text" id="input-box1">
     <input type="text" id="input-box2">
    <button type="button" id="btn_get">Click</button>
    //get data from db here
    $textbox1 = 'foo';
    $textbox2 = 'deen';
    echo $textbox1;
    echo $textbox2;



Here are some approaches, maybe them can help you:

  1. The first approach would be to check your console to make sure that the jQuery version allows you to use the $.ajax() resource. Some jQuery versions like the "slim" doesn't provide ajax calls.

  2. Once you have checked that put the property error within your ajax call:

$('#btn_get').on('click', function(){
 $.ajax({
   type    : "get",
   url     : '/path/to/php/file',       
   success : function(data)
   {
     $('#input-box1').val(data);
     $('#input-box2').val(data);
   },
   error: function(xhr, ajaxOptions, thrownError) {
       console.log(xhr);
   }
 });
});

If you have a error response you will be able to identify it checking your browser's console tool (F12).

  1. Check your /path/to/php/file to make sure that your file really exists.
  2. Remember that the success callback gets your echo command as a string. So probably your return will be something like this:
foodeen

A good approach would be to return a json response:

$textbox1 = 'foo';
$textbox2 = 'deen';
echo json_encode(array($textbox1 ,"textBox1"));

Finally when your response is executed in the success callback you'll be able to convert it from plain string to a json format:

$('#btn_get').on('click', function(){
 $.ajax({
   type    : "get",
   url     : '/path/to/php/file',       
   success : function(data)
   {
     var response = JSON.stringify(data);
     $('#input-box1').val(response[0]);
     $('#input-box2').val(response[1]);
   },
   error: function(xhr, ajaxOptions, thrownError) {
       console.log(xhr);
   }
 });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM