tommie20 Posted November 18, 2011 Share Posted November 18, 2011 Hi guys, I have a login page where the user can login, the input is being send to php where it checks if the input is in the mysql database. If so i would like to send back the username that is typed in to autofill it in a form completed later on. In code: $(document).ready(function(){ $("#username").focus(); $("#submit").click(function(){ $.ajax({ url: "http://serverip/session.php", cache: false, type: "POST", data:{ username: $("#username").val(), password: $("#password").val() }, success: function(data){ if (data == '1') window.location.replace("home.html"); else{ alert("error"); } } }); }); }); PHP: <?php session_start(); if(!isset($_SESSION['username'])){ if(isset($_POST['username'])){ $db = new mysqli("localhost", "root", "", "gegevens"); $stmt = $db->prepare("SELECT username FROM members WHERE username = ? AND password = ?"); $stmt->bind_param('ss', htmlentities($_POST['username'], ENT_QUOTES), htmlentities($_POST['password'], ENT_QUOTES)); $stmt->execute(); $stmt->store_result(); if($stmt->num_rows() == 1){ $stmt->bind_result($username); $stmt->fetch(); $_SESSION['username'] = $username; echo "1"; exit; } }else{ echo "0"; } } ?> I read in other posts that i could use datatype json to send multiple variables back. But i couldn't get it to work properly. I would like to send back the username typed in but the '1' has to be send back too. Thanks, Tom Quote Link to comment https://forums.phpfreaks.com/topic/251374-sending-back-variable-to-ajax/ Share on other sites More sharing options...
trq Posted November 18, 2011 Share Posted November 18, 2011 I read in other posts that i could use datatype json to send multiple variables back. But i couldn't get it to work properly. Why not post the code that isn't working then? It's really as simple as: echo json_encode(array('username' => $username, 'status' => true)); In your php, then something like.... success: function(data) { if (data.status == 1) { console.log('You have logged in as ' + data.username); } else { console.log('Login failed'); } } in you Javascript. Quote Link to comment https://forums.phpfreaks.com/topic/251374-sending-back-variable-to-ajax/#findComment-1289293 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.