M
M
Mors Clamor2018-10-02 23:35:09
PHP
Mors Clamor, 2018-10-02 23:35:09

Ajax request not working, what should I do?

Actually the problem is that I began to re-pick my site so that everything interacts using json. And everything worked out for me until I got to the point where I needed to find out the user's login. There are files in the scripts folder:
get_user.php - to get the user object

<?php
  include "connect.php";
    //Получаем все поля пользователя с таким логином
    session_start();
    $id=$_SESSION["id"];
  $result = $mysqli->query("SELECT * FROM users WHERE id='$id'");
    //Преобразуем в массив
  $result = mysqli_fetch_assoc($result);
  echo json_encode($result);

?>

is_auth.php - checks if the current user is authorized
include "functions.php";
$response=array()
session_start();
if (isAuth()) {
  $response["response"]="true";
  echo json_encode($response);
} else {
  $response["response"]="false";
  echo json_encode($response);
}


And in main.js in the same function folder
function isAuth() {
  $.ajax({
    type:"post",
    url:"scripts/is_auth.php",
    success:function(data,text) {
      var res=JSON.parse(data);
      alert(res.response);
      if (res.response=="true") {
      return true;	
      } else {
        return false;
      }
      
    }
  })
}

function getUser() {
  $.ajax({
    type:"post",
    url:"scripts/get_user.php",
    success:function(data,text) {
      var response=JSON.parse(data);
      alert(response);
      return response;
    }
  })
}


When trying to debug by alert-s, the response from the server gave either undefined or null. Help, what am I doing wrong?

PS funtions.php 100 times tested - works fine

Answer the question

In order to leave comments, you need to log in

2 answer(s)
B
Bulat, 2018-10-03
@KZ_LIFE

In order for Ajax requests to work with sessions, you need to include xhrFields: {
withCredentials: true
} in the request parameters

M
Mors Clamor, 2018-10-03
@66demon666

But with getJSON I liked it, thank you)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question