Am I doing something wrong with the following code? I can't seem to get alert("success") to process when the Ci session expires. Below is my jquery and Ci code:
setInterval(function() {
jQuery.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire", function(data) {
var sessionState = jQuery.parseJSON('{"sessionExpired":"true","sessionExpired":"false"}');
if(sessionState.sessionExpired === "true") { // if session is expired run the following code
var dataString = 'true';
jQuery.ajax({ // send the expired signal to Ci so that it knows the session has expired
type: 'POST',
dataType: 'JSON',
url: '<?=base_url()?>index.php/regUserDash/extendSession',
data: {'dataString': true},
success: function(data) {
if (data.extendedSession == true) {
alert('success');
} else {
return false;
}
}
});
} else if(sessionState.sessionExpired == "false") {
return;
}
});
}, 120000); // loop through every 2 minutes
CodeIgniter Code:
public function sessionExpire() {
if ($this->session->userdata("logged") == "1") {
echo json_encode(array("sessionExpired" => false));
} elseif($this->session->userdata("logged") == "0") {
echo json_encode(array("sessionExpire" => true));
}
} public function extendSession() {
// set loggedIn session var
$this->session->set_userdata('logged', '1');
// return json to ajax call
echo json_encode(array("extendedSession" => true));
}
jQuery.parseJSON('{"sessionExpired":"true","sessionExpired":"false"}'); return first sessionExpired = true and second sessionExpired = false, which overwrite the first.
So, here is one way to do this (need test):
setInterval(function() {
jQuery.getJSON("<?=base_url()?>index.php/regUserDash/sessionExpire", function(data) {
if(data.sessionExpired == "true") { // if session is expired run the following code
// var dataString = 'true'; // Remove this
jQuery.ajax({ // send the expired signal to Ci so that it knows the session has expired
type: 'POST',
dataType: 'JSON',
url: '<?=base_url()?>index.php/regUserDash/extendSession',
data: {'dataString': true},
success: function(data) {
//if (data.extendedSession == true) {
alert('success');
//} else {
// return false;
//}
// Remove commented code, because extendSession() always return true
}
});
} else {
return 'Session not expired!';
}
});
}, 120000); // loop through every 2 minutes
And CI functions:
public function sessionExpire()
{
if ($this->session->userdata("logged") == "1") {
echo json_encode(array("sessionExpired" => false));
} elseif ($this->session->userdata("logged") == "0") {
echo json_encode(array("sessionExpired" => true));
}
}
public function extendSession()
{
// set loggedIn session var
$this->session->set_userdata('logged', '1');
// return json to ajax call
echo json_encode(array("extendedSession" => true));
}
Related
I tested status.php return value with var_dump($result) and alerted it out in check() function like this:
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
alert(data);
});
}
and it did return true or false depending on situation, but when I check if data is true or false inside of check() function it always returns false.
status.php:
<?php
function status(){
if(logged() === true) {
$result = true;
} else {
$result = false;
}
return $result;
}
status();
?>
check() function: always alerts "false" even though sometimes should be "true"
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data === true){
alert("true");
} else {
alert("false");
}
});
}
You're not sending the return value of the status() function back to PHP. Use:
echo json_encode(status());
And change the AJAX call to expect a JSON response.
function check() {
$.ajax({
url: "status.php",
dataType: 'json'
}).done(function(data) {
alert(data);
});
}
you just echo the $result like this
ajax not returning value so that we have to echo it.
<?php function status(){
if(logged() === true) {
$result = true;
} else {
$result = false;
}
echo $result; } status(); ?>
and then should be like this
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data == "true"){
alert("true");
} else {
alert("false");
}
}); }
Use
**dataType: 'json'**
function check() {
$.ajax({
url: "status.php",
dataType: 'json'
}).done(function(data) {
alert(data);
});
}
and on status.php use
echo json_encode(status());
You cannot get the response by return method in ajax. to get value "echo" whatever the result in the function , like
function status(){
if(logged() === true) {
$result = "1";
} else {
$result = "0";
}
echo $result;exit;
}
you will get the value 1 or 0 in your ajax success function
Ajax may not be returning a boolean true or false, rather a string.
So try and put true in double quotes:
if(data=="true")
You can also use the trim function on data to ensure no whitespace is present in the returned data, like so:
if($.trim(data)=="true")
Just Remove Type checking i.e '===' replace with '=='
function check() {
$.ajax({
url: "status.php"
}).done(function(data) {
if(data == true){
alert("true");
} else {
alert("false");
}
});
}
I used this system.. sendind a json with success = 0 or 1 depending on success or error, is this correct or there is a better more correct method to pass true or false to the ajax call?
if (empty($item)) {
// add to the DB
$return['success'] = 0;
return Response()->json($return);
} else {
$return['success'] = 0;
$return['message'] = "Already in Collection";
return Response()->json($return);
}
then in Ajax:
jQuery(function ($) {
$(document).ready(function () {
$("body").on("submit", ".dynamic-form", function (e) {
var form = $(this);
var span = $(form).find('input[name="span_id"]').val();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
if (data.success == 1) {
alert("success");
}
else if (data.success == 0) {
alert("error");
}
}
});
e.preventDefault();
});
});
});
I use true or false and then compare like that if (data.success).
If you want a boolean send a boolean, but it's just my opinion.
This depends only on you, you can save your success as you do or to status...
<?php
if (empty($item)) {
// add to the DB
$return['success'] = true;
} else {
$return['success'] = false;
$return['message'] = "Already in Collection";
}
return Response()->json($return);
My question is simple, I'm using AJAX and i want to redirect the user to another page if the user fill up the registration form properly, however if the user failed to match his/her password. i want to show an error message.
here is my PHP code:
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
header("Location: anotherpage.php");
exit();
}
else
{
echo 'password does not match';
}
}
}
here is my ajax:
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
$('#error').text(data);
}
});
return false;
});
The problem here is that it doesn't redirect to another page unless i refresh the page.
You can simply use javascript to redirect to the page like below:
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
echo true;
}
else
{
echo 'password does not match';
}
}
}
And for redirecting, you can use:
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data === true) {
window.location = 'Your url path here';
} else {
$('#error').text(data);
}
}
});
return false;
});
Instead of header("Location: anotherpage.php"); just do echo '1' and in your AJAX call, if data['responseText'] == '1' than just do a document.location.href = 'anotherpage.php'
JavaScript does not work with header() as it is browser-based language whereas PHP communicates directly with the Server. The best solution would probably be to return an error flag and message json_encode()'d.
If you return 0 (error) then display a message.
If you return 1 (success) redirect with JavaScript to a URL passed by php. That way you will be able to easily change the new URL should anything change in the website.
JavaScript
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
dataType: 'json',
data: frm.serialize(),
success: function (data) {
if (data.r == 0){
$('#error').text(data.m);
}
if (data.r == 1){
document.location.href = data.m;
}
}
});
return false;
});
PHP
if (isset($_POST['password']) && isset($_POST['retype_password']))
{
$password = $_POST['password'];
$retype_password = $_POST['retype_password'];
if(!empty($password) && !empty($retype_password))
{
if($password == $retype_password)
{
echo json_encode(array(
'r' => 1,
'm' => 'anotherpage.php'
));
exit();
}
else
{
echo json_encode(array(
'r' => 0,
'm' => 'Passwords do not match'
));
exit();
}
}
}
var frm = $('#frm_register');
frm.submit(function (e)
{
e.preventDefault();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
if(data) {
winlow.location = data;
}
}
});
return false;
});
In your action page just echo the link where you wanna redirect if you want
I m trying to check if a username exists or not but even if the username doesn't exists it keeps saying "Username already exists" this is my javascript code:
$.validator.addMethod("checkUsername",
function(value, element) {
var test = "";
$.ajax({
type:"GET",
url: site_url + "/ajax/checkusername/" + value,
success: function(result){
if(result=="exists")
return false;
else
return true;
}
});
},
"Username Already Exists."
);
$("#myform").validate({
rules: {
username2: {
required: true,
minlength: 6,
checkUsername:true
},
password2: {
required: true,
minlength: 6
},
email: {
required: true,
email: true
}
}
});
});
This is my controller code:
public function checkusername($username)
{
$this->load->model('user_model');
$user = $this->user_model->getUser($username);
if($user == null)
{
echo json_encode("notexists");
}
else
{
echo json_encode("exists");
}
}
Any Ideas about this how this can be solved?
Thanks in advance.
Why are you encoding the response as JSON when you're not parsing JSON with your ajax?
What happens when you simply do this?:
public function checkusername($username)
{
$this->load->model('user_model');
$user = $this->user_model->getUser($username);
if($user == null)
{
echo "notexists";
}
else
{
echo "exists";
}
}
EDIT:
$.validator.addMethod("checkUsername",
function(value, element) {
var result = false;
$.ajax({
type:"GET",
async: false,
url: site_url + "/ajax/checkusername/" + value,
success: function(msg) {
result = (msg == "exists") ? false : true;
}
});
return result;
},
"Username Already Exists."
);
$.ajax read a string. Cause you do echo json_encode this string is json.
You can use $.getJSON in stead of $.ajax
$.getJSON( site_url + "/ajax/checkusername/" + value, function( json ) {
if(json=="notexists"){alert('Not exists')}
});
or add $.parseJSON to your original code:
if($.parseJSON(result)=="exists")
update: i had to change my answer
your function doesn't return the result of your $.ajax. $.ajax had to set your return value. Cause can't return before your ajax has been finished, you also have to add async: false to your request (see: How do I make jQuery wait for an Ajax call to finish before it returns?)
$.validator.addMethod("checkUsername",
function(value, element) {
var test = false;
$.ajax({
type:"GET",
async: false,
url: site_url + "/ajax/checkusername/" + value,
success: function(result){
if(result=="notexists") {test = true; }
}
});
return test;
},
"Username Already Exists."
);
I don't think I am passing the variable the right way between my separate PHP and AJAX files.
I am debugging this by triggering the second condition $status = 'info'; in my PHP file.
Currently, status is coming up as "undefined" for alert(data.status);
signup_process.php
if (condition){
$status = 'success';
else {
$status = 'info';
}
AJAX
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
I know that the 2nd condition is being triggered because I put a header redirect there just for testing and it worked fine.
Good to use json while return back data from php to ajax.
$return_data = array();
if (condition){
$return_data['status'] = 'success';
} else {
$return_data['status'] = 'info';
}
echo json_encode($return_data);
exit();
Now, if you are return back json data to ajax, then you need to specify return data type into ajax call as below
function send() {
var data = $('#signup_form').serialize();
$.ajax({
type: "POST",
url: "signup_process.php",
data: data,
dataType: 'json',
success: function (data) {
alert(data.status);
if (data.status == 'success') {
// everything went alright, submit
$('#signup_form').submit();
} else if (data.status == 'info')
{
console.log(data.status);
$("label#email_error").show();
return false;
}
}
});
return false;
};
You should send a JSON object back from php:
$data = array();
if (condition){
$data['status'] = 'success';
else {
$data['status'] = 'info';
}
header('Content-type: application/json');
echo json_encode($data);
The json_encode() method converts the array to a JSON object so you can access each array key by name on the js side.