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.
how do i construct the data in the php so it wont be echoed.. ??
Sagive, I only program in javascript, so I’m not sure. Maybe someone will see the comment and reply.
@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.
Correcting :
It will be not be echoed directly on to the browser until you do it in jQuery.
Really needed this, thanks!