Form onsubmit with php and javascript

2019-09-08 17:30发布

问题:

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 retrieves the data through an SQL query but refreshes the page causing the google map to reset to the original starting point. What is the best way to resolve this?

Here is the form code:

<form id="user-location" method="post" action="#" onsubmit="return codeAddress();">
                    <input id="addressInput" name="addressInput" type="text" maxlength="5">

                   <input id="submit4" value="GO" type="submit"  >

                </div>
</form>

Here is part of the script for google maps:

function codeAddress() {
  var address = document.getElementById('addressInput').value;
  geocoder.geocode( { 'address': address}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      map.setCenter(results[0].geometry.location);
      var marker = new google.maps.Marker({
          map: map,
          position: results[0].geometry.location
      });
    } else {
      alert('Geocode was not successful for the following reason: ' + status);
    }
  });
}

回答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
});


回答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.