简体   繁体   中英

How can I send data with Ajax to the specified user without request from the specified user

Consider a user does the login operation successfully.Now I have a session from the specified user and it is as follows:

$_SESSION['login_user'] = $username;

I searched about this issue in internet and I understood that I should use the Ajax . I saw this link but I could not understand that which method should I use to send the data to the specified user.

The $_SESSION variable is globally available so you can just use it in the file that renders the page where you want to display the message. A request over Ajax is only necessary if you want to avoid a page reload after the user has logged in.

As an example in your view.php:

echo 'Welcome back'.$_SESSION['login_user'].'!';

You can send data (from the server) back to the client by echoing it. For example you might want to get the dateime from the server to prevent the client tampering with it:

Server (assume will return json)

$datetime = new Datetime();

$res = array(
    'date' => $datetime->format('d-m-Y'),
    'hour' => $datetime->format('H'),
    'minutes' => $datetime->format('i'),
    'seconds' => $datetime->format('s'),
);

echo json_encode($res);

Client (assume will use jquery)

$.ajax({
            url: 'url_to_the_above_file.php',
            type: 'post',
            data: { // dummy post data that can be read server-side
                action : 'some value',
            },
            dataType: 'json',
            beforeSend : function() {
                //some action BEFORE send here
            },
            success: function(data, textStatus, jqXHR){
                //here is your response from the server
                console.log(date);
                console.log(hour);
                console.log(minutes);
                console.log(seconds);
            },
            error: function(data) {
                console.log("we are in error");
                console.log(data);
            },
            complete: function() {
                //some action AFTER send here
            }
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM