<?php if (isset($_POST['login'],$_POST['password'])){ $a= $db->getRow('select Id_Users,Fam_Users,Name_Users,Otch_Users from Users WHERE Logon_Users=?s AND Password_Users=?s',$_POST['login'],$_POST['password']); } if (empty($a)){ $arg["error"]="Пара логин пароль не верны"; } else { $arg["error"]="0"; $_SESSION['Id_Users']=$a['Id_Users']; $_SESSION['Fam_Users']=$a['Fam_Users']; $_SESSION['Name_Users']=$a['Name_Users']; $_SESSION['Otch_Users']=$a['Otch_Users']; } echo json_encode($arg,JSON_UNESCAPED_UNICODE); 

So I make a request:

 <script language="JavaScript"> var send = document.getElementById("avtoriz"); var xhr = new XMLHttpRequest(); var resp = document.getElementById("resp"); var form = new FormData(); send.onclick= function() { form.append("login",document.getElementById("login").value); form.append("password",document.getElementById("password").value); xhr.open("post","user_iden/autorization",true); xhr.send(form); resp.innerHTML=xhr.status + ': ' + xhr.statusText; }; xhr.onreadystatechange= function() { if (xhr.status != 200) { show(resp); resp.innerHTML=xhr.status + ': ' + xhr.statusText } else { var respons = JSON.parse(xhr.responseText, function(key, value) { if (key == 'error') return new String(value); return value; }); if (respons.error=='0') { location.reload(); } else { resp.innerHTML=respons.error; show(resp); } } }; </script> 

In principle, everything works as it should, but I do not understand why the error gives

  • Well, did you see what comes back from the server? - u_mulder
  • @u_mulder Yes, for example, here: {"error": "A couple of login passwords are not correct"} - Ghost
  • No code is needed here, JSON is needed. What you gave ( {"error":"Пара логин пароль не верны"} ) quite correctly soars. And check for errors here: jsonlint.com - user207618

1 answer 1

I understood where the legs grow from this error, and so xhr.status returns 200 before loading the request body and it turns out JSON.parse 2 times, when the request body is empty and when the request body is loaded, this is the correct piece:

 <script language="JavaScript"> var send = document.getElementById("avtoriz"); var xhr = new XMLHttpRequest(); var resp = document.getElementById("resp"); var form = new FormData(); send.onclick= function() { form.append("login",document.getElementById("login").value); form.append("password",document.getElementById("password").value); xhr.open("post","user_iden/autorization",true); xhr.send(form); }; xhr.onreadystatechange= function() { if (xhr.readyState==4){ if (xhr.status != 200) { show(resp); resp.innerHTML=xhr.status + ': ' + xhr.statusText } else { var respons = JSON.parse(xhr.responseText, function(key, value) { if (key == 'error') return new String(value); return value; }); if (respons.error=="Нет ошибки") { location.reload(); } else { resp.innerHTML=respons.error; show(resp); } } } }; </script>