Load () не работает для вызова шаблона PHP при отправке формы - PullRequest
0 голосов
/ 07 октября 2019

Я пытаюсь загрузить php-файл в div при отправке формы. В тот момент, когда все запускает строку $('#signupform').load('newsletter-signup-call.php');, у меня есть простой эхо-запрос, и он не срабатывает. Если я зайду в этот шаблон, он будет работать.

Куда я иду не так? Могу ли я запустить два Ajax-вызова (как это само по себе работает), но, похоже, есть проблемы с load.

  <script>
    $("#signupForm").submit(function(e) {
        e.preventDefault();
        var form = $(this);
        var email = $("#EmailAddress").val();

        $.ajax({
               type: "POST",
               url: form.attr('action') + '?email=' + email,
               data: form.serialize(),
               beforeSend: function(){
                 $(".newsletter-loading").show().css({"display":"inline-block"});
               },
               success: function(data)
               {
                   console.log(data); //data contain response from your php script
                   register_signup();
                   register_prefs();

                   (function() {
                       window.sib = {
                           equeue: [],
                           client_key: "xxx"
                       };
                       /* OPTIONAL: email for identify request*/
                       window.sib.email_id = email;
                       window.sendinblue = {};
                       for (var j = ['track', 'identify', 'trackLink', 'page'], i = 0; i < j.length; i++) {
                       (function(k) {
                           window.sendinblue[k] = function() {
                               var arg = Array.prototype.slice.call(arguments);
                               (window.sib[k] || function() {
                                       var t = {};
                                       t[k] = arg;
                                       window.sib.equeue.push(t);
                                   })(arg[0], arg[1], arg[2]);
                               };
                           })(j[i]);
                       }
                       var n = document.createElement("script"),
                           i = document.getElementsByTagName("script")[0];
                       n.type = "text/javascript", n.id = "sendinblue-js", n.async = !0, n.src = "https://sibautomation.com/sa.js?key=" + window.sib.client_key, i.parentNode.insertBefore(n, i), window.sendinblue.page();
                   })();

                   sendinblue.track('marketing');
                   $(".newsletter-loading").hide();
                   form.replaceWith("<br /><p>Thanks for signing up! You'll receive an email with your discount.</p>");
               }
             });

    });
    function register_prefs(){
      var email = $("#EmailAddress").val();
      Cookies.set('Address', email, { expires: 100000 });
      $('#signupform').load('newsletter-signup-call.php');
    }

    function register_signup(){
      ga( 'send', 'event', 'Newsletter Sign Up', 'submit' );
    }
  </script>

1 Ответ

0 голосов
/ 07 октября 2019

Попробуйте console.log статуса ответа, чтобы увидеть, что идет не так

function register_prefs(){

    //see if this function is triggered 
    console.log('register_prefs function triggered')

    var email = $("#EmailAddress").val();
    Cookies.set('Address', email, { expires: 100000 });

    $('#signupform').load('newsletter-signup-call.php', function( response, status, xhr ){
        console.log('Server response : ', response)//The serve response
        console.log('Status Message : ', [xhr.status, xhr.statusText])//See the status of your request, if any error it should be displayed here
    });
}

НО, зачем выполнять другой серверный вызов с нагрузкой, если вы уже используете ajax, вы можете вернуть html в первомвызовите объект json {Mydata: ..., MyHTML: ...} и просто используйте $('#signupform').html(data.MyHTML) в случае успеха.

Кроме того, не уверен, но я подозреваю, что неправильно сформированный URL, попробуйте вместо этого '/newsletter-signup-call.php' илиабсолютный путь просто чтобы быть уверенным.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...