I have never done combining ajax and session before. So far i have done something like this.
var sessionvar;
$.ajaxSetup({cache: false})
$.get('test.php' ,function (data) {
sessionvar = data;
alert(sessionvar);
var checkedCbs = $('sessionvar:checked');
if (checkedCbs.length === 4) {
alert("You can only select 3 books");
this.checked = false;
}
});
I want to try set the limitations based on session. Inside the test.php i have something like this
<?php
session_start();
if(isset($_POST['sBorrow']) && $_POST['action']){
if(isset($_SESSION['sBorrow']) && is_array($_SESSION['sBorrow'])){
$sborrow = $_POST['sBorrow'];
$set = $_SESSION['sBorrow'];
}
else{
$set = array();
}
if($_POST['action'] == "SET"){
array_push($set, $_POST['sBorrow']);
$_SESSION['sBorrow'] = $set;
}
else if($_POST['action'] == "UNSET"){
$unset = $_SESSION['sBorrow'];
if(($key = array_search($_POST['sBorrow'], $unset)) !== false) {
unset($unset[$key]);
$_SESSION['sBorrow'] = $unset;
}
}
}
//session_destroy();
if(isset($_SESSION['sBorrow'])){
$countses = count($_SESSION['sBorrow']);
echo $countses;
}
// nothing requested, so return all values
print json_encode($_SESSION);
?>
Inside these i have create some array to store something. Never mind that, i just want to know how to run an ajax with session. Im not sure if my codes is right for implementing that.
Related
I tried to run the code below but it doesn't work, and I tried everything I remember and couldn't get to work.
AJAX Call
var status = $(this).prop("checked");
var room_id = id;
$.post('maintenanceControl.php', {action: status, id: room_id});
PHP Script
<?php
if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
$action = $_POST['action'];
$id = $_POST['id'];
if ($action) {
return manageMaintenance($id, true);
} else {
return manageMaintenance($id, false);
}
}
function manageMaintenance($room_id, $status)
{
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString, true);
foreach ($data['rooms'] as $key => $entry) {
if ($key == $room_id) {
$data[$key]['maintenance'] = $status;
}
}
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
return true;
}
At first I thought it was a malfunction but the example below worked just fine
$.post( "test.php", function( data ) {
alert(data);
});
PHP
<?php
echo "test";
In order to get data back into the Javascript ajax call, you need the php script to echo something.
Return values in php do not find their way back into the Ajax call.
Often, php scripts echo a value, either a single value or if you want the get more complex data from php back into the Ajax call, you can json encode several values and echo that.
You have to echo/print something in php script to send response to ajax request. You have to do something like below.
$response=false;
if (isset($_POST['action']) && !empty($_POST['action']) && isset($_POST['id']) && !empty($_POST['id'])) {
$action = $_POST['action'];
$id = $_POST['id'];
if ($action) {
$response=manageMaintenance($id, true);
} else {
$response=manageMaintenance($id, false);
}
}
function manageMaintenance($room_id, $status)
{
$jsonString = file_get_contents('status.json');
$data = json_decode($jsonString, true);
foreach ($data['rooms'] as $key => $entry) {
if ($key == $room_id) {
$data[$key]['maintenance'] = $status;
}
}
$newJsonString = json_encode($data);
file_put_contents('status.json', $newJsonString);
return true;
}
echo $response==true? "OK" : "FAILED";
I try to unset my variabele when the input is not "all" in a selection of radioboxes. The if statemtent works and does the job perfectly, but the else doesn't work. Any ideas?
$profile = $_POST["profile"];
if ($profile != 'all') {
$conditions["profile"] = $profile;
} else {
unset($conditions["profile"]);
}
I think your $_POST variable may not be set. Try something like this:
either:
$profile = isset($_POST["profile"]) ? $_POST["profile"] : 'all';
or within the else block:
} else {
if(isset($conditions["profile"])) unset($conditions["profile"]);
}
I want to check the username availability while users register. I am working on the front end. The backend code was given to me.
These are the php code in signup.php
if (isset($_GET['chkusername']))
JSON_username_avail($_GET['chkusername']);
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username, $ret));
die();
}
function validate_username($username, & $retval_arr) {
if ($username == NULL)
$retval_arr['E_UserName'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['E_UserName'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['E_UserName'] = "USERNAME_EXISTS";
return $retval_arr;
}
function username_validation($user) {
$username = str_split($user);
foreach($username as $i) {
$i = ord($i);
if ($i >= 48 and $i <= 57)
continue;
if ($i >= 65 and $i <= 90)
continue;
if ($i >= 97 and $i <= 122)
continue;
return FALSE;
}
return TRUE;
}
function data_not_exists($table, $field, $data, $CSense = FALSE) {
$conn = connect_db();
$data = filter_var($data, FILTER_SANITIZE_STRING);
if ($CSense == TRUE)
$sql = "SELECT * FROM ".$table.
" WHERE ".$field.
"='".$data.
"'";
else
$sql = "SELECT * FROM ".$table.
" WHERE upper(".$field.
")='".$data.
"'";
$result = mysqli_query($conn, $sql);
switch ($result - > num_rows) {
case 0:
return TRUE;
break;
case 1:
return FALSE;
break;
default:
die("500 Internal Server Error: 122");
} //switch
}
Now I dont know that much of php. I created a javascript function to send the username to the signup.php page for validation.
Here is my function
function submit_form() {
var u = document.getElementById("username").value;
$.post("signup.php", {
"chkusername": u
},
function (data) {
var x = data; //here i dont know how to get the return string. Whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS.
}, "json");
}
here i am getting the value of x as [object Object].
But i need to store the return message in variable x. I want to know whether it is NULL_USERNAME OR INVALID_USERNAME OR USERNAME_EXISTS. Kindly help me with that.
The username is POSTed but in the PHP you try to access it with $_GET, change to:
if (isset($_POST['chkusername']))
JSON_username_avail($_POST['chkusername']);
Also your validation logic doesn't look right, what if the username is valid and available? I would add an else clause and set a success variable:
function JSON_username_avail($username) {
$ret = array();
print json_encode(validate_username($username));
die();
}
function validate_username($username) {
$retval_arr = array('success' => false, 'message' => '');
if ($username == NULL)
$retval_arr['message'] = "NULL_USERNAME";
else if (!username_validation($username))
$retval_arr['message'] = "INVALID_USERNAME";
else if (!data_not_exists("user", "username", $username, TRUE))
$retval_arr['msessage'] = "USERNAME_EXISTS";
else
$retval_arr['success'] = true;
return $retval_arr;
}
and the ajax:
if(!data.success){
console.log(data.message);
} else {
// valid and available
}
Try,
function(data){
var x = data.E_UserName;
}, "json");
also change your request to GET as per MrCode's answer
function submit_form() {
var u = document.getElementById("username").value;
$.get("signup.php", {
"chkusername": u
},
function (data) {
var x = data.E_UserName
}, "json");
}
I have this script that sends via $.post some information
$("#clickme").click(function(e){
var selected = $(".img input:checked").map(function(i,el){return el.name;}).get();
var prelucrare = selected.join(";")
$.post('test.php', {
rezultat: prelucrare,
},
function(data){
$('#rez').html(data)
});
});`
And the PHP file that handles the $.post
<?php
require_once '../config.php';
If(isSet($_POST['rezultat'])) {
$d = explode(';', $_POST['rezultat']);
foreach($d as $numar_inregistrare){
$SQL = "DELETE FROM galerie_foto WHERE numar_inregistrare = '$numar_inregistrare'";
$rezultat = mysql_query($SQL) or die(mysql_error());
return true;
}
} else {
exit;
}
?>
I have two questions:
1. How can I make the js script do a thing if the return value is true and an other thing if the return value is false ? Something like this ?
$.post('test.php', {
rezultat: prelucrare,
success: function(msg){
valid = (msg == 1) ? true : false;
if(!valid) {
$("#valid_input").html("Please enter valid info");
} else {
$("#valid_input").html("");
}
}
)};
My other question is about the returning result, because I'm in a loop if there are 3 things in the array the result will be truetruetrue instead of just one true, what can I make to get just one true ?
You can use "return" only in functions and methods. To print "true" or "false" once, in the foreach loop you can break out or in your case just exit with 'false' if there's an error. You'll have something like this:
foreach($d as $numar_inregistrare){
$SQL = "DELETE FROM galerie_foto WHERE numar_inregistrare = '$numar_inregistrare'";
$rezultat = mysql_query($SQL);
if (!$rezultat) {
exit('false');
}
}
echo 'true';
....
Using PHP and jQuery Ajax to build a basic log in system.
What I want to do is submit sections of a form via ajax and return an array. I'm not quite sure if I've got this one right.
Here is the PHP
if($access_function == 'access_login_1'){
$email = $_POST['access_email'];
$pwd = $_POST['access_pwd'];
if(!$email || !$pwd){
$error = 'Empty';
}
else {
$user = get_user($email);
if($user && $user['pwd'] == $pwd){
if($user['status'] == 1){
$action = 1;
}
else {
$order = 'Unauthorised';
}
}
else {
$error = 'invalid';
}
}
return array('action'=>$action,'error'=>$error,'order'=>$order);
}
The get_user function is like this::
function get_user($email){
global $cnx;
$q = $cnx->prepare("SELECT email FROM `users` WHERE email = :email");
$q->execute(array(':email' => $email));
return $q->fetch();
}
Now the jQuery is the real struggle. What I want is to submit the serialised values to this php. If the script returns an action of 1, I want to perform another script, I want $error to go into a div called error and order into a div called $order
This hasn't worked:
function sendvars(container,linkrul,perform){
var vars = 'access=1';
$(container).find('input').each(function(){
vars += '&' + $(this).attr('name') + '=' + $(this).val();
});
$.ajax({type:'POST',url:linkrul,data:vars,success:function(results){
if(results == 1){ }
else { $(container).find('.orders').html(results).slideDown(300); }
}
});
}
-- Hashing is off for not just while we test everything.
I would do it returning json encoded arrays:
if($access_function == 'access_login_1'){
$email = $_POST['access_email'];
$pwd = $_POST['access_pwd'];
if(!$email || !$pwd){
$resp = array(
'action' => $someValue,
'order' => $someValue,
'error' => 'No Email or password provided'
);
}
else {
$user = get_user($email);
if($user && $user['pwd'] == $pwd){
if($user['status'] == 1){
$resp = array(
'action' => 1,
'order' => $someValue,
'error' => 'No Error'
);
}
else{
$resp = array(
'action' => $someValue,
'order' => 'Unauthorised',
'error' => 'Order Error'
);
}
}
else {
$resp = array(
'action' => $someValue,
'order' => 'Unauthorised',
'error' => 'Invalid'
);
}
}
echo json_encode($resp);
}
And in js:
function sendvars(container,linkrul,perform){
var vars = 'access=1';
$(container).find('input').each(function(){
vars += '&' + $(this).attr('name') + '=' + $(this).val();
});
$.ajax({type:'POST',url:linkrul,data:vars,dataType:'JSON',success:function(results){
if(results.action == 1){
//do something
}else if(results.action == someOtherValue){
$(container).find('.orders').html(results.order).slideDown(300);
}else{
alert(results.error); //Or put the error in some div
}
//any other code or if/else statement
});
}
You need to think more carefully about what data is being sent from the PHP to the AJAX callback:
Remember that a PHP script cannot "return" anything, it simply "displays" it. So return array('action'=>$action,'error'=>$error,'order'=>$order); will not produce any output that the Javascript can read unless you then serialize it (turn it into a string and output it) in some way, such as XML or JSON (using json_encode()). You can test that the script is outputting something useful by looking at it directly in your browser, or using debug tools such as Firebug.
jQuery needs to know what encoding you've output your data in (see documentation on the dataType parameter). If it's XML, it will pass the whole XML document to your callback function, so you would need to use functions like .find and .each to inspect it. Probably the easiest is for your PHP to use header('Content-type: application/json'); (which tells jQuery you're using JSON) and echo some data using json_encode, so that your Javascript callback gets a simple Javascript object to work with.
Your current Javascript assumes that the result of the AJAX call is either an integer (result == 1) or a blob of HTML .html(results). A better approach would be to pass back the whole result structure shown in your PHP code (i.e. echo json_encode(array('action'=>$action,'error'=>$error,'order'=>$order));). Then you can check and act on each part of the structure separately (e.g. response.action == 1, .html(response.order)), and your code becomes more readable and more flexible for future situations.
Finally, jQuery has some built-in functions which can do some more of your work for you here: check out $.post as a short-hand for the AJAX call, and .serialize() (or its cousin .serializeArray()) for reading out the current values of form elements in a form you can send to the AJAX callback.
(Incidentally, I'm sure you'd have spotted this, but I presume linkrul should be linkurl)
This is also one option.
HTML
<input type='text' class='email' />
<input type='password' class='pass' />
PHP - checkLogin.php
<?php
$action = 0;
$order = 0;
$error = 0;
if(isset($_POST['email'], $_POST['pass'])) {
if(!empty($_POST['email']) && !empty($_POST['pass'])) {
$user = get_user($email);
if($user && $user['pwd'] == $_POST['pass']){
if($user['status'] == 1){
$action = 1;
} else {
$order = 'Unauthorised';
}
} else {
$error = 'invalid';
}
} else {
$error = "Empty";
}
$array = array('action'=>$action,'error'=>$error,'order'=>$order);
echo json_encode($array);
}
Javascript
function checkLogin(){
var email = $('.email').val();
var pass = $('.pass').val();
$.post('checkLogin.php', {email:email,pass:pass}, function(response) {
var result = $.parseJSON(response);
if(response['action'] == 1) {
//authorized
} else if(response['order'] == 'Unauthorised') {
//unauthorized
} else {
//error
}
});
}