Skip to content Skip to sidebar Skip to footer

Form Onsubmit With Php And Javascript

I have a site that loads data based on user input in a form. I also want to refresh a google map based on that same input. Unfortunately, when I submit the form, it correctly retri

Solution 1:

If you don't want to reload your page, don't do an onsubmit. Instead, change your HTML to...

<div id="user-location">
    <input id="addressInput" name="addressInput"type="text" maxlength="5"/>
    <input id="submit4" value="GO"type="submit" onclick="codeAddress();"/>
</div> 

Your Javascript would then just update the map without submitting the form after you've ran your geocoding request. Alternatively you can also use jQuery to attach the click event like so...

$(document).ready(function () {
    $('#submit4').click(function () {
        codeAddress();
    });
});

Or you could insert your entire request in there. To make that work, you would remove the onclick event. But if you don't want to have a dependency on jQuery, just use the first solution. Again, the key is not to do a full submit. To communicate with your PHP file, have your function return the results as JSON via...

echo json_encode($geodata);

... and then request it with $.getJSON which is a jQuery utility which works like so...

$.getJSON('[php script name].php[?any args]', function(data) {
    // assign your geocodes here
});

Solution 2:

You're looking to prevent the form's default behavior, which is to submit, and for a cross-browser solution, I'd recommend jQuery's prevent default function. Check it out here.

Post a Comment for "Form Onsubmit With Php And Javascript"