on submit ajax result undefine

喜夏-厌秋 提交于 2021-02-11 12:24:26

问题


my code is :

$('form').submit(function(){
                var email           = $('#email').val();
                var dataString      = 'email='+email;
                var datadata;
                $.ajax({
                    type     : "get",
                    url      : "checkEmail.php",
                    data     : dataString,
                    dataType : "html",
                    success  : function(result){
                                 datadata = result;

                              }   
                });

          alert(datadata);
          return false;
            });

why this datadata is undefine ?

i develope a from. and i must check duplicate email by ajax befor submit. it return catect result but form will submited.


回答1:


the ajax call is asynchronous, which means when the alert is fired, the ajax call hasn't completed yet.

try putting the alert on the ajax success function like this:

$('form').submit(function(){
                var email           = $('#email').val();
                var filename        = '<?php echo basename($_SERVER['PHP_SELF'], '.php'); ?>';
                var dataString      = 'email='+email+'&userlevel='+filename<?php echo isset($_GET['ID']) ? "+'&uid='+".$_GET['ID'] : '';  ?>;
                var datadata;
                $.ajax({
                    type     : "get",
                    url      : "checkEmail.php",
                    data     : dataString,
                    dataType : "html",
                    success  : function(result){
                                 datadata = result;
                                 alert(datadata);

                              }   
                });


          return false;
        });



回答2:


This is because the onsuccess is a async call.. you are trying to get datadata while it has not been defined yet. Create a function where you define datadata @ the onsuccess and pass it result so it will be called when it is available



来源:https://stackoverflow.com/questions/14997857/on-submit-ajax-result-undefine

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!