When I set the session in a file called signin.php:
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'array.php',
type: 'post',
data: {'user': $user}
});
";
In another file (index.php), I want to get:
<?php
session_start();
echo "log in as <span id=\"user\"></span><br/>";
$user = $_POST['user']
echo "
<script>
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
</script>
";
?>
I know I completely messed up with the code. What I want is that when the session is set in the signin.php file, I want $user in the content in "log in as $user" automatically updated without refresh the page, any help will be greatly appreciated!
First, work on diligently formatting your code more effectively. That code you posted was all over the place. This is a bad practice to get in and leads to errors, bugs, and other effects which can be difficult find due to the formatting.
If I follow what you're doing, when someone logs in and then hits the index.php page, you want to be able to load a user's information from another file that will give back the user data asynchronously?
signin.php
Your code is confusing in what it appears to be doing; you simply have not told us enough both in code and explanation to understand what the workflow entails.
For instance, in signin.php, you're echoing a <script> tag that does an $.ajax() request, but who/what get's this code? Is this part of the signin.php content, if the user successfully logs in? Does this mean the signin.php will load the page to use the $.ajax() here, or is that meant to run from the $.ajax() on success?
If it's the latter, you need to return regular Javascript with no markup (like a <script> tag wrapped around it) and use dataType: 'script' in the options.
Also, I would at least use a more descriptive word than array.php; if you're getting user data from it, name that file something like userdata.php.
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
dataType: 'script',
data: 'json=' + jQuery.serialize({user: '$user'})
});
";
Then in userdata.php, you can access it with $_POST['json'].
index.php
This honestly makes no sense:
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
);
Why is the setInterval() in an anonymous function that's run while setting $.text()? This is one of those What? moments, where I'm not even sure what you're trying to accomplish.
Before that though, you have:
$user = $_POST['user'] <<< Note here, you need a ; at the end
Why is this a $_POST? Does the signin.php use $_POST to log a user in? Here, I believe you want $_SESSION (I think, hope, ??), since that's where you stored the username when the user logged in using signin.php.
This is my best guess as to what you're trying to do (assuming you're returning JSON-formatted data):
<?php
session_start();
$user = $_SESSION['user'];
echo "log in as <span id=\"user\"></span><br/>";
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
data: 'json=' + jQuery.serialize({user:'$user'}),
dataType: 'json',
success: function(data){
$('#user').text(data.fullname);
}
});
</script>
";
?>
Try the following:
<?php
$user = 'john';
$_SESSION['user'] = $user;
?>
<script type="text/javascript">
$.ajax({
url: 'array.php',
type: 'post',
data: { 'user': <? echo json_encode($user) ?> }
});
</script>
Related
I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.
good afternoon from gmt+8 timezone.
I had built a login/system , now I want to implement a function that will click out users , so i make a status column in the db ,
2 types of values , lock => lock , active => not lock.
I can use crud method to update the status and output in a table. surely i cam lock the user , and status change to lock, that is working fine, but the problem is the locked user still has access the to system , since the session still valid , she/he has to close the browser or their session is terminated.
on the login page I check if user is lock then can login.
since the user still has access when the session still valid , I want to input ajax call the server to check the status on setInterval.
on backend php: check if user is lock , terminate the session , give alerts box and redirect.
but the issue now is my code is not working, here are my ajax call , if I un-comment //console.log('success');, success will be kept in console.log , meaning the call is success.
<script>
function getUserStatus(){
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
});
}
setInterval(function(){
getUserStatus();
},3000);
</script>
on my ajax.php page , I make sure connection to db is working,
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$admin_username = check_input($_POST['username']);
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clicked out');window.location.href='../index.php';</script>";
}
}
function to check user is lock
function isLocked($username){
global $connection ;
$query = "SELECT status FROM table where name = '$username' ";
$result = mysqli_query($connection,$query);
confirm($result);
while( $row = fetch_array($result)){
if($row['status'] == 'locked' ){
return true;
}else{
return false;
}
}
}
if i directly access ajax.php with the log user , below action is working .
if( isLocked($admin_username) ){
session_destroy();
echo "<script>window.alert('you had been clickedout');window.location.href='../index.php';</script>"; }
not sure what is wrong with my codes and how to fix it ?
any assistance/suggestion would be highly appreciated .
your ajax.php echos something, that may be data, a json or in your case a js script.
The ajax calls ajax/ajax.php, if the http request succeeds it enters
success:
function(response){
//console.log('success');
}
so the variable response holds the output of that call to ajax/ajax.php. if you use
$.ajax({
type: "POST",
url: 'ajax/ajax.php',
dataType: "script",
data: {username: '<?php echo $_SESSION['admin_username'] ;?>' },
success: function(response){
//console.log('success');
}
the value of "response" will be executed if it is a working script.(without tags)
further information you can find here:
http://api.jquery.com/jQuery.ajax/
without dataType: "script",in the call you could do something like that:
function(response){
//console.log('success');
$('#somediv').html(response);
}
that will insert the result in a div, if it is a well formated js script, it will be executed.
I have the following extremely simple PHP tester:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.2/jquery.min.js"></script>
<button id="button">send request</button>
<script>
$("#button").click(function(){
$.ajax({
type: "POST",
url: "ajaxTest.php",
data: {userresponse: "hi"},
success: function(data){
alert(data)
analyse()
}
})
})
var analyse = function () {
<?php
if(isset($_POST["userresponse"])){
$variable = $_POST["userresponse"];
switch($variable){
case "hi":
echo 'alert("' . $variable . '")';
break;
default:
echo 'alert("LOGIC")';
}
}
?>
}
</script>
What's supposed to happen is that when I click the button, it sends the data userresponse: "hi" to the server, and then PHP receives it and alerts the value (i.e. "hi")
However, despite the fact that the file paths are correct, the AJAX send is OK in XHR, the PHP does not receive the value of the data, and the alert(data) returns the entire HTML document.
What is going on and how do I fix this?
Remove analyze() and put your php code in external file called ajaxTest.php, your code works perfect just remove your php code fron analyze and request for external this is bad practice having both in same file(header problems).
Proof:
I am currently migrating an already built web application to MVC, and I'm figuring out that I'm too newbie to do some kind of changes. There are some ajax calls that are freaking me out. I'll try to be as clear as possible, but due to my inexperience I'm not sure if I won't let some important information by the way.
The point is in the old application, things go this way:
In the php code:
if ($action_user == 'show_alerts') {
$list = array();
$query = "SELECT alert_type FROM alert_contact WHERE NOT
deleted AND user_email=" . typeFormat($email);
$result = mysqli_query($db, $query) or die('Error in query "'.$query . '": ' . mysqli_error($db));
while ($db_field = mysqli_fetch_assoc($result)) {
$list[] = $db_field['alert_type'];
}
echo json_encode($list);
In the jquery code:
$.ajax({
type: 'POST',
url: 'userpost.php',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Here comes my problem, and since I don't have an userpost.php file anymore, I have to send it to the index.php and call my users component by a get petition, which I don't like, but I coudn't find another way to do it. And, what is even worse, I don't know at all how ajax is getting the variables that it needs. It must be a pretty basic mistake, but I recognize my skills at this point are't so good. That's what I'm doing in my version:
In the php code:
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
In the jquery code:
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json',
success: function(data) {
alert ('gotcha');
$.each(alertsarray, function(index, value) {
if ($.inArray(value, data) === -1) {
$("#sub" + value).prop("checked", false);
$('#alert' + value).removeClass("list_alert_sub");
}
else {
$("#sub" + value).prop("checked", true);
$('#alert' + value).addClass("list_alert_sub");
}
});
},
error: function(data) {
alert("¡Error (ajax)!");
}
});
Any help would be appreciated, and if there's some more information I've missed, please let me know. Thanks in advance.
UPDATE:
I've been making some progress but don't seem to find a real solution. Now I know that the url has to be the controller, so I'm using 'components/userpost/controller.php' as it, and it reaches the ajax call, cause the success alert is showing up. The problem is the MVC way, because I send ajax to the controller, but since I don't have a reload in the page, all the includes are failing so they are obviously not being loaded, and I'm getting errors like this:
PHP Warning: include(components/userpost/model.php): failed to open
stream: No such file or directory in
/var/www/html/viewer_mvc/components/userpost/controller.php on line 3,
referer: http://localhost/viewer_mvc/index.php
Really hope you guys can show me where am I failing, and if there's a special way to do these thing in MVC.
For the JQuery call it makes a POST request to index.php?option=users with JSON data. The form with the ID userForm is serialized using the Jquery serialize method.
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Now for your PHP sample
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
This code will be looking for variables that probably don't exist anymore if it is a different file i.e. is there an $action_user variable?
To start reimplementing it you will need to add the logic so that it checks the POST variable if your not using the framework code. So if you have a form element with the name 'name' then that will be available in your PHP script POST variable
$_POST['name']
[How to call a PHP function in MVC using AJAX]
$.ajax({
type: 'POST',
url: 'save-user.php',
data: { fname: "manish", email: "manishkp#com", role:"admin"},
success: function(data) {
console.log(data);
if(data == 'error')
{
$('#Register_error').text('Must Be filled...');
$('#Register_error').show();
}
else {
$('#Register_error').hide();
$('#Register_success').text('Successfully submit');
$('#Register_success').show();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$fname = $_POST['fname'];
$email = $_POST['email'];
$role = $_POST['role'];
if(!empty($fname) && !empty($email) && !empty($role))
{
#MYSQL CONNECTION QUERY #
echo"success";
}
else{
echo "error";
}
?>
The following script sends data with ajax for login
I want to format the data returned by using, in essence, a session variable ($ _SESSION)
I can do it
$("#login").click(function(){
username=$("#user_name").val();
password=$("#password").val();
$.ajax({
type: "POST",
url: "inc/login.inc.php",
data: "username="+username+"&password="+password,
success: function(msg){
if(msg!='false')
{
$("#login_form").fadeOut("normal");
$("#shadow").fadeOut();
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
//valori menù
if(tipo=='1')
{$("#admin").css('display','none')}
}
else
{
$("#add_err").html("Username o password errata");
}
},
beforeSend:function()
{
$("#add_err").html("<img hspace='84' src='img/loading.gif' alt='Loading...' width='32' height='32'>" )
}
});
return false;
});
especially this is possible, in this way would print the name of the user just logged. otherwise I would not know how to do
$("#profile").html("<\?php print(\"$_SESSION['name'].\" <a href='inc\/logout.inc.php' id='logout'>Logout k2<\/a>\");\?>");
You can't insert PHP code after the script has already been processed.
Either pull it in via ajax, or include the actual PHP output into your javascript.
ie, in page.php
<script>
var sessionName = '<?php echo $_SESSION['name']; ?>';
</script>
then when you need it later
$("#profile").html(sessionName + " Logout k2");
JavaScript is client-side, it simply can't execute your php code.
You have to return something (eg. the username) in the php file you use in your ajax request and use that in your JS.
See the jQuery ajax docs for examples.
You'll need to serve the php code:
$("#profile").load("inc/login-header.inc.php");
login-header.inc.php
<?php
print($_SESSION['name'] . " <a href='inc/logout.inc.php' id='logout'>Logout k2</a>");
?>
The easiest way to send information back from the php script to the javascript, is by using the msg variable in
success: function(msg){
If you just want to send back one string, you just echo that one string in your php file and you will have its value in msg. If there are multiple variables you want to send back, you can package the result in a json object.
So assuming that everything you want to send back is contained in the php array named $output, you do a echo json_encode($output); at the end of your php script to get the whole thing in msg.
that won't work, as the PHP code is never processed.
In login.inc.php try something like this
<?php
if (!loginOK()){
echo "{login:false}";
} else {
echo "{login:true, name:'".$_SESSION['name']."'}";
}
and then on the client
success: function(msg){
if (msg.login){
// stuff
} else {
$("#profile").html(msg.name + $('<a>').attr('href', 'logout.php').html('logout'));
}
}