I use my own Framework, in localhost all works perfectly fine but not on the server.
I'm logged, so I've a session id.
On a ajax request, the php script doesn't keep my session, if I return the session, the session are empty but me in my side, I keep the session.
It's like if the server thinks the ajax request is a new user.
I don't know where to look and I can't post all the framework code here...
Yesterday I already have this issue (at work) then at home, I retested and all worked great...
I don't get it...
$(document).on('click', '.edit', function(){
$.ajax({
type: "POST",
url: ROOT+"list",
data: {id:id},
headers: {
Accept : "application/json; charset=utf-8"
},
cache: false,
success: function(data){
console.log(data.sess.ROLE);
if(data.status == "error"){
//error
}else{
//ok
}
}
});
});
Controller:
public function editAction(){
//if(!$this->ROLE('tokayn')){ $this->redirectUrl('thread_index'); }
if(Request::POST()){
if(is_int($_POST['id'])){
$user = $this->batiments->findById($_POST['id']);
if($user->id_proprio == $_SESSION['id']){
$data = array('status'=>'ok', 'message'=>$user);
Request::renderJson($data);
}else{
Request::renderJson(array('sess'=>$_SESSION));
//$data = array('status'=>'error', 'message'=>'error');
//Request::renderJson($data);
}
}else{
$data = array('status'=>'error', 'message'=>'error');
Request::renderJson($data);
}
}else{
//$this->redirectUrl('thread_index');
}
}
If a user is not logged, the session role is 'visitor' but if he's logged, the session role is 'connected'.
I've a echo before the ajax form and it's 'connected'.
Then, on submit the ajax form, the ajax request return 'visitor' but if I refresh, I keep the 'connected' echo...
I've faced this issue for me the problem was I was using
https://server:1234/somecontroller
while i was requesting from ajax as
http://server:3344/somecontroller
and session was not shared between https and http so double check if this apply for you.
Related
I have read a lot on codeIgniter ajax response. I have and modified my ajax script multiple times yet codeIgniter does not return the json response although I see the response when debugging with firefox developer browser under the network tab of web console. here's what i have written
AJAX script
$("#class_id").change(function(){
var class_id = $("#class_id").val();
alert(class_id);
alert("<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id");
$.ajax({
method: "POST",
url: "<?php echo base_url(); ?>teacher/index.php?teacher/set_class_id",
dataType: 'json',
data: {class_id: class_id},
success: function(response) {
$("#res").html(reponse.class_id);
}
});
return false;
});
controller
function set_class_id()
{
if ($this->session->userdata('teacher_login') != 1)
redirect(base_url(), 'refresh');
//echo "dsdsd".$this->input->POST('class_id');
if (!empty($this->input->POST('class_id')))
{
$page_data = array('class_id' => $this->input->POST('class_id'));
//$response["JSON"] = json_encode($page_data);
$response = array('class_id' => $this->input->POST('class_id'));
echo json_encode($page_data);
$this->load->view('backend/index', $page_data);
}
}
Have you tried using
$this->output
->set_content_type('application/json')
->set_output(json_encode(array('foo' => 'bar')));
Also, check th output class for more info Codeigniter Output Class
So I figured a way out. using just php, I sent the class_id to the controller using a submit button then checked for the response on the page to enable the subject dropdown. Although i haven't figured why the ajax isn't working yet. thanks guys for your inputs
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.
At this moment I am using laravel. In this context I am having a form which is successfully submitted by using ajax to a controller. and that controller make it to the database. But the problem is as the ajax is doing its job the whole page remain unmoved / unchanged after the submission even the database is updated.
Now what I want
I want to give feedback to the user that your post is successfully submitted there. or what I want to do in further, I want to refresh the section in which the post is collected from the database as this post can be retrieved from there. But by using ajax only.
So there is no need to collect the whole page or refresh.
here is my form structure
`
{{ Form::open(array('route' => array('questions.store'), 'class' => 'form-horizontal' )) }}
blah blah blaaa .......
<script type="text/javascript">
$(".form-horizontal").submit(function(e){
$(this).unbind("submit")
$("#ask").attr("disabled", "disabled")
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response){
console.log(response);
}
});
return false;
});
</script>
{{ Form::close() }}
`
As it is very much visible that the post is updated through a route & controller I want to have another dive and a success message at this script to be displayed after the success of posting. I am looking for some professional structure using what there is minimal need to have interaction with the server side and give user a better page viewing experience.
Thanks a lot for helping me in this research.
I am not sure if I understand you well, but if you want to notify the user about the result of an ajax-called db update you need to have
a route for the ajax save db call - it should point to a method that does the db update.
the db update method should return some value indicating the success/failure of update (for example OK or FAIL)
the only result of calling the method will be just plain text page with OK or FAIL as body
fetch the result by ajax and inform user accordingly (after form submit button)
check out the below code for ajax call itself (inside the form submit handler) to see what I mean
var db_ajax_handler = "URL_TO_YOUR_SITE_AND_ROUTE";
var $id = 1; //some id of post to update
var $content = "blablabla" //the cotent to update
$.ajax({
cache: false,
timeout: 10000,
type: 'POST',
tryCount : 0,
retryLimit : 3,
url: db_ajax_handler,
data: { content: $content, id: $id }, /* best to give a CSRF security token here as well */
beforeSend:function(){
},
success:function(data, textStatus, xhr){
if(data == "OK")
{
$('div.result').html('The new Question has been created');
}
else
{
$('div.result').html('Sorry, the new Question has not been created');
}
},
error : function(xhr, textStatus, errorThrown ) {
if (textStatus == 'timeout') {
this.tryCount++;
if (this.tryCount <= this.retryLimit) {
//try again
$.ajax(this);
return;
}
return;
}
if (xhr.status == 500) {
alert("Error 500: "+xhr.status+": "+xhr.statusText);
} else {
alert("Error: "+xhr.status+": "+xhr.statusText);
}
},
complete : function(xhr, textStatus) {
}
});
EDIT: as per comment, in step 2 (the method that is called with AJAX) replace
if($s)
{
return Redirect::route('questions.index') ->with('flash', 'The new Question has been created');
}
with
return ($s) ? Response::make("OK") : Response::make("FAIL");
EDIT 2:
To pass validation errors to the ajax-returned-results, you cannot use
return Response::make("FAIL")
->withInput()
->withErrors($s->errors());
as in your GIST. Instead you have to modify the suggested solution to work on JSON response instead of a plain text OK/FAIL. That way you can include the errors in the response and still benefit from the AJAX call (not having to refresh the page to retrieve the $errors from session). Check this post on the Laravel Forum for a working solution - you will get the idea and be able to fix your code.
I am building a registration form with jquery which should handle the request via Ajax.
My code:
$.ajax(
{
type: "POST",
url: "http://www.example.com/register.php",
data: $("#register-form").serialize(),
cache: false,
success: function(message)
{
$("#reg_notification").html(message).fadeIn(400);
}
});
Now the register.php should either output an error if for example the email address is not valid and this will be put into the div reg_notification. If no error is made, then the user should be redirected to a "welcome page". But it is important that this page is not allways static, so in other words, I can not use a location.href in the jquery code but want to use
header("Location: http://www.example.com")
in PHP. The problem is that the user wont be redirected but the content of www.example.com will be put inside the div reg_notification.
I found a similar problem here: How to manage a redirect request after a jQuery Ajax call but the difference is that there they are using json which I can not use due to my server and they are also redirecting inside the javascript and not in the php file.
Impossible with header redirection.
Use something like that:
...
success: function(message)
{
$("#reg_notification").html(message)
.fadeIn(400, function() {window.location = "url"});
}
or
success: function(response)
{
if (response.success) {
$("#reg_notification").html(response.message)
.fadeIn(400, function() {window.location = response.redirectTo; } );
} else {
// somethings else
}
}
in php:
header("Content-type: application/json");
echo json_encode(array(
"success" => true,
"message" => "some message",
"redirectTo" => "my url"
));
UPDATE
header redirect impossible because XMLHttpRequest transparently follows to redirect url for get result. See there
I have a problem in server side retrieving session with using ajax post request. Here is my sample code:
JavaScript:
$(function() {
$('.jid_hidden_data').submit(function() {
var serialized = $(this).serialize();
var sUrl = "http://localhost/stuff";
$.ajax({
url: sUrl,
type: "POST",
data: serialized,
success: function(data) {
alert(data);
}
})
return false;
});
});
CodeIngiter(PHP) side:
function stuff()
{
$post_stuff = $this->input->post('my_stuff'); // WORKS PERFECTLY
$user_id = $this->session->userdata('user_id'); // RETURNS NULL
}
Where commented returns NULL it should return users session data, because it really exists. What is the problem? Method post doesn't get cookies or what? Thanks for any help!
Update:
For clarification i have session set with $this->session->set_userdata($data).
And I don't have a problem when posting it without js/ajax. I mean with plain form submit it works fine.
I had a similar problem when accessing a CI app using different domain names. Even though those domain names pointed to the same web server, I got two separate sessions.
For example, consider this Controller :
class User extends Controller
{
function User()
{
parent::Controller();
$this->load->library('session');
}
function login()
{
$this->session->set_userdata('login_token', true);
echo 'finished logging in';
}
function logout()
{
$this->session->unset_userdata('login_token');
echo 'finished logging out';
}
function status()
{
if ($this->session->userdata('login_token'))
{
echo 'logged in';
}
else
{
echo 'not logged in';
}
}
}
I access the following URLs in sequence. Beside each URL is the corresponding output :
http://localhost/app/user/login "finished logging in"
http://localhost/app/user/status "logged in"
http://127.0.0.1/app/user/status "not logged in"
So the session I have when accessing the app on localhost does not carry over to 127.0.0.1, even though I'm hitting the same web server.
Could it be that the domain name of the URL in your AJAX script is different to that of the URL that you are testing with?