How do you differentiate between an AJAX GET and an AJAX POST request in CakePHP? - ajax

In my CakePHP app for my login method I do some different things for when a user submits a form via AJAX calls using if ($this->request->is('ajax'))
However I also want to allow the login method to be shown in a modal for quick login which again is an ajax call. But how do I detect the difference between the AJAX GET to show the form and then AJAX POST to do the actual login?
See below I can detect native get and posts but for ajax how do I detect the difference in CakePHP??? As it seems I can only detect an ajax event and not the type :/
NATIVE:
GET = if ($this->request->is('get'))
POST = if ($this->request->is('post'))
AJAX:
GET = if ($this->request->is('ajax'))
POST = if ($this->request->is('ajax'))
Thanks

Solution:
if ($this->request->is('get'))
{
if ($this->request->is('ajax'))
{
echo json_encode('ajax get'); exit;
}
else {
echo 'Normal get'; exit;
}
}
if ($this->request->is('post'))
{
if ($this->request->is('ajax'))
{
echo json_encode('ajax post'); exit;
}
else {
echo 'Normal post'; exit;
}
}

Not sure if I understand the question, but if the problem is that the form data can come in either as a POST or GET, the solution is to check whether the POST data is there. If it is, use POST, otherwise take the data from GET. (Or other way around.)
If the function should do different things depending on whether the form has been sent as POST or GET, then simply make two different functions in the controller.

Related

Laravel: controller not teletransporting me (redirect-ing me) to the page

from Ajax the controller does get the keyword I want, as it confirms it (because I echo it), and my idea was that on getting that keyword, it should redirect to the page I want. Yet, it does not, and also, while it does change the locale, I have to reload the page, otherwise, it won't show any translation and locale changes on the page. In Firebug when I hover over the POST, I get the correct URL to where I would want to go: sort of http://myweb.com/es but the controller does not change the http URL box of my browser on my web to go there.
I am simplifying the Controller code here, but actually I will want it to go to different URLs depending on the keyword it gets, something that I would do with a switch statement or IF else if etc.
So the controller is as simple as this:
public function changelanguage()
{
$lang = \Input::get('locale');
echo "I got $lang";
Session::put('locale', $lang);
return redirect('/es');
}
If instead of using ajax I use a Form, then I dont need to reload, the Action of the form makes the controller change the locale and translate the page without reloading. But I need to use ajax and in any case, the controller does get correctly the keyword ('en', 'es', 'de' etc ) for languages, so it should take it from there and redirect me to the URL page, but it just doesnt move.
if you are curious about the Ajax, here it is, but it does send the keyword as I said.
$(document).ready(function(){
$('.choose-language').on('click', function(e){
e.preventDefault();
var selectedlanguage = $(this).data('value');
$.ajax({ // so I want to send it to the controller
type:"POST", // via post
url: 'language',
data:{'locale': selectedlanguage},
}); // HERE FINISHES THE $.POST STUFF
}); //HERE FINISHES THE CLICK FUNCTION
}); // HERE FINISHES THE CODE
ROUTES
Route::post('language', array(
'as' =>'language',
'uses' => 'LanguageController#changelanguage'
));
If you’re trying to perform the redirect in the AJAX-requested script, then it won’t work. You can’t redirect from a script request via AJAX otherwise people would be doing all kinds of nefarious redirects.
Instead, set up a “success” handler on your AJAX request that refreshes your page if the request was successful. It can be as simple as:
var url = '/language';
var data = {
locale: $(this).data('value');
};
var request = $.post(url, data)
.success(function (response) {
// Script was successful; reload page
location.reload();
});
I’m not sure how you’re allowing users to select locales, but since you need a reload any way I think AJAX is pointless here. Just have a traditional form that submits the new locale to an action, set the locale in a session/cookie/whatever, and then redirect back to the referring page.

Cakephp - Proper way to return AJAX Success response?

I have been using the trick below to return success response with AJAX:
//In controller
echo 'success';
//In Javascript
if(response == 'success'){
//redirect
window.location.href = '/users/profile/';
}
It works fine on localhost. But in web server, I got the error below everytime I want to redirect the page after success:
Cannot modify header information - headers already sent by (output started at ...
So yeah, I know it is caused by the echo before redirecting.
So, Is there proper way to return the success response? No need to be a message, just true or false is enough.
[EDIT]
By using exit('success'), it works fine, but is this the best way?
Thanks.
It is better to redirect from javascript.
//In controller
echo 'success'; exit;
//In Javascript
if(response == 'success'){
window.location = 'your-controller-action';
}
EDIT
You may have space before/after php Opening/Closing tags in controller and models. Remove all the closing tags from all controllers and models and any whitespace before opening tags. Then check the result.

Codeigniter controller detecting ajax file upload

I have set up my Codeigniter application so that I can upload files via Ajax. I followed this tutorial http://net.tutsplus.com/tutorials/javascript-ajax/how-to-upload-files-with-codeigniter-and-ajax/
My original form checked to see if an ajax request had been called, if not then I had the fallback CI form validation / error messages showing instead.
I checked this using - $this->input->is_ajax_request()
My code looked like this:
if($this->input->is_ajax_request()){
// process ajax form data
} else {
if($this->form_validation->run() == FALSE) {
$data['success'] = 0;
$data['errors'] = validation_errors();
} else {
$data['success'] = 1;
}
$this->load->view('form', $data);
}
After doing some investigation I discovered that I couldn't apply the same technique because it isn't actually an ajax request, therefore I am not sure how I can use this approach. If anyone can point me in the right direction that would be great. I don't like it being totally dependent on ajax, I like having a fallback option. I noticed in the comments that someone has set up a CSFR cookie in their ajaxfileupload.js but to be honest I'm not too hot with js so I wouldn't know where to begin. Thanks in advance.
In your AJAX request along with everything else you could post key/value:
ajax : 1
Then in your controller:
if( $this->input->post('ajax') == 1 ) {
// process ajax form data
}
else
{
// form validation
}
Hope this helps.

how can I redirect in .jsp while working with Ajax

I am developing application using Ajax and jsp.
My index.jsp page has HTML code for Login and some Ajax code in javascript. Ajax will call my another CheckLogin.jsp page
CheckLogin.jsp page checks on server for valid username and password. It returns "success" if it's valid otherwise will return message stating "username or password is not valid."
Now, when username and passwrod is valid, instead of success, I want to redirect the page to "Home.jsp" what should I do?
I am new to jsp. I appreciate your help on this.
JSP code gets run once on the server before it goes to the client, so JSP/JSTL cannot do a redirect following the success or otherwise of an AJAX call (without a full page refresh - which obviates the use of AJAX). You should to do the redirect with Javascript:
if (success) {
var successUrl = "Home.jsp"; // might be a good idea to return this URL in the successful AJAX call
window.location.href = successUrl;
}
On successful AJAX call/validation, the browser window will reload with the new URL (effectively a redirect).
Since I don't see your code, you can integrate this somewhere inside your validation :
<%
pageContext.forward("logged.jsp");
%>
function Edit() {
var allVals = $('#NEWFORMCampaignID').val();
if (allVals > 0) {
window.location = '/SMS/PrepareSMS?id='+allVals;
}
else
alert("Invalid campaign to Edit")
}
In order to redirect using Button click and pass some parameters, you can call the Controller Path(#RequestMapping(value="/SMS/PrepareSMS")) and then handle it there..

create a nested jQuery post in another post callback?

since I'm new in jquery, can you tell me how to redirect a page to another action method ?
I develop a MVC web application. I use jquery post method to do some validation, and when it return true, it will be redirect page to another one.
My problem is..when when I redirect page using window.location, it's works well in IE (IE 9). but didn't work on firefox & chrome.
So, I try to using jquery post method to redirect page from action method in my controller. I call redirect post method in a jquery post call back.
it is my code :
$.post(posturl, formData, function (result) {
if (result == 'True') {
$.post("/Controller/RedirectMethod", {_Action: 'Index', _Controller: 'Home'}, null);
}
else
alert('failed');
}
);
and this is my RedirectMethod :
[HttpPost]
public ActionResult RedirectMethod(string _Action, string _Controller)
{
return RedirectToAction(_Action, _Controller);
}
so how I should create a nested post in another post callback ?
or there is another way to redirect page ?
thanks,
You won't be able to do a RedirectToAction inside an Ajax request.
If you need the web page to change to a different location inside the Ajax response, use window.location as Ben suggested.
One thing to bear in mind is that you'll need to remove the 'HttpPost' action filter.

Resources