Codeigniter method ajax issue related to url - ajax

I have a controller where i have a method called index.
In this method i am retrieveing data from database and using a paging library setting variables for view for paging. When i add a new record i am hitting another function using ajax. There after insertion i call
$this->index();
Now in index i am checking a condition
if($this->input->is_ajax_request()){
//dont load header and footer
}
but the problem is that when i come to index from my save function it looses the ajax request and my condition in index function in not checked and header and footer is always loaded. I want the ajax request still be available even if i jump from one method of codeigniter to another? Any suggestion? Or alter native.
Because i dont want to create another function where create the paging again with header and footer ommited.

Something that might be useful is CodeIgniter's session class which has a flashdata method. Flashdata is a bit of session data that is only stored for the next server request, then it is deleted.
In your save function, you could have this at the end:
$this->session->set_flashdata('ajax', true);
and as part of the condition in your index function, you could have:
if($this->input->is_ajax_request() || $this->session->flashdata('item')){
//dont load header and footer
}
This would then check that the request was actually an ajax request OR that a session variable has been temporarily set to tell CodeIgniter that it should be treated like an ajax request.

Related

Whats the difference between redirect and this in Codeigniter?

I am new in Codeigniter and it's one of the good frameworks of php. But on some conditions I'm confused. Like this one. If any of you have any clarification about my dough, it's a great help for me.
Offcouse redirects refresh the page and $this not but apart from this I want to know - anyhow both of them used to go to somewhere else on view pages or like in other controller or in same controller to other methods.
But we don't use these side by side because when getting any of them it will go to that page or method without checking the next lines.
In case of a normal difference then have lot's of but I just want to know about the condition of going to next page or method when we use redirect or $this like this -
$this->Function($value); //It's method of same controller.
redirect('Controller/function'); //It's also doing same with page reload.
Thank for looking my problem.
Redirect()
When you will call any function of helper in codeigniter then you can call function directly without using any object. Helper in Codeigniter is collection of functions.
Redirect() method is a part of URL helper in Codeigniter.
For your ref. https://www.codeigniter.com/user_guide/helpers/url_helper.html
So, just load helper using $this->load->helper('url'); or you can also mention in autoload.php file.
$this->Function(); used to call a function from same controller
$this->Function(); used to call a function from same controller
redirect()
While building a web application, we often need to redirect the user from one page to another page. CodeIgniter makes this job easy for us. The redirect() function is used for this purpose.
redirect($uri = '', $method = 'auto', $code = NULL)
The first argument can have two types of URI. We can pass full site URL or URI segments to the controller you want to direct.
The second optional parameter can have any of the three values from auto, location or refresh. The default is auto.
The third optional parameter is only available with location redirects and it allows you to send specific HTTP response code.
Redirect means jumping to another function mentioned in the redirect method.
$this->Function($value); => jumping to another function and you can execute the code of the same function as well as pass the value back by returning value.
When you send request to codeigniter generally CI controller gets called and then function which is mentioned in uri segment. like below... So this will be another request.
redirect('Controller/function'); //It's also doing same with page reload.
But when you have to call another function within the same request then you can use below approach
$this->Function($value); //It's method of same controller.
This will execute the given function and return the value within same request.

Laravel Session data not written/update/availabe in View when using AJAX

When I add things to the Session with Session::put() in my controller action, then that data is not available in my view, with Session::get() when doing AJAX request.
The same problem goes for the Former package, which I use for nice form building. It relies on passing some info via the Session, which is used to mark fields as valid/invalid. This functionality is also not working when using AJAX.
I set a view like always, in my View:
$this->layout->content = View::make('account.login')
For AJAX requests, I do NOT render the normal way with layout, but instead get the specific "content" section of the template and return it:
$this->layout->content->renderSections()['content']
When I do a "normal" request, then Session data works fine.
When I do an AJAX request, then Session data set in the controller DURING the AJAX call is ignored. Any Session data set BEFORE the AJAX call is available.
I'm wondering if Laravel has some issue with Session under AJAX calls, or with the the "renderSection()" method above?
I have checked all the obvious problems:
AJAX request uses the same session ID as non-AJAX request.
GET/POST verbs are used correctly etc.
Replicate:
In CONTROLLER action: Session:put('foo','bar');
In VIEW file (in the content part): Session:put('foo2','bar2');
In VIEW file (in the content part): var_dump(Session::get('foo','bar')); // Returns 'bar' in non-AJAX calls, but returns nothing for AJAX calls (!!!)
In VIEW file (in the content part): var_dump(Session::get('foo2')); // Returns 'bar2' in both AJAX and non-AJAX calls as expected.
It seems like the Session values set in the controller action ARE LOST when it renders the view. Therefore my question if this is 1) an AJAX vs. SESSION issue in Laravel, or 2) an Session vs. renderElement() problem that I am not aware of?
I had the same problem and just found a potential solution:
I found a similar problem relating to laravel 3. For the session to persist in an ajax call you need to return the response correctly.
return json_encode($response);
This is causing the problem. It's not it appears a valid response to enable the session to persist. Change it to:
return Response::json($response);
This enables the session to persist!
For some reason a normal form submit or call to the method allows the first one but ajax does not.
I've seen references elsewhere about echo statements in the method affecting the session - the return I suppose must behaving similar to an echo
This is the post that triggered the solution:
http://forumsarchive.laravel.io/viewtopic.php?id=1304

failed to return AJAX call when use_session_sid

I am trying to use php's use_trans_sid, so I will have phpsessid in all urls.
But, when I set use_trans_sid to 1, AJAX call did not get result properly.
Somehow the result truncated.
When I set use_trans_sid back to 0, AJAX call get result properly again.
What would be the problem?
I am using the Yii framework.
Check ajax url requests when use_trans_sid=1, if they haven't phpsessid var than you need manually add it to request url as GET parameter.
use_trans_sid=1 rewrites only page url, not js and ajax. When it using, PHP try to find session id in get parameter, if not found - created new session.
When you using use_trans_sid=0 ajax works, because PHP work over cookie session id
I have set php's use_trans_sid to 1.
With that, PHP will insert code to propagate session id.
In my case, PHP inserted a hidden variable in a form which has been encoded into json object.
As the result, ajax call get it as a request error (it did not get a json object).
I confirmed this by replacing the form with string like 'Hello'.
With that, PHP did not insert code to propagate session id. And ajax call get it as a good json object.
Now the problem has changed into 'how to make such interruption from PHP will not interfere ajax call?'

Zend_Form csrf validation for ajax queries

Here is how I add the csrf to the form
$this->addElement('hash', 'csrf', array('ignore' => false));
When this happens the session is created, Then when the user sends an ajax request, the values in the request are validated by creating an instance of the form, and the form is always valid for the first ajax request since the beginning of initial request which created the html output,
When the ajax request has been sent for the second time something different happens,
That instance of the form has a different csrf value than the originally made one, and when my code is done, the originally created session is destroyed as well, so there is no session to check the received the values against, and hence the form doesn't validated and the following error occurs.
No token was provided to match against
Any ideas at which event, the csrf values of the form are automatically stored in the session?
The hash value is generated at render time and invalidated after the each request.
If you want to continue using Zend_Form_Element_Hash in your AJAX form where the form may submit several times, your AJAX response should include the new hash value. Upon receiving the response, you should update the form data.
There s a solution without any to render in the view : Totaly ajax !
How to use Zend Framework Form Hash (token) with AJAX

Use CodeIgniter form validation in a view

I have footer view that's included on all my pages which contains a form. I would like to be able to make use of CI's form validation library to validate the form. Is that possible?
Currently the form posts back to the current page using the PHP_SELF environment variable. I don't want to get it to post to a controller because when validation fails it loads the controller name in the address bar, which is not the desired behaviour.
Any suggestions gratefully received.
Thanks,
Gaz
One way, whilst far from ideal, would be to create a "contact" function in every controller. This could be in the form of a library/helper.
CI doesn't natively let you call one controller from another, although I believe there are extensions that enable this.
Another option would be an AJAX call instead, which would allow you to post to a generic controller, validate etc whilst remaining on the current page.
In this use case, I would definitely go for an AJAX call to a generic controller. This allows you to show errors even before submitting in the origin page.
Another way (slightly more complex), involves posting your form data to a generic controller method, passing it a hidden input containing the current URL.
The generic controller method handling your form can then redirect to the page on which the user submitted the form, passing it the validation errors or a success message using flash session variables: $this->session->set_flashdata('errors',validation_errors()) might do the trick (untested)
The good thing about this is that you can use the generic form-handling method for both the ajax case (suppressing the redirect) and the non-ajax case
AJAX would be best, just like everyone else says.
I would redirect the form to one function in one controller, you could make a controller just for the form itself. Then have a hidden value with the return URL. As far as errors go you could send them back with flashdata.
Just remember to never copy paste code, it a bad practice and guarantees bugs.
//make sure you load the proper model
if ($this->form_validation->run() == FALSE){
// invalid
$redirect = $this->input->post('url');
$this->session->set_flashdata('errors',validation_errors());
redirect($redirect);
} else {
/*
success, do what you want here
*/
redirect('send them where ever');
}

Resources