简体   繁体   中英

Using jQuery to return json values to a form field

I've created a jsfiddle with my code - not the CSS section has the PHP logic just for demonstration.

I want to enter a postcode in the zip field - then once the button is clicked it queries the geocode googlemaps script and returns a json object - I am just having problems returning this object back to the form fields. I can see the json in the console log - but i'm doing something wrong when passing it back to the view. Any ideas?

http://jsfiddle.net/JxBQZ/2/

Here is the js file

    $('form').on('click','#geocode',function(event) {    
    event.preventDefault();
    var zip = $('#geocode_field').val();

    $.ajax({
        type: "GET",
        url: "/test/gmaps",
        data: { zip: zip},
        dataType: "json",
        cache: true,
        success: function(data){
            console.log(data.street);
        }   
    });
});


<form>
<label>Zip</label>
<input type="text" id="geocode_field" name="zip" /><button id="geocode">Search</button>
<label>Street 1</label>
<input type="text" id="street1" name="street1" />
<label>Street 2</label>
<input type="text" id="street2" name="street2" />
<label>Town</label>
<input type="text" id="town" name="town" /> 
<label>County</label>
<input type="text" id="county" name="county" />
</form>

You should set a dataType to json instead of jsonp , because you called to your own domain. jsonp is used for cross domain ajax and it also required difference returned format.

dataType: "json",

Hope this helps

Instead of $.ajax() method, use $.post() method. It will then update your views part.

Try something like this:

$.post("/test/gmaps", { data: zip}, function(data) {
for (var key in data) {
    $('#fetchdata').html(data.street); 
   }}, "json");

here, #fetchdata is the id in which data is to be received, it can be span, input box etc. In your query when you return the value, return it in json_encoded format. Such as:

function some(){
//your query
$data_to_return[] = something;
echo json_encode($data_to_return);
}

You can read more about the $.post() method HERE

Sussed it... its too early. :(

    $('form').on('click','#geocode',function(event) {    
    event.preventDefault();
    var zip = $('#geocode_field').val();

    $.ajax({
        type: "GET",
        url: "/test/gmaps",
        data: { zip: zip},
        dataType: "json",
        cache: true,
        success: function(data){
            console.log(data.street);
            $('#street1').val(data.street);
        }   
    });
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM