How to make data loading via ajax? I need to start an html document with an ajax request to retrieve several data and write them to the appropriate id.

AJAX request: ( see comments )

$(document).ready(function() { $.ajax({ type: POST, url: 'php/getData.php', data: //что передавать здесь? success: function(data) { // и как правильно получить здесь? $("#userName").text(data[name]); $("#userAge").text(data[age]); } }) return false; }); 

How to send $ name and $ age data from getData.php to ajax request

 <?php require "db.php"; if (isset($_SESSION['logged_user'])) { //Получение данных $name = $_SESSION['logged_user']->name; $age = $_SESSION['logged_user']->age; } else{ header('location ../login.php'); } ?> 

Just in case authorization:

 <?php require "db.php"; $data = $_POST; $user = R::findOne('users', 'login = ?', array($data['login'])); if ($user) { if (password_verify($data['password'], $user->password)) { $_SESSION['logged_user'] = $user; } else { echo ('Неверный пароль'); } } ?> 

    1 answer 1

    Give json for example

     <?php require "db.php"; header('Content-Type: application/json'); $get_result = ['auth' => false]; if (isset($_SESSION['logged_user'])) { //Получение данных $name = $_SESSION['logged_user']->name; $age = $_SESSION['logged_user']->age; $get_result = ['name' => $name, 'age' => $age, 'auth' => true]; } echo json_encode($get_result); ?> 

    And take accordingly

     $(document).ready(function() { $.ajax({ type: GET, dataType: 'json', url: 'php/getData.php', success: function(data) { // и как правильно получить здесь? if (data.auth) { $("#userName").text(data.name); $("#userAge").text(data.age); } else { window.location = '/login.php'; } } }) return false; }); 

    There is also a short recording option.

     $(document).ready(function() { $.getJSON('php/getData.php', function(data) { if (data.auth) { $("#userName").text(data.name); $("#userAge").text(data.age); } else { window.location = '/login.php'; } }); }); 
    • Thank you so much, it was the “short version of the recording” that worked - Kirill Mironov
    • one
      @ Kirill Mironov I think because it was necessary to make a check on the object in success and if not the object then execute toJSON, but this is not exact =) - Walfter