如何从AJAX提交的表单中获得响应?

时间:2017-12-18 22:52:37

标签: javascript php jquery ajax joomla

我想使用Acymailing Joomla!安装在 example.com/mailer 的组件,用于管理example.com上非Joomla网站的订阅

在这种情况下,我有简单的脚本

 $(function () {
    $('form').on('submit', function (e) {
      e.preventDefault();
      $.ajax({
        type: 'post',
        url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
        data: $('form').serialize(),
        success: function () {
          swal('Great success!');
        }
      });
    });
  });

和表格

<form class="form-inline" action="https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub" method="post">
    <div class="form-group">
        <label class="sr-only" for="user_name">Email address</label>
        <input id="user_name"   type="text" name="user[name]" value="" class="form-control" placeholder="Email">
    </div>
    <div class="form-group">
        <label class="sr-only" for="user_email">Password</label>
        <input id="user_email"   type="text" name="user[email]" value="" class="form-control" placeholder="Password">
    </div>
    <button type="submit" class="btn btn-default">Sign Up!</button>
    <input type="hidden" name="user[html]" value="1" />
    <input type="hidden" name="acyformname" value="formAcymailing1" />
    <input type="hidden" name="ctrl" value="sub"/>
    <input type="hidden" name="task" value="optin"/>
    <input type="hidden" name="redirect" value="https://example.com"/>
    <input type="hidden" name="option" value="com_acymailing"/>
    <input type="hidden" name="visiblelists" value=""/>
    <input type="hidden" name="hiddenlists" value="1"/>
</form>

一切正常,除了成功,错误状态......

Joomla Acymailing有sub.php文件来处理ajax响应

 if($config->get('subscription_message',1) || $ajax){
        if($allowSubscriptionModifications){
            if($statusAdd == 2){
                if($userClass->confirmationSentSuccess){
                    $msg = 'CONFIRMATION_SENT';
                    $code = 2;
                    $msgtype = 'success';
                }else{
                    $msg = $userClass->confirmationSentError;
                    $code = 7;
                    $msgtype = 'error';
                }
            }else{
                if($insertMessage){
                    $msg = 'SUBSCRIPTION_OK';
                    $code = 3;
                    $msgtype = 'success';
                }elseif($updateMessage){

                    $msg = 'SUBSCRIPTION_UPDATED_OK';
                    $code = 4;
                    $msgtype = 'success';
                }else{
                    $msg = 'ALREADY_SUBSCRIBED';
                    $code = 5;
                    $msgtype = 'success';
                }
            }
        }else{
            if($modifySubscriptionSuccess){
                $msg = 'IDENTIFICATION_SENT';
                $code = 6;
                $msgtype = 'warning';
            }else{
                $msg = $modifySubscriptionError;
                $code = 8;
                $msgtype = 'error';
            }
        }

        if($msg == strtoupper($msg)){
            $source = acymailing_getVar('cmd', 'acy_source');
            if(strpos($source, 'module_') !== false){
                $moduleId = '_'.strtoupper($source);
                if(acymailing_translation($msg.$moduleId) != $msg.$moduleId) $msg = $msg.$moduleId;
            }
            $msg = acymailing_translation($msg);
        }

        $replace = array();
        $replace['{list:name}'] = '';
        foreach($myuser as $oneProp => $oneVal){
            $replace['{user:'.$oneProp.'}'] = $oneVal;
        }
        $msg = str_replace(array_keys($replace),$replace,$msg);

        if($config->get('redirect_tags', 0) == 1) $redirectUrl = str_replace(array_keys($replace),$replace,$redirectUrl);

        if($ajax){
            $msg = str_replace(array("\n","\r",'"','\\'),array(' ',' ',"'",'\\\\'),$msg);
            echo '{"message":"'.$msg.'","type":"'.($msgtype == 'warning' ? 'success' : $msgtype).'","code":"'.$code.'"}';
        }elseif(empty($redirectUrl)){
            acymailing_enqueueMessage($msg,$msgtype == 'success' ? 'info' : $msgtype);
        }else{
            if(strlen($msg)>0){
                if($msgtype == 'success') acymailing_enqueueMessage($msg);
                elseif($msgtype == 'warning') acymailing_enqueueMessage($msg,'notice');
                else acymailing_enqueueMessage($msg,'error');
            }
        }
    }

JSON看起来像Joomla一样通过index.php注册到同一个表单?option = com_acymailing&amp; ctrl = sub

 message    Subscribe confirmed
 type   success
 code   3

 {"message":"Subscribe confirmed","type":"success","code":"3"}

问题是:如何在外部提交表单( at example.com page )上获取提交状态成功,错误,已经下限等?

5 个答案:

答案 0 :(得分:6)

这个简单的改变可能会为你做到:

$(function () {
  $('form').on('submit', function (e) {
    e.preventDefault();
    $.ajax({
        type: 'post',
        url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
        data: $('form').serialize()
      }
    }).done(function (data) {
        swal('Great success!');
    });
  });
});

我个人喜欢:

$.post("https://example.com...", {
    data: $('form').serialize()
}, function(data) {
    swal('Great success!');
});

因为您的结果位于JSON,所以应该更像是:

$.post("https://example.com...", {
    data: $('form').serialize()
}, function(data) {
    console.log(data); // shows full return object in console
    swal('Great success!');
}, "json");

答案 1 :(得分:2)

尝试以下内容,我已解释了评论中的更改:

$(function () {
    $('form').on('submit', function (e) {
        e.preventDefault();
        var formdata = $(this).serializeArray(); //i really prefer serializeArray better than serialize (up2u)
        $.ajax({
            type: 'post',
            dataType: 'json', //because your data is json
            url: 'https://example.com/mailer/index.php?option=com_acymailing&ctrl=sub',
            data: formdata, 
            success: function (d) {//d is the return/response of your url (your question answer)
                swal(
                  d.type+': '+d.code ,
                  d.message,
                  d.type
                );
            },
            error: function(d){
                swal(
                  'Oops..' ,
                  'Something went wrong!', //your json must be in trouble
                  'error'
                );
                console.log(d); //delete this in production stage
                console.log(d.responseText); //i add this so you will know what happenned exactly when you get this error. delete this too in production stage
            }
        });
    });
});

答案 2 :(得分:1)

我不觉得你的ajax有问题,我可以从Joomla php代码中看到,每次当你请求joomla URL时你总是得到response header status code as 200,所以你的javascript将总是落在成功块上ajax代码,返回一些基于json的消息,当我检查该控制器的joomla acymaling(版本5.8.1 for joomla 3.8.3)代码时,我在line number 74上看到他们正在检查请求是否使用ajax,但在php标题中缺少Access-Control-Allow-Origin,这将限制您的外部调用,以便您可以从以下位置替换此if条件:

if($ajax){
    @ob_end_clean();
    header("Content-type:text/html; charset=utf-8");
}

if($ajax){
    @ob_end_clean();
    header("Content-type:text/html; charset=utf-8");
    header("Access-Control-Allow-Origin: *");
}

所以允许来自任何其他域的调用,但请记住这也会导致您的joomla代码漏洞。您还需要更改HTML表单,并在HTML中添加一个隐藏字段:

<input type="hidden" name="ajax" value="1" />

所以允许你的joomla控制器文件发出ajax请求。

现在在你成功的ajax块中你可以做一个像这样的检查:

success:function(data, status, xhr){
    var json = $.parseJSON(data);
    swal(json.message, json.type);
}

我希望这能帮助你完成你想要的,快乐编码。

答案 3 :(得分:0)

我也面临这种类型的问题。为了解决这类问题,我把一个变量放在成功的参数html中。

e.g. success(html)

console.log(html)

这显示所有错误,包括通知和所有错误。打开errore_reporting['E_ALL'];。并且不要将dataType设置为&#39; json&#39;

答案 4 :(得分:0)

您问题的简单解决方案是:

success: function (data) {
    $("#<id_of_tag>").html(data);
}

数据:从服务器返回到您的AJAX调用的响应

id_of_tag:您要在其中显示您返回的输出。

这只是一个例子,您可以决定要返回哪种数据以及您希望如何处理回复。

回答你的问题:On Success函数中的参数将包含你的回复。

在我的情况下,我正在返回另一个JSP页面,我希望以div标签显示。

另请查看以下链接:我认为它可能会对您有所帮助

Best way to check if AJAX request was successful in jQuery