AJAX call killing CodeIgnite Session. WHy? - ajax

I am using CodeIgniter 2.x . for authentication i am using flexi auth ( http://haseydesign.com/flexi-auth/ ). I am facing a terrible problem. On a simple ajax request i am losing session.
Controller :
$this->auth = new stdClass;
// Load 'standard' flexi auth library by default.
$this->load->library('flexi_auth');
// Check user is logged in as an admin.
// For security, admin users should always sign in via Password rather than 'Remember me'.
if (! $this->flexi_auth->is_logged_in_via_password())
{
// Set a custom error message.
$this->flexi_auth->set_error_message('You must login as an admin to access this area.', TRUE);
$this->session->set_flashdata('message', $this->flexi_auth->get_messages());
redirect('auth');
}
Controller Function
public function checkItemCode(){
if($this->input->is_ajax_request()){
//die('sdasda');
$getResult = $this->items_model->checkCodeAvailablity();
if($getResult == false){
echo '<span style="color:#f00; margin-left:10px;">This code has been used for another item. Kindly use any other code. </span>';
}else{
//echo '<span style="color:#f00">You can use this code!!!</span>';
}
} // if
} // checkItemCode
AJAX CALL
$(document).ready(function() {
/// make loader hidden in start
$('#Loading').hide();
$('#code').blur(function(){
$('#Loading').show();
$.post("<?php echo base_url()?>items/checkItemCode", {
code: $('#code').val()
}, function(response){
$('#Loading').hide();
setTimeout("finishAjax('Loading', '"+escape(response)+"')", 400);
});
return false;
});
});
function finishAjax(id, response){
$('#'+id).html(unescape(response));
$('#'+id).fadeIn();
}
I have done all possible options available on net like sess_update function, MY_Session lib etc etc. but no luck.
Kindly help me out.
Best Regards.

Related

Request Ajax in Live Server doesn't work for printing

my cashier project build in laravel. i need print receipt from web browser via mobile bluetooth.
i use mike42/escpos and RawBT package.
my program is working fine when running in localhost. but, doesn't work in live server
this is my VIEW :
<button
onclick="ajax_print('{{url('/cashier/pay',[$id])}}',this)"
class="btn btn-sm btn-warning">Pay
</button>
this is my AJAX
function ajax_print(url, btn) {
b = $(btn);
b.attr('data-old', b.text());
b.text('wait');
$.get(url, function (data) {
window.location.href = data; // main action
}).fail(function () {
alert("ajax error");
}).always(function () {
b.text(b.attr('data-old'));
})
}
and this is my Controller :
try{
$profile = CapabilityProfile::load("POS-5890");
$connector = new RawbtPrintConnector();
$printer = new Printer($connector, $profile);
// Content
$printer->setJustification(Printer::JUSTIFY_CENTER);
$printer->selectPrintMode(Printer::MODE_DOUBLE_WIDTH);
$printer->text("Hello World.\n");
//Print
$printer->cut();
$printer->pulse();
} catch (Exception $e) {
return redirect()->route('cashierindex')->with('error','Something Error');
} finally {
$printer->close();
}
Can you help me, why this code doesn't work in live server, but working fine in localhost ?
I assume that is a touch little bit of problem..
in mike42 you have to spark off the requirement personal home page extension to your server. in your case, you forgot activating required extension
I think this is a little bit of problem..
in mike42 you should activate the requirement php extension in your server. in my case, i forgot activating intl extension

Laravel - how to return json on current page instead of popup window

I'm building SPA with Laravel and Vuejs, so I want to let users signin with github on popup window but problem is that authorization callback function returns json data on popup window instead of current page.
Here is a code:
Client side
authenticate() {
window.open("login/github", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
}
Server side
public function redirectToProvider($service, Request $request)
{
return Socialite::driver($service)->stateless()->redirect();
}
public function handleProviderCallback($service, Request $request)
{
$providerUser = Socialite::driver($service)->stateless()->user();
return new JsonResponse([
'data' => $providerUser
]);
}
I need to close popup window when user successfully sign in and than handleProviderCallback to return json on a current page. Any idea how can I solve this?
Parent window
<button type="button" onclick="openNewWindow()">Login With Github</button>
<script>
var win = null;
function openNewWindow() {
win = window.open("ukulele.html", "_blank", "toolbar=yes,scrollbars=yes,resizable=yes,top=500,left=500,width=400,height=400");
win.focus();
}
window.saveToken = function() {
console.log(win.document.getElementById('json_data_here').value)
}
</script>
Child window: After success login with github, save token to a hidden input and close window:
<input type="hidden" id="json_data_here" value="aadcs"/>
<script>
window.opener.saveToken();
window.close();
</script>

Codeigniter ajax information needed

I am a beginner with Codeigniter. This will be my first time to use Ajax. I want only "content" part change when I click the navigation links. I need to learn how to use ajax in my site.
MY_Controller.php :
class MY_Controller extends CI_Controller {
protected $data = array();
function __construct() {
parent::__construct();
}
function render_page($view) {
if( ! $this->input->is_ajax_request() )
{
//do this to don't repeat in all controllers...
$this->load->view('templates/header', $this->data);
//menu_data must contain the structure of the menu...
//you can populate it from database or helper
}
$this->load->view($view, $this->data);
if( ! $this->input->is_ajax_request() )
{
$this->load->view('templates/menu');
$this->load->view('templates/footer', $this->data);
}
}
My home/about controller view function:
public function view($page = 'home')
{
$this->load->helper('text');
$this->data['records']= $this->services_model->getAll();
if ( ! file_exists('application/views/pages/'.$page.'.php'))
{
// Whoops, we don't have a page for that!
show_404();
}
$data['title'] = ucfirst($page); // Capitalize the first letter
$this->render_page('pages/'.$page,$data);
}
I think , I could enable ajax in MY_Controller.php. What to do after this? How shall i enable posts in the view?
Edit : I made some more research about jquery and ajax.
This is my navigation menu part of html :
<div id="sidebar-content">
<ul id="menu">
<li class="current">ANASAYFA</li>
<li>HAKKIMIZDA</li>
......
I have written and ajax.js file in the head section as :
//Navigation
$("#sidebar-content ul li a").click( function(){
$.ajax({
url: "<?php echo site_url('about'); ?>",
type: 'POST';
data: JSON,
success: function(msg) {
$('#content').body(msg);
}
});
});
return false;
});
Can you refine my code ? One more problem is :If I use the ajax in the head part,how can i post different pages as urls?
Your problem is a little ambiguous, but here are some issues I can see with your JQuery:
You have set data: Json in your JQuery, but it looks like you are
returning HTML, so change this to HTML.
You have a semi colon after type: post when it should be just a
comma
The url points to the controller, not the method. Change it to "<?php echo site_url('about/view'); ?>",
There is no such thing as JQuery .body(), you want .html() or the complete line for your success function: $('#content').html(msg);. Obviosult make sure you have a element named id="content".JQuery will then replace this with the reponse from the server, which should be pure html returned from your controller. You can use codeigniters $this->load->view() to return the correct file.
Other notes - it seems you need to read up on JQuery, especially the ajax function
Here's a good tutorial to follow about using Ajax with CI - http://net.tutsplus.com/tutorials/php/codeigniter-from-scratch-day-8-ajax/
Finally, use the console and network features in Chrome's developer tools web inspector or get Firebug for Firefox this way you can see js errors and monitor ajax requests (XHR)

ajaxComplete/ajaxStop/ajaxSuccess not firing

I appreciate any and all help. I am a beginner with little jQuery/AJAX experience and I have been going crazy trying to figure out why I can't figure this out.
I'm writing a Facebook page application that has the user grant permissions and upload a video to the page. All of this works fine and dandy. This is not so much a Facebook API related issue as it is an ajax issue (at least I think).
Basically, I am trying to gain control of the page IN SOME WAY after the user uploads a video. I am using the [malsup jQuery Form Plugin][1] to have the resulting page (which is a page on Facebook displaying returned JSON values) load in a hidden iframe.
I am able to get ajaxStart to fire, and I've tested this by having it change the background color or print an alert message when I click "Upload". However, when the upload completes (and it does complete successfully), NOTHING ELSE HAPPENS. The returned JSON values load in the hidden iframe and the page sits there. I have tried getting ajaxComplete, ajaxStop and ajaxSuccess to fire, but none of them do for whatever reason.
So overall, here is what I am trying to accomplish:
- I want to redirect the user or make some hidden content appear after the file upload completes. I don't even care if there's errors. I just need SOMETHING to happen.
- I am using the jQuery Form Plugin because I am not unfortunately not advanced enough to figure out how to use that value and do something with it, but if anyone can steer me in the right direction, that would be appreciated.
And finally, here is my code:
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6/jquery.js"></script>
<script type="text/javascript" src="http://malsup.github.com/jquery.form.js"></script>
<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
iframeTarget: '#output2',
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback
};
// bind form using 'ajaxForm'
$('#theform').ajaxForm(options);
});
// pre-submit callback
function showRequest(formData, jqForm, options) {
return true;
}
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
</script>
<script type="text/javascript">
jQuery().ready(function(){
$('body').ajaxStart(function() {
$(this).css("background-color","red");
});
$('body').ajaxSend(function() {
$(this).css("background-color","blue");
});
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
$('body').ajaxStop(function() {
$(this).css("background-color","purple");
});
});
</script>
</head>
<body>
<?php
$app_id = "xxxxxxx";
$app_secret = "xxxxx";
$my_url = "xxxxxx";
$video_title = "xxxxxxxxx";
$video_desc = "xxxxxxxxx";
$page_id = "xxxxxxxx";
$code = $_REQUEST["code"];
if(empty($code)) {
// Get permission from the user to publish to their page.
$dialog_url = "http://www.facebook.com/dialog/oauth?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&display=popup&scope=email,publish_stream,manage_pages";
$current_url = (!empty($_SERVER['HTTPS'])) ? "https://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'] : "http://".$_SERVER['SERVER_NAME'].$_SERVER['REQUEST_URI'];
if ($current_url != $dialog_url)
{
echo('<script>window.location ="' . $dialog_url . '";</script>');
}
} else {
// Get access token for the user, so we can GET /me/accounts
$token_url = "https://graph.facebook.com/oauth/access_token?client_id="
. $app_id . "&redirect_uri=" . urlencode($my_url)
. "&client_secret=" . $app_secret
. "&code=" . $code;
$access_token = file_get_contents($token_url);
$accounts_url = "https://graph.facebook.com/me/accounts?" . $access_token;
$response = file_get_contents($accounts_url);
// Parse the return value and get the array of accounts we have
// access to. This is returned in the data[] array.
$resp_obj = json_decode($response,true);
$accounts = $resp_obj['data'];
// Find the access token for the page to which we want to post the video.
foreach($accounts as $account) {
if($account['id'] == $page_id) {
$access_token = $account['access_token'];
break;
}
}
// Using the page access token from above, create the POST action
// that our form will use to upload the video.
$post_url = "https://graph-video.facebook.com/" . $page_id . "/videos?"
. "title=" . $video_title. "&description=" . $video_desc
. "&access_token=". $access_token;
// Create a simple form
echo '<form action=" '.$post_url.' " method="POST" enctype="multipart/form-data" id="theform">';
echo 'Please choose a file:';
echo '<input name="file" type="file">';
echo '<input type="submit" value="Upload" id="button-upload" />';
echo '</form>';
}
?>
<iframe id="output2" name="output2"></iframe>
</body></html>
Thank you for your help!!
It seams you are getting an Ajax Error. I don't see any error handler in your code. Could you try to add an error handler as follows
<script>
$(document).ready(function(){
$(document).ajaxError(function(e, jqxhr, settings, exception) {
alert(exception);
})
})
</script>
I have played around with file uploads, and there are a complicated beast because of all the security that browsers have for protecting users file systems and whatnot.
On to your problem, I think that there is a good chance that your AjaxForm jQuery plugin doesn't connect properly to the global Ajax state for Jquery. Even if it did, I would say that tapping into the global Ajax state is a bad design. If you add any other ajax requests to this page, then your ajaxComplete, ajaxStop, etc. functions are going to start getting called.
Your better approach is to use the callbacks provided by the AjaxForm plugin. Lets focus on this first part of your code.
Does this work?
success: showResponse // post-submit callback
...
// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
alert(responseText);
}
If so, could you replace this:
$('body').ajaxComplete(function() {
$(this).css("background-color","green");
});
With this:
function showResponse(responseText, statusText, xhr, $form) {
$(this).css("background-color","green");
}
I believe that using the success: callback is the intended use of the AjaxForm plugin.
The jquery ajaxSend or ajaxStart throws some kind of an error and the document does not execute ajaxComplete. I tried to fix the bug for quite a while and was only able to find a workaround:
function hideAjaxIndicator() {
$('#ajax-indicator').hide();
}
$(document).ready(function () {
setTimeout(hideAjaxIndicator, 1000);
});
You can add this to .js file.

How make Zend_Form submission without reload a page - with Ajax?

How make Zend_Form submission without reload a page - with Ajax?
This is code for create form that reload a page when submitted, what should be change or add that this form will submit with ajax (1.regular solution 2.jquery solution):
Form:
class Application_Form_Login extends Zend_Form
{
public function init()
{
$username=new Zend_Form_Element_Text('username');
$username ->addFilter('StringToLower')
->addValidator('alnum');
$password=new Zend_Form_Element_Text('password');
$password->addFilter('StringToLower')
->addValidator('alnum');
$submit=new Zend_Form_Element_Submit('submit');
$this->addElements(array($username,$password,$submit));
}
}
Controller:
$form = new Application_Form_Login();
$request = $this->getRequest();
if ($request->isPost()) {
if ($form->isValid($request->getPost())) {
if ($this->_process($form->getValues())) {
//code indside
}
}
}
$this->view->form = $form;
View:
<?
echo $this->form;
?>
My proposal that I don't think is proper(does form make filtering and validation?) for View:
<?
echo $this->form;
?>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form').submit(function(){
var sendData=$(this).serialize();
$.ajax(
{
url:'',
dataType:'json',
type:'POST',
data:sendData,
success: function(data) {
}
});
return false;
});
});
</script>
Thanks
Well,
for filtering/validation you might want to send the form using Ajax and by knowing at the server-side that it is an Ajax request (you can use a flag for that, like a header, search for knowing if a request is ajax or not) and sending back only the form 'area'. Then when you receive it you can overwrite it.
There is currently no wiser way to do it with Zend_Form I think.

Resources