How to get a response from the form submitted by AJAX?

I want to use Acymailing Joomla! component installed in example.com/mailer for managing subscriptions from a site without Joomla to example.com

In this case, I have a 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 status ...

Joomla Acymailing has a 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 does JSON look on the Joomla registration side in the same form on index.php? option = com_acymailing & ctrl = sub

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

The question arises: how to get the status of the sending status, an error that is already subordinate, etc. in an external submission form ( on example.com )?

+5
source share
6 answers

I don’t feel that your ajax had problems, what I see from the Joomla php code, every time you request a joomla URL, you will always get a response header status code as 200 , so your javascript will always land on a success block ajax code returning with some message in json, when I checked the joomla acymaling code (version 5.8.1 for joomla 3.8.3) for this controller, I saw on line number 74 , they check if the request is being executed using ajax, but are missing Access-Control-Allow-Origin in the php header, which will limit your external call so that you can replace this if condition:

 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: *"); } 

to allow calls from any other domain, but remember that this could also cause vulnerabilities for you, the joomla code. you also need to change your HTML form, as well as add another hidden field to your HTML:

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

to allow ajax request by your joomla controller file.

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

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

I hope this helps you in what you want, happy coding.

+1
source

this simple change can 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 , this 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"); 
+6
source

Try the following: I explained the changes inside the 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 } }); }); }); 
+2
source

I also run into this type of problem. To solve this type of problem. Put the variable in success as an html argument.

 eg success(html) 

and

console.log(html)

it shows all errors, including notifications and all. enable errore_reporting['E_ALL']; . and do not set dataType to "json".

0
source

A simple solution to your question:

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

: Answer returned from the server to an AJAX call

id_of_tag: where you want to display the returned result.

Its just an example, you can decide what data you want to return and what you want to do with the answer.

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

As in my case, I am returning another JSP page that I want to display in the div tag.

Also check out the link below: I think this may help you

Best way to check if an AJAX request was successful in jQuery

0
source

I just looked at the source code and it looks like the script was written by someone who does not know the correct Content-Type for JSON or how to use json_encode . You need to make the following changes to the AJAX code:

 $(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(jsonAsHtml) { // the script sets Content-Type to text/html // so jQuery "intelligent guessing" fails // you must call parseJSON on the content yourself var data = $.parseJSON(jsonAsHtml); swal('Great success! message=' + data.message + ', type=' + data.type + ', code=' + data.code); } }); }); }); 
0
source

Source: https://habr.com/ru/post/1274174/


All Articles