0

I am trying post a form data using AJAX and display the result in a div. Despite of all my best efforts, I failed.

Here is the code I am using with jQuery 1.8.3

HTML:

<form action="" method="post" id="forecastform">
    <input type="text" name="weatherloc" class="weatherloc">
    <input type="submit" name="weathersubmit" class="weathersubmit" value="Get Forecast">
</form>

<div class="wfposts"></div>

JavaScript at head section:

        <script type="text/javascript">
            jQuery('#forecastform').submit(function(event) {
            event.preventDefault();
            var term = jQuery('.weatherloc').val();
            var url = <?php echo get_template_directory_uri() . '/local-forecast-process.php';?>;

                 var posting = jQuery.post( url, { weatherloc: term } );

                    posting.done(function( data ) {
                    var content = jQuery( data );
                    jQuery( ".wfposts" ).empty().append( content );
                    });
            });
        </script>

First of all, the page reloads ignoring the event.preventDefault();
I am not sure if the data is being sent or not as the div isn't being populated after the page loads.

Someone please help

4

2 回答 2

2

您必须将其包装在 $.ready 中,因为forecastform当 jQuery 尝试选择它时该元素不存在。

$(document).ready(function(){
   jQuery('#forecastform').submit(function(event) {
   ....
   ...
   })
}
于 2013-08-21T16:17:31.390 回答
2

语法错误,未加引号的字符串!

代替:

var url = <?php echo get_template_directory_uri() . '/local-forecast-process.php';?>;

var url  = "<?php echo get_template_directory_uri(); ?>/local-forecast-process.php";

如果元素后不包含 javascript,则添加 DOM 就绪处理程序。

于 2013-08-21T16:20:16.207 回答