How to pass a AJAX call on OctoberCMS - php

Im using OctoberCMS, the user plugin and I want to send data via AJAX to a controller and save the data in the database (in the column of the logged in user).
So I created a new Route in my routes.php
<?php
Route::get('saveHighscore', 'test\Profile\Controllers\HighScore#saveHighscore')
->middleware('web');
And a controller
<?php
namespace Test\Profile\Controllers;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use October\Rain\Auth\Models\User;
use RainLab\User\Facades\Auth;
class HighScore extends \Illuminate\Routing\Controller
{
function saveHighscore(Request $request) {
DB::table('users')->where(['id' => Auth::getUser()->id])->update(['highscore' => $request]);
}
}
And my jQuery calls
$.ajax({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
url: "/saveHighscore",
type: "POST",
data: highscore
});
But nothing works. If I call /saveHighscore in my browser with dummy data in the controller, it works fine

It should work without any issue.
But I think you are making 2 different requests
In ajax config you specified -> type: "POST" and you are listening for get request
May be you just need to change Route::get -> Route::post
Now it should work expected.
If any doubts please comment.

The AJAX framework only works on the CMS controller or Backend controllers (controllers extending backend/classes/controller). If you're wanting to send data via AJAX without using the built in AJAX framework, then we would have to see more information from your console / network tab of your browser dev tools to see why exactly it's failing.

Related

404 (Not Found) file, request using laravel with jQuery Ajax

I'm currently working on a migration from native PHP to laravel.
The issue is when I try to make a request through Jquery Ajax:
console.log("Join Save TOken Func");
jQuery.ajax({
type: "POST",
url: "/app/controllers/router.php",
data: { controller: 'api_token', action: action, token: Token, token_name: Token_name, expire_date: Expire_date, permissions: Permissions },
cache: false,
success: function(r) {
...
The console log returns:
POST http://127.0.0.1:8000/app/controllers/router.php 404 (Not Found)
I have this Js file in the directory:
public\assets\js
I had some issues accessing to other paths different to the /public path, and not sure if this problem is related, because my "router" file is located in:
app\controllers\router.php
you can't access the controller manually from file js or blade, you must use routes on folder routes/web.php to access the controller
if you want to access that controller you must declare this on your routes/web.php
use App\Http\Controllers\router;
Route::POST('/router',[router::class,'index']);
//you can replace 'index' with your function name on laravel
and to access that controller with this
http://127.0.0.1:8000/router
in your situation i think you should read this documentation
https://laravel.com/docs/9.x/eloquent-resources
and this
https://laravel.com/docs/9.x/urls#urls-for-named-routes

How to get form data into laravel 5.6 controller that posted with OPTIONS method

I am creating APIs into laravel 5.6 for angular.
Form data is sending to API with OPTIONS method.
How can I get this data into the controller?
I have tested like this.
jquery ajax
$.ajax({
url:'domain.com/laravel_app/api/register_user',
type:"options",
dataType:'json',
data:{name:'Joe'},
success:function(r)
{
console.log(r);
}
})
Laravel route
Route::match(['post', 'options'], '/register_user/', 'UserController#register_user');
Laravel controller
public function register_user(Request $request)
{
print_r($request->all());
$arr1['status']='SUCCESS';
return json_encode($arr1);
}
All is working fine with "post" method but not with "options"
This seems to be an issue with jQuery ignoring the spec on the OPTIONS verb and sending your data as the request body.
You should be able to bypass this by doing:
$.ajax({
url:'domain.com/laravel_app/api/register_user?'+$.param({name: 'Joe'}),
type:"options",
dataType:'json',
success:function(r)
{
console.log(r);
}
})
However keep in mind that according to the spec:
The HTTP OPTIONS method is used to describe the communication options for the target resource.
What you are using this request here does not seem to be used to describe communication options for the target resource so you should not be using the OPTIONS method for this.

Wordpress REST API custom endpoint for method POST

I am currently working on a project which requires a WordPress website and a simple REST api. I discovered that WordPress has its own REST api and decided to extend its functionality to meet my needs. All I need to do is to have endpoints for GET and POST requests that retrieve/insert data from/to a table which is not directly related to WordPress (but in the same database). I successfully implemented all GET requests, however, I am struggling to get the POST ones working.
I have this route register defined:
register_rest_route('api/v1', 'create-player/', array(
'methods' => 'POST',
'callback' => 'create_player',
));
The client sends a request through ajax call which is expected to hit the endpoint from the route above. This is the ajax:
$.ajax({
method: "POST",
url: '/wp-json/api/v1/create-player/',
data : JSON.stringify(data),
contentType: 'applcation/json',
beforeSend: function (xhr){
xhr.setRequestHeader("X-WP-None", locData.nonce);
console.log('beforeSend');
},
success: function(response){
console.log("success" + response);
},
fail: function (response){
console.log("fail" + response);
}
});
I am not sure how to build the POST route register from the REST api, the other GET requests have an attribute args that map directly to the parameters passed in the endpoint. Do I need something like that to handle the request data when using POST? How do I get the data type passed from the ajax and then use it in my function create_player(); The WP REST API documentation seems to be incomplete and all of the information I found uses endpoints for built-in WordPress features such as posts/authors/blogs etc. but I don't need that, I just want to use the provided functionality and create my own interface. Thank you.
in your callback function you can use something like this:
$param = $request->get_param( 'some_param' );
// You can get the combined, merged set of parameters:
$parameters = $request->get_params();
https://www.coditty.com/code/wordpress-api-custom-route-access-post-parameters
Finally found it! In order to access the body of the POST request use $request->get_body(); in your register_rest_route callback method.
Add POST in methods while registering route and in your callback function access your POST variables via $request array. That's it.

AJAX calls to HTTP in Angular

I have an existing application that Im moving to Angular and I have some questions. My new Angular app has four routes:
Home
Activity
Login
Signup
In my old app I had AJAX calls to PHP that would query MySQL and return the information as needed, but I could tie everything together using jQuery and call my AJAX calls from one centrally located .js file.
Now, I need to write a call to $HTTP to do the same thing as my AJAX calls did, but I dont know where to put everything!
For example I have the following sample $HTTP function I found online:
<script>
var app = angular.module('myApp', []);
app.controller('myCtrl', function($scope, $http) {
$http.get("users.php")
.then(function(response) {
$scope.users = response.data;
});
});
</script>
Where does this go in the Angular file structure? I intend to call it from the Activity route, which creates another question. Since the route pages are based on templates how do I call the function from the route or template so I can see the results on the Activity page?
Factory/Service is what you are looking for. Ajax call should be made inside a factory method which in turn returns the data to the controller (myCtrl in your example).
You should bind your controller (myCtrl) with the view (Activity) in the route provider itself.
Here is an example that will give you a clear picture.
How factory works

How to link Javascript file to the model folder in Zend

Ok so Ive got this Javascript file, simply:
$(document).ready(function() {
$('.status').prepend("<div class='score_this'>(<a href='#'>score this item</a>)</div>");
$('.score_this').click(function(){
$(this).slideUp();
return false;
});
$('.score a').click(function() {
$(this).parent().parent().parent().addClass('scored');
$.get("/js/Rating.php" + $(this).attr("href") +"&update=true", {}, function(data){
$('.scored').fadeOut("normal",function() {
$(this).html(data);
$(this).fadeIn();
$(this).removeClass('scored');
});
});
return false;
});
});
Where it says /js/Rating.php, that file is in application/modules/recipes/models/Rating.php, this is because it contains some Zend logic that cant be accessed outside the application.
Through the Controller. That is the only reasonable way.
Remember JavaScript is executed on the client side, not the server. You placed your models outside the publicly accessible webroot, because your users are supposed to access your MVC app (e.g. the domain logic in the Rating model) through your app's FrontController and not on the Model directly.
In other words, since .get() issues an Ajax Request, you should direct this request to the Ratings controller in your app and make the Ratings controller call the appropriate model in your application. The model returns something to the controller and the controller then returns this result to the client.
Example:
$.get("/rating/update/someParamId/someParamValue");
This assumes you are using the default rewrite rules. In your controller you could then do $this->getRequest()->getParam('someParamId') and it would contain 'someParamValue'. The controller will return the ViewScript usually rendered by the action back to the client, so you might want to disable the layout to just return the HTML fragment.

Categories