can not make call to Controller function via ajax call - php

I know similar question has been answered in this forum. I have tried many of the solutions provided in stackoverflow for the problem, yet could not solve it. So I am expecting some suggestions from your expertise.
I am trying to make a call to AjaxController function on form submit via ajax call using Cakephp 3. The issue here is i am getting 403 error. I have not yet found out the fix for this. I can see that form is passing the value but Ajax call can not reach the controller function . I get following error
POST http://localhost/shoppingCart/ajax/ajaxTest 403 (Forbidden)
AjaxController:
public function ajaxTest(){
$result = "hello";
return $result;
}
script:(view.ctp of AjaxController)
$(document).ready(function(){
$('button').click(function(event){
var form_data = $(this).serialize();
var hidden_value = $('[name="id"]').val();
// alert("your form data "+hidden_value);//works fine here
event.preventDefault();
$.ajax({
url:'../ajaxTest',
type:'POST',
data : hidden_value,
success:function(result){
alert('success');
$("#result").text(result);
},
error:function(error){
alert('error ='+(error.Message));
}
});
});
});
// });
</script>

According to Cakephp:
If authenticator returns null, AuthComponent redirects user to the
login action. If it’s an AJAX request and config ajaxLogin is
specified that element is rendered else a 403 HTTP status code is
returned.
I think you didn't specify any authorization scheme. That why according to cakephp you are getting 403 error.
If you don’t use an authorization scheme, make sure to check
authorization yourself in your controller’s beforeFilter or with
another component.
You can make actions public (in beforeFilter or initialize) using:
// Allow all actions
$this->Auth->allow();
// Allow only the index action.
$this->Auth->allow('ajaxTest');
// Allow only the view and index actions.
$this->Auth->allow(['ajaxTest', 'index']);
CakePhp > Authentication > Handling Unauthenticated Requests
CakePhp > Authentication > Using No Authorization

Related

Angularjs + Codeigniter user authentication

I have an app that has a full angularjs frontend with a codeigniter backend (with thishttps://github.com/philsturgeon/codeigniter-restserver)
I am using the codeigniter backend just to make api requests essentially.
The problem I am having now is managing a navigation view based on whether or not a user is logged in.
I have the navigation in its own navCtrl with a userService and loginCtrl.
I am storing loggedIn true or false in a cookie with a $watch on it in the navCtrl so it will update the navigations appropriately.
Any insight on why this may not be working? Any code i need to provide to clarify? Is there a "better" way to do this?
EDIT: The $watch is not actually catching when I update the value using the userService.
Thank you!
We have a very similar setup as you. What we do is have Codeigniter send a HTTP Status code of 419 (not logged in) or something like that. And then you'll use Angular Interceptors to 'listen' for the response from the backend.
app.factory('loggedIn',function($q,$location){
return {
/*
* Intercept all response errors & handle them
*/
responseError: function(response) {
if (response.status == 419) {
console.error("You are not logged in");
$location.path('/login');
}
return $q.reject(response);
}
};
});
Then push it to the $httpProvider:
app.config(['$httpProvider', function($httpProvider){
$httpProvider.interceptors.push('loggedIn');
}]);
This should handle your front-end navigation pretty easily.
There are also other things that you can do for the $http requests before sending & before response is returned. Makes for a slick setup.
Checking sessions in Angularjs and CI using AJAX:
Javascript function called in angular js controllers:
function check_session()
{
$.get(base_url+"admin/check_session/check", function(data, status){
if(data=="1") /* error 1 => un-athorized user */
{
window.location.href=base_url+"login";
}
});
}
Expaining AJAX request:
check_session is CI controller and check is function in that.

SagePay with Laravel, Route issue

Im integrating Sagepay and after successful payment it returns a url like so:
/success?crypt=#4672799fb6f902806caba4
So how can i reflect this in my routes file.
I currently have:
Route::get('success', function(){
return 'Success';
});
But doesn't work, so what should I need in the routes file to achieve this callback?
Make sure that it is issuing a GET request, the callback may be a POST.
Try:
Route::all('success', function(){
return 'Success';
});

More API examples needed for mailchimp - send data then redirect

I'm relatively new to mailchimp and have been using this post to implement a very simple email capture form that will redirect to a new landing page on submit. I have been using this post:
using an existing form to send data to mailchimp, then redirect
I understand everything in the post except I need an example for this statement:
"However, if you want to redirect, you'd simply alter your jQuery ajax function to do so."
Can someone provide an example of how to alter the jQuery ajax function? Also I don't need it to return a success or failure message, I just need it to capture the name / email and then immediately redirect to the next page.
Thanks
Sparky is saying that you can modify the success function of the AJAX that is part of the submit function tied to form $('#signup').
i.e., Currently the success function is:
...
success: function(msg) {
$('#message').html(msg);
}
...
And you could just update to redirect doing something like:
...
success: function(msg) {
document.location = '/target/path/file.html';
}
...
EDIT - Doing the above will redirect the browser - so long as the AJAX call is successful (not necessarily that the API call was successful.) So even if the PHP is returning an error in the message - the success function is called because it is referring to the success of the AJAX call itself.
If you want to redirect only on a successful message returned by the PHP file then you'll have to check the incoming msg and handle accordingly.
...
success: function(msg) {
if (msg.indexOf('Success') != -1) {
document.location = '/target/path/file.html';
} else {
$('#message').html(msg);
}
}
...
This will redirect the browser on a successful message return from the PHP file, otherwise it will display the message in $('#message') .

Cannot detect if User is Logged in when using Paginator (backbone.js)

I am using the Backbone.js Paginator plugin. It does infinite scroll pagination well by defining its own Collection for the models involved in the pagination. If the user is logged in, the PHP backend will return the Backbone object with an additional attribute is_liked to cause that item to have a different CSS styling.
Problem: When the Paginator plugin (with its own Collection Backbone.Paginator.requestPager) does a GET fetch request on the backend, the backend is not able to determine if the user is logged in! However, when I use the usual Backbone.Collection, the backend is able to determine whether the user is logged in! It works with a $.post() too. This makes me think the problem lies in the plugin's Backbone.Paginator.requestPager
I am checking the results by using the Network section of Chrome's developer tools. If the authentication check works, api/test can be seen to return some data about the user. If login status cannot be determined, it returns null
UPDATE: The GET request sent by Backbone.Paginator.requestPager collection does not include the Cookie info in the headers that is found in the GET request sent by Backbone.Collection. Could this be the problem? How can I force Backbone.Paginator.requestPager to not strip out the cookie data from the headers?
What is happening here? And how can I solve this (without rewriting my own pagination code)?
Auth Test using PHP Backend (Laravel Framework)
Route::any('api/test', function() {
// This will return some data of the user if logged in
return json_encode(Auth::user());
});
Typical Backbone Collection [Works]
SimilarUserCollection = Backbone.Collection.extend({
model: User,
url: 'api/test'
});
Paginator's Collection [Doesnt Work]
PhotoCollection = Backbone.Paginator.requestPager.extend({
model: Photo,
paginator_core: {
type: 'GET',
dataType: 'json',
url: 'api/test'
},
paginator_ui: {
firstPage: 1,
currentPage: 1,
perPage: 7,
totalPages: 10
},
server_api: {
'page': function() { return this.currentPage; }
},
parse: function (response) {
return response;
}
});
This is a crossdomain issue:
One Request is to this URL:
http://www.mysite.com/api/test?page=1
And the other to this:
http://mysite.com/api/test
For the browsers www.mysite.com is totally different so if the Cookie is generated on www.mysite.com requests to mysite.com will not contain it. Be sure that both requests goes to the same domain and you will not have the Cookie issue.

Backbone.js sync - PHP return

I'm learning to work with Backbone.js and set up the following environment:
/* define the model */
var Login = Backbone.Model.extend({
url:"api/index.php/login/"
});
/* the following code is contained in a view method */
var login = new Login({
email: $("#email").val(),
pass: $("#pass").val()
});
var result = Backbone.sync('create',login);
alert(JSON.stringify(result));
In the "index.php" on the server the correct method is called and the data is correctly available.
The alert just outputs: {"readyState":1}
Now my question: What should the server (index.php) return/output to answer the client?
I'd like to transfer data back to the client to e.g. display it.
Backbone.sync() is an asynchronuous operation. You cannot do
var result = Backbone.sync('create', login);
because sync() does not return anything useful. It sends the request to the server and returns immediately, long before the server's response has arrived.
Use the options parameter and place success and error callback functions there.
Backbone.sync('create', login, {
success: function () {
// whatever you want to do when login succeeds
},
error: function () {
// display an error message
}
});
The error callback would be executed if the server returned an 401 Unauthorized response, for example; the success callback when the server returns 200 OK.
For documentation on how to use these callbacks and what other options you can use, read the jQuery.ajax() docs.

Categories