Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to obtain response from form submitted by AJAX?

I want to use Acymailing Joomla! component installed at example.com/mailer to manage subscriptions from non Joomla site on example.com

In that case I have simple script

 $(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!');
        }
      });
    });
  });

and form

<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>

Everything works fine except success, error states...

Joomla Acymailing have sub.php file to handle ajax responses

 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');
            }
        }
    }

And JSON looks like on Joomla side registration to the same form by index.php?option=com_acymailing&ctrl=sub

 message    Subscribe confirmed
 type   success
 code   3

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

The question is: how to obtain that submission statuses success, error, already submbited etc on external submission form (at example.com page)?

like image 801
PipBoy2000 Avatar asked Dec 18 '17 22:12

PipBoy2000


1 Answers

this simple change may do it for you:

$(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!');
    });
  });
});

I personally like:

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

since your result is in JSON, that should be more like:

$.post("https://example.com...", {
    data: $('form').serialize()
}, function(data) {
    console.log(data); // shows full return object in console
    swal('Great success!');
}, "json");
like image 78
NappingRabbit Avatar answered Sep 28 '22 00:09

NappingRabbit