0

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;



1
  • 1
    url : '/path/to/php/file', /path/to/php/file must be the actual php file you requesting response from' Commented Mar 14, 2019 at 10:39

1 Answer 1

1

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);
   }
 });
});
Sign up to request clarification or add additional context in comments.

1 Comment

I'm glad to hear that :)

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.