Interactive by Nature

Extracting Ajax Return Data With jQuery

Problem

I love my job and the people I work with, but some of our standard procedures are somewhat outdated. For example, when we need data from the back-end, we get a hidden html input field with the requested data in the value attribute. Sometimes we get two hidden inputs with data that needs to be extracted. Sometimes we get markup and display it via AJAX.

The problem begins when we need to extract that value from the returned hidden input field and display it to the end user in a text field.

When you search for things like extracting “extracting ajax return data”, there’s really not that much out there. This leads me to believe that most developers are using a more current method like JSON. We are moving toward RESTful solutions, but we’re not there yet.

Solution

First create a jQuery object from the response data (inputs in this case).

var $response=$(data);

Next create a variable dataValue and .filter() out everything but the input field with id=”hiddenInput” and extract it’s value.

dataValue = $response.filter('#hiddenInput').val();

The last piece of the solution is to set the displayed input attribute value to whatever value was returned in the hidden input. In my situation, it’s the users mortgage payment amount.

				
$('#amount').attr('value',dataValue);

You might end up with something that looks like this.

$.ajax({
    type: "GET",
    url: url,
    data: {accountNumber: payment},
    success: function(data, result) {
        var $response=$(data);
        dataValue = $response.filter('#hiddenInput').val();
        $('#amount').attr({
            value: dataValue,
            readonly: true
        });
    }
});

If you know of a different method, please share in the comments section below.

Comments

  1. how do i construct the data in the php so it wont be echoed.. ??

    Sagive on September, 18th, 2012 at 5:29 pm
  2. Sagive, I only program in javascript, so I’m not sure. Maybe someone will see the comment and reply.

    admin on September, 18th, 2012 at 7:02 pm
  3. @sagive :
    Just call your script using ajax and echo json_encode(data). It will be returned to the calling jquery script. It will be echoed directly on to the browser until you do it in jQuery.

    Kunal on July, 16th, 2013 at 4:21 am
  4. Correcting :
    It will be not be echoed directly on to the browser until you do it in jQuery.

    Kunal on July, 16th, 2013 at 4:22 am
  5. Really needed this, thanks!

    Spencer on May, 23rd, 2016 at 9:43 am

Leave a Comment