0

I am trying to return data from a database and populate a text field after the user enters an ID in the first text box. Currently I had the code working as long as the user did not enter a space in the ID number. Now I am attempting to allow that use case. My PHP code returns a json encoded array with three fields: first_name, last_name, and full_name.

When I use console.log(data) to view the data being returned I receive the following:

    {"first_name":"Test","last_name":"Test","full_name":"Test Test"} 

However in my code, I try to write data.full_name in a .val() nothing is populated, and when use the console.log I get an error saying "undefined".

Here is the whole jQuery Code:

    $("#ID").blur(function () {
        var params = {};
        params.ID = encodeURIComponent($(this).val());
        $.post("getter.php", params, function ( data ) {
          if (!data) {
             $("input[name=username]").val("User Not Found");
          } else {
             $("input[name=username]").val(data.full_name);
             $("input[name=username]").attr("readonly", true);
          }
        });
     });

Any help you can offer would be much appreciated.

0

2 Answers 2

1

Force jQuery to read the returned data as json:

$("#ID").blur(function () {
        var params = {};
        params.ID = encodeURIComponent($(this).val());
        $.post("getter.php", params, function ( data ) {
          if (!data) {
             $("input[name=username]").val("User Not Found");
          } else {
             $("input[name=username]").val(data.full_name);
             $("input[name=username]").attr("readonly", true);
          }
        }, "json"); // <- json forced
     });

and then make sure your returned data is in proper json format (for example with json_encode in php)

Sign up to request clarification or add additional context in comments.

2 Comments

By adding JSON to the post, it will send the data to the PHP page as a JSON object, correct? How can I pull that information to run my SQL query on the getter page? Sorry, that is a new method to me.
No, it will interpret the data you are getting back as a json object. This is why you are not able to use data.full_name with your above code - jquery is not interpreting the data it receives back as an object. See the jquery documentation on $.post: api.jquery.com/jQuery.post .
0

Use trim() to remove spaces.

Then you can check if the parameter value is_numeric(), and if false, set a default value.

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.