5

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

Cœur
  • 37,241
  • 25
  • 195
  • 267
PipBoy2000
  • 440
  • 7
  • 21
  • 2
    In your ajax call set `dataType` to `'json'`. Put a variable in the success as argument like `success(data)` and use it within that scope like `data.message`. Read the jquery docs for what other arguments get passed to the success, error... – frz3993 Dec 18 '17 at 23:13
  • Thanks but no success :( Within 7 hours i will set bounty for this thread – PipBoy2000 Dec 20 '17 at 15:10
  • It will help to know better what is happening: can you open chrome dev tools, network monitor and check the request status? is it a 200? on the console tab do you see any warning? – Tiago Coelho Dec 27 '17 at 10:01
  • @PipBoy2000 is your form+ajax hosted on another server? – Salman A Dec 28 '17 at 13:38
  • @SalmanA is on the same server – PipBoy2000 Jan 02 '18 at 08:24
  • 1
    The issue was crappy coding by the plugin author. Anyway, the answer suggesting adding `dataType: "json"` is correct. Also `JSON.parse` is alternate solution. – Salman A Jan 02 '18 at 08:26

5 Answers5

6

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");
Salman A
  • 262,204
  • 82
  • 430
  • 521
NappingRabbit
  • 1,888
  • 1
  • 13
  • 18
2

Try the following, I have explained the changes inside comments:

$(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
            }
        });
    });
});
Salman A
  • 262,204
  • 82
  • 430
  • 521
plonknimbuzz
  • 2,594
  • 2
  • 19
  • 31
1

I don't feel your ajax had issues, what i can see from the Joomla php code, everytime when you request that joomla URL you will always get a response header status code as 200, so your javascript will always land on success block of ajax code, returning with some json based message, when i checked the joomla acymaling (version 5.8.1 for joomla 3.8.3) code for that controller, i saw on line number 74 they are checking if the request is made using ajax, but missing Access-Control-Allow-Origin in php header which will restrict your outside call so you can replace this if condition from :

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

to

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

so to allow calls from any other domain as well, but do remember this can also cause vulnerabilities to you joomla code. also you need to change your HTML form as well add one more hidden field in your HTML :

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

so to allow ajax request by your joomla controller file.

now in your success block of ajax you can make a check something like this :

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

I hope this will help you in acomplishing what you want to, Happy coding.

Abhinav Verma
  • 425
  • 7
  • 14
0

I also face this type of problem.for solving this type of problem i Put a variable in the success as argument html.

e.g. success(html)

and

console.log(html)

this shows all errors including notices and all. turn on errore_reporting['E_ALL'];. and do not set dataType to 'json' .

TarangP
  • 2,711
  • 5
  • 20
  • 41
0

Simple solution to your question is :

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

data : Response returned from the server to your AJAX call

id_of_tag : where you want to display your returned output.

Its just an example, you can decide, what kind of data you want to return and what you want to do with your response.

To answer your question: On Success parameter in function will contain your response.

As in my case, i am returning another JSP page, which i want to display in div tag.

Also check below link : I think it might help you

Best way to check if AJAX request was successful in jQuery

Sachin Bankar
  • 372
  • 6
  • 13