Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

ajsmith_codes's avatar

Solved: Ajax request data returns as object - how to populate multiple inputs?

I make an Ajax call to get contact data. I had it working where I was getting 1 piece of data: email. The returning data would populate into an input: $('input[name="email"]').val(data);

I now need to get Email and Phone. I can successfully get the data returned, but I can't seem to populate the two separate input fields.

If I do that now, I get an object. I then tried this but it doesn't work either:

$('input[name="email"]').val(data["email"]); $('input[name="number"]').val(data["phone"]);

What am I missing here?

0 likes
39 replies
ajsmith_codes's avatar

[{"id":1,"customer_id":1,"type":"Main","name":"Alfredo Nitzsche","email":"[email protected]","phone":"(759) 475-5822 x550","active":1,"slug":"aut-aperiam-ipsum","created_at":"2020-09-25 08:35:55","updated_at":"2020-09-25 08:35:55","deleted_at":null}]

kitten's avatar

hmm,... your code should work, as well s data.fieldName..

can you try to output in console this and see if you get the email?

// in the success function
done(r){
	if(r){
		console.info(r.data.email);
	}
}

ajsmith_codes's avatar

I tried to place your code in the success function, but it wouldn't work. I did this instead:

console.info(data.email);

That came back undefined, so I just did console.info(data);

[{…}] 0: {id: 1, customer_id: 1, type: "Main", name: "Alfredo Nitzsche", email: "[email protected]", …} length: 1

kitten's avatar

can you please post the ajax code part, please? It would be easier for me to see what might be wrong, otherwise i could keep guessing..

Things to make sure:

  • Your ajax endpoint exits with a json encoded string, something like this:
exit( json_encode( [ 'data' => ['your response data] ] ) );
  • your ajax request config includes (but not necessarily) the dataType:
$.ajax({
...
dataType: 'json',
})
.done(function(r){ /* here you can access: r.data since data is the "key" of your response object */ })
.error(function(x,s,e){})
ajsmith_codes's avatar

Sorry about that. :)

Here is the JS code that is in a file on it's own:

$('select[name="contact_id"]').on('change', function () {

    var contact_id = $(this).val();

    if (contact_id) {
        $.ajax({
            url: '/api/contact/get/' + contact_id,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                $('#loader').css("visibility", "visible");
            },

            success: function (data) {


                $('input[name="email"]').val(data.email);
                $('input[name="number"]').val(data["phone"]);

                console.info(data.email);

            },
            complete: function () {
                $('#loader').css("visibility", "hidden");
            },
            error : function(){
                alert('Some error occurred!');
            }
        });
    } else {
        $('select[name="contact_id"]').empty();
    }

});

Here is the Controller:

public function getContact($id){

    $data = DB::table('customer_contacts')->where("id",$id)
    ->get();

    return json_encode($data);

}
kitten's avatar

hmm..

try this:

public function getContact($id){

    $data = DB::table('customer_contacts')->where("id",$id)
    ->get();

    return [  'data' => json_encode($data) ];

}

and in your success function:

success: function (response) {
	var data = response.data;

	// this should be a valid json object
	console.info('data', data);

	// if this doesn't show up you should change how you respond (in your controller, instead of serializing the collection, transform it to array and this should work afterwards)
        console.info('email', data.email);

                $('input[name="email"]').val(data.email);
        $('input[name="number"]').val(data["phone"]);
	},
},

ajsmith_codes's avatar

Email comes back as undefined. The data comes back like this:

data [{"id":1,"customer_id":1,"type":"Main","name":"Alfredo Nitzsche","email":"[email protected]","phone":"(759) 475-5822 x550","active":1,"slug":"aut-aperiam-ipsum","created_at":"2020-09-25 08:35:55","updated_at":"2020-09-25 08:35:55","deleted_at":null}]

kitten's avatar

Have you tried my example? with the collection change to array? or better yet, to json?

// with your existent js success code
public function getContact($id){

    return DB::table('customer_contacts')->where("id",$id)->toJson();

}

ajsmith_codes's avatar

I didn't see that code before. I just tried it and got a popup that says "some error occurred" and gives me a 500.

kitten's avatar

do you have a model for the customer_contacts table? you could simply change it to:

return CustomerContact::find($id)->toJson();

if that doesn't solve it, then your last resort is to process to send the response as array and update the js success function like in my example

public function getContact($id){

    $data = DB::table('customer_contacts')->where("id",$id)->get();

	return json_encode( [ 'data' => compact($data) ] );
}

and js:

success: function (response) {
	var data = response.data;

	// this should be a valid json object
	console.info('data', data);

	//#! you should see the email address now
        console.info('email', data.email);

                $('input[name="email"]').val(data.email);
        $('input[name="number"]').val(data["phone"]);
	},
},

ajsmith_codes's avatar

I'm not sure why none of these are not working. If I make two separate ajax calls, it works.

$('select[name="contact_id"]').on('change', function () {

    var contact_id = $(this).val();

    if (contact_id) {
        $.ajax({
            url: '/api/contact/getEmail/' + contact_id,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                $('#loader').css("visibility", "visible");
            },

            success: function (data) {
                $('input[name="email"]').val(data);
            },
            complete: function () {
                $('#loader').css("visibility", "hidden");
            },
            error : function(){
                alert('Some error occurred!');
            }
        });
        $.ajax({
            url: '/api/contact/getPhone/' + contact_id,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                $('#loader').css("visibility", "visible");
            },
            success: function (data) {
                $('input[name="number"]').val(data);
            },
            complete: function () {
                $('#loader').css("visibility", "hidden");
            },
            error : function(){
                alert('Some error occurred!');
            }
        });
    } else {
        $('select[name="contact_id"]').empty();
    }

});
kitten's avatar

I use ajax in every project I have and to be honest, this never happened to me.. so I'm pretty much out of ideas..

If you want, I can have a look over team viewer f that's okay with you (you could send me the credentials through email ****@gmail.com)

Other than that I can't think of anything else :(

ajsmith_codes's avatar

Darn. Thanks for trying! I don't have Team Viewer and this is a work project, so I'm not sure I would be allowed to do that. I can, however, share it via github if you want.

kitten's avatar

It's okay, no worries :)

Here is something else you can try:

public function getContact($id){

    $data = DB::table('customer_contacts')->where("id",$id)->get();

	return json_encode(  (array)$data );
}

having access to the git repo won't help too much unless I can install the application so I could have an instance running upon which I can test :)

laracoft's avatar

@ajsmith_codes Can you show your HTML form?

$('input[name="email"]').val(data["email"]);            // if this works for <input name="email">,
$('input[name="number"]').val(data["phone"]);	// then this works for <input name="number">,
ajsmith_codes's avatar

Sure. Here are the two input fields. If I send two ajax requests separately, it works fine. It's when I send one request for two pieces of data.

                            <label
                                class="col-form-label font-weight-bold {{ $errors->has('number') ? 'text-danger' : '' }}">

                                Phone

                            </label>

                            <div
                                class="input-group">

                                <input
                                    class="form-control {{ $errors->has('number') ? 'border-danger' : '' }}"
                                    id="number"
                                    type="text"
                                    name="number"
                                    value="{{ $contact->phone ? $contact->phone : old('number') }}">
                                <div
                                    class="input-group-append">
                                                <span
                                                    class="input-group-text">

                                                    <input
                                                        type="checkbox"
                                                        class="mr-1"
                                                        name="deletePhone"
                                                        value="1"
                                                    >
                                                    <span
                                                        class="error">Delete</span>
                                                </span>

                                </div>

                            </div>

                            @error('number')
                            <p class="error">{{ $message }}</p>
                            @enderror

                        </div>

                        <div
                            class="form-group">

                            <label
                                class="col-form-label font-weight-bold {{ $errors->has('email') ? 'text-danger' : '' }}">

                                Email

                            </label>

                            <div
                                class="input-group">


                                <input
                                    class="form-control {{ $errors->has('email') ? 'border-danger' : '' }}"
                                    id="email"
                                    type="email"
                                    name="email"

                                    value="{{ $contact->email ? $contact->email : old('email') }}">
                                <div
                                    class="input-group-append">
                                                <span
                                                    class="input-group-text">

                                                    <input
                                                        type="checkbox"
                                                        class="mr-1"
                                                        name="deleteEmail"
                                                        value="1"
                                                    >
                                                    <span
                                                        class="error">Delete</span>
                                                </span>

                                </div>
                            </div>

                            @error('email')
                            <p class="error">{{ $message }}</p>
                            @enderror

                        </div>
kitten's avatar

Casting data to array didn't solve it?

laracoft's avatar

@ajsmith_codes Does this URL /api/contact/get/' + contact_id with console.info(data) still get you this response?

[{"id":1,"customer_id":1,"type":"Main","name":"Alfredo Nitzsche","email":"[email protected]","phone":"(759) 475-5822 x550","active":1,"slug":"aut-aperiam-ipsum","created_at":"2020-09-25 08:35:55","updated_at":"2020-09-25 08:35:55","deleted_at":null}]
  1. If yes, try console.info(data[0].email) and console.info(data[0].phone)
  2. If #1 shows email and phone, then go for $('input[name="email"]').val(data[0].email); and $('input[name="number"]').val(data[0].phone);
  3. If #1 gives errors, show the output for console.log(data)
ajsmith_codes's avatar

When using this:

$data = DB::table('customer_contacts')->where("id",$id)->get();

    return json_encode(  (array)$data );

I get this back when I do a console.info(data):

{*items: Array(1)} *items: Array(1) 0: {id: 1, customer_id: 1, type: "Main", name: "Alfredo Nitzsche", email: "[email protected]", …} length: 1 proto: Array(0)

laracoft's avatar

Can change it to console.log(data)? More familiar to me.

laracoft's avatar

@ajsmith_codes pretty sure this will work:

$('select[name="contact_id"]').on('change', function () {

    var contact_id = $(this).val();

    if (contact_id) {
        $.ajax({
            url: '/api/contact/get/' + contact_id,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                $('#loader').css("visibility", "visible");
            },

            success: function (data) {
                $('input[name="email"]').val(data[0].email);
                $('input[name="number"]').val(data[0].phone);

                console.log(data);
            },
            complete: function () {
                $('#loader').css("visibility", "hidden");
            },
            error : function(){
                alert('Some error occurred!');
            }
        });
    } else {
        $('select[name="contact_id"]').empty();
    }

});
jlrdw's avatar

@ajsmith_codes object array or single object?

Single object would be:

$('input[name="email"]').val(data.email);
$('input[name="number"]').val(data.phone);

The indexes like [0] is more than one row.

laracoft's avatar

@jlrdw I think the returned JSON is an array of 1 object. I'm taking the one/light touch approach to solve this case.

ajsmith_codes's avatar

Sorry, no. I get:

    at Object.success (custom.js:174)
    at fire (app.js:65779)
    at Object.fireWith [as resolveWith] (app.js:65909)
    at done (app.js:72069)
    at XMLHttpRequest.<anonymous> (app.js:72330)
laracoft's avatar

Need to see what console.log(data) does.

$('select[name="contact_id"]').on('change', function () {

    var contact_id = $(this).val();

    if (contact_id) {
        $.ajax({
            url: '/api/contact/get/' + contact_id,
            type: "GET",
            dataType: "json",
            beforeSend: function () {
                $('#loader').css("visibility", "visible");
            },

            success: function (data) {
                // $('input[name="email"]').val(data[0].email);
                // $('input[name="number"]').val(data[0].phone);

                console.log(data);
            },
            complete: function () {
                $('#loader').css("visibility", "hidden");
            },
            error : function(){
                alert('Some error occurred!');
            }
        });
    } else {
        $('select[name="contact_id"]').empty();
    }

});
ajsmith_codes's avatar

The strange thing is that I didn't get anything by using console.log. I only get the error.

EDIT: I commented out the input code and was able to see the console.log info:

{*items: Array(1)} *items: Array(1) 0: active: 1 created_at: "2020-09-25 08:35:55" customer_id: 1 deleted_at: null email: "[email protected]" id: 1 name: "Alfredo Nitzsche" phone: "(759) 475-5822 x550" slug: "aut-aperiam-ipsum" type: "Main" updated_at: "2020-09-25 08:35:55" proto: Object length: 1 proto: Array(0) proto: Object

laracoft's avatar

ok, change console.log(data) to console.log(data[0]["phone"]), does it work?

If yes, use $('input[name="email"]').val(data[0]["email"]); and $('input[name="number"]').val(data[0]["phone"]);

ajsmith_codes's avatar

I get:

Uncaught TypeError: Cannot read property 'phone' of undefined

Next

Please or to participate in this conversation.