ERR_EMPTY_RESPONSE ошибка между вызовом PHP и Ajax - PullRequest
0 голосов
/ 17 декабря 2018

Я прочитал довольно много вопросов, похожих на этот, но на самом деле не было ответа на эту проблему в темах, которые я прочитал.У меня есть простой вызов Ajax для серверного скрипта, чтобы сравнить две строки.Но, случайным образом это происходит, но в других случаях сервер отвечает jquery.min.js:4 POST https://www.example.com/otpcheck net::ERR_EMPTY_RESPONSE и что-то похожее на: XHR failed loading: POST

Откуда на самом деле происходит эта ошибка, так как данные на самом деле были отправлены, как я могу подтвердить в отладчике Chrome,Вот мой скрипт вызова Ajax:

// --------------- START REGISTRATION OTP CHECK -----------------------------
$(document).ready(function() {

// Hide error label
	$("#error2").hide();
	$("#loader2").hide();
	 

	// process the form
	$('#RegistrationOTPForm').submit(function(event) {

		$("#error2").hide(); // hide errors when form submitted

		// get the form data
		// there are many ways to get this data using jQuery (you can use the class or id also)
		var formData = {
			'OTP' 				: $('input[name=OTP]').val()
		};

		// process the form
		$.ajax({
			type 		: 'POST', // define the type of HTTP verb we want to use (POST for our form)
			url 		: './OTPcheck.php', // the url where we want to POST
			data 		: formData, // our data object
			dataType 	: 'json', // what type of data do we expect back from the server
			beforeSend: function()
            {
                $("#error2").hide();
				$("#error3").hide();
				$("#loader").hide();
				$("#loader2").hide();
				$("input[type=submit]").attr("disabled", "disabled");
				$("input[type=text]").attr("disabled", "disabled");
				$("input[type=password]").attr("disabled", "disabled");
				$("select").attr("disabled", "disabled");
            },
			encode 		: true
		})
			// using the done promise callback
			.done(function(data) {

				// log data to the console so we can see
				console.log(data); 

				// here we will handle errors and validation messages
				if ( ! data.success) {
					
						// handle errors for  ---------------
	
	if (data.errors.OTP) {
		$("#OTP").val("");
		 $("input[type=submit]").removeAttr("disabled");
		 $("input[type=text]").removeAttr("disabled");
		 $("input[type=password]").removeAttr("disabled");
		 $("select").removeAttr("disabled");
		$("#error2").show(function(){
		$('#error2').html('' + data.errors.OTP + ''); // add the actual error message to the error label
		});

	}
				} else {

					// ALL GOOD! just show the success message!
					$("input[type=password]").attr("disabled", "disabled");
					$("input[type=submit]").attr("disabled", "disabled");
					$("input[type=text]").attr("disabled", "disabled");
					$("select").attr("disabled", "disabled");
                    window.location.href= "./RecoverUserIDSecurityInformation";
				}
			})

			// using the fail promise callback
			.fail(function(data) {

				// show any errors
				// best to remove for production
				console.log(data);
			});

		// stop the form from submitting the normal way and refreshing the page
		event.preventDefault();
	});

});

// --------------- END REGISTRATION OTP CHECK -----------------------------

А вот сценарий на стороне сервера, который он вызывает: OTPcheck.php

<?php
if(!isset($_SESSION)) 
    { 
        session_start(); 
    } 
//-- data and error arrays	
$errors         = array();  	// array to hold validation errors
$data 			= array(); 		// array to pass back data
// --------------------

$Real_OTP = "123456";
/**********************************************************************/

// -------- Function to test input
function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}
// -------------------------

if ( !empty($_POST)) {
	
		// Variables from post
	$GLOBALS['OTP'] = test_input($_POST["OTP"]); 
/*************************************************************/
// Checks for empty Amount
  if (empty($OTP)) {
   $errors['OTP'] = 'You have entered an invalid code';
  } else if (strcmp($OTP, $Real_OTP) !== 0){ //--Comparing both strings if they are not same while maintaning case sensitivity like Cow should be Cow so if == 0, strings are same. If !==0 strings are not equal
	  $errors['OTP'] = 'You have entered an invalid code';
  } else {
	  $_SESSION['RecoverUserIDProgress'] = "Progress";
	  
	  $data['success'] = true;	  
  } 
   
  
 /*************************************************************/  


/************************************************************/

	if ( ! empty($errors)) {
		// if there are items in our errors array, return those errors
		$data['success'] = false;
		$data['errors']  = $errors;
	} else {
	
	$data['success'] = true;

		// if there are no errors process our form, then return a message
		
		
	}
	
} else {
	$data['success'] = false;
		$data['errors']  = $errors;
}

// return all our data to an AJAX call
	echo json_encode($data);
?>

Из приведенного выше вы видите, что это простой скрипт сравнения строк.У меня есть значение по умолчанию 123456, и мне просто нужно сравнить, совпадает ли значение поля, отправленного из формы HTML, со значением по умолчанию, которое я установил в серверном скрипте.Почему тогда у меня есть это net::ERR_EMPTY_RESPONSE или XHR failed loading: POST

Если кто-то может указать мне правильный путь, я был бы очень благодарен.Я уже теряю сон из-за этого.Спасибо за все ваши ответы и поддержку заранее.

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