Ajax запрос не выполнен: неожиданное завершение JSON - PullRequest
0 голосов
/ 06 февраля 2020

Я новичок в JQuery, и когда я пытаюсь опубликовать данные на своей странице PHP, я получаю следующую ошибку:

Результат: parsererror SyntaxError: неожиданное завершение JSON input 200 ok

Вот код моей php страницы:

     $('#contactUsForm').on('submit',function(event){
          event.preventDefault();
          var name  = $("#name").val();       
          var subject = $("#subject").val();      
          var comments = $("#commentArea").val();

          var mydata = {personName:name, subjectName:name, commentArea:comments};         
          $.ajax({            
                    type: "POST",             
                    url: "check_and_send_mail.php",           
                    data: JSON.stringify(mydata),
                    dataType: "json",             
                    success : function(data){
                          var erreur = typeof(reponse.Error)!='undefined' ? reponse.Error : null;
                          var result = typeof(reponse.result)!='undefined' ? reponse.result : null;
                          var list_grp = $("#list_grp");

                          alert('it is okay');            
                    },            
                    error : function(xhr, status, error){
                          alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
                    }         
         });   
 });

И мой check_and_send_mail. php находится в тот же каталог, что и на другой странице, и есть только это:

      <?php       ?> 

Какое решение?

Заранее спасибо

Ответы [ 4 ]

0 голосов
/ 07 февраля 2020

Я следовал вашему совету, но он не работает:

$ ('# contactUsForm'). On ('submit', function (event) {event.preventDefault ();

    var name  = $("#name").val();
    var subject = $("#subject").val();
    var comments = $("#commentArea").val();

    var mydata = {'personName':name, 'subjectName':name, 'commentArea':comments};
    $.ajax({ 
        type: "POST",
        url: "check_and_send_mail.php",
        data: mydata,
        dataType: "json",
        success : function(response){
            var erreur = typeof(response.Error)!='undefined' ? response.Error : null;
            var result = typeof(response.result)!='undefined' ? response.result : null;
            var list_grp = $("#list_grp");

            alert('it is okay');
        },
        error : function(xhr, status, error){
              alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            //afficher_erreur('Ajax error :' + formatErrorMessage(jqXHR, textStatus));
        }
    });
});
0 голосов
/ 07 февраля 2020

Я не думаю, что вам нужно JSON привести данные в строку, просто обновите переменную mydata и удалите JSON .stringify

var mydata = {'personName':name, 'subjectName':name, 'commentArea':comments};         
$.ajax({            
    type: "POST",             
    url: "check_and_send_mail.php",           
    data: mydata,
    dataType: "json",             
    success : function(data){
       // here data is a response
    },            
    error : function(xhr, status, error){
      // handle error
    }         
});

, затем из PHP вы можете отправить ответ

 $response = true; // Just a true response for now
 // Send the response
 header('Access-Control-Allow-Origin:*');
 ob_clean();
 echo json_encode($response);
 die();
0 голосов
/ 07 февраля 2020

Я исправил, но у меня всегда одно и то же сообщение об ошибке

$('#contactUsForm').on('submit',function(event){
    event.preventDefault();

    var name  = $("#name").val();
    var subject = $("#subject").val();
    var comments = $("#commentArea").val();

    var mydata = {personName:name, subjectName:name, commentArea:comments};
    $.ajax({ 
        type: "POST",
        url: "check_and_send_mail.php",
        data: JSON.stringify(mydata),
        dataType: "json",
        success : function(response){
            var erreur = typeof(response.Error)!='undefined' ? response.Error : null;
            var result = typeof(response.result)!='undefined' ? response.result : null;
            var list_grp = $("#list_grp");

            alert('it is okay');
        },
        error : function(xhr, status, error){
              alert("Result: " + status + " " + error + " " + xhr.status + " " + xhr.statusText)
            //afficher_erreur('Ajax error :' + formatErrorMessage(jqXHR, textStatus));
        }
    });
});
0 голосов
/ 07 февраля 2020

Эта часть вашего кода:

success : function(data){
                      var erreur = typeof(reponse.Error)!='undefined' ?    reponse.Error : null;
                      var result = typeof(reponse.result)!='undefined' ? reponse.result : null;
                      var list_grp = $("#list_grp");

                      alert('it is okay');            
                },           

должна выглядеть следующим образом:

 success : function(reponse){
                      var erreur = typeof(reponse.Error)!='undefined' ?  reponse.Error : null;
                      var result = typeof(reponse.result)!='undefined' ? reponse.result : null;
                      var list_grp = $("#list_grp");

                      alert('it is okay');            
                },           

Вы получили ответ в переменной 'data', а не в переменной 'reponse', которую вы Используем. Заметьте, попробуйте исправить орфографическую ошибку «response», чтобы быть уверенным, что она не смущает вас в будущем

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