"How to fix 'Ajax request getting a 419 unknown status" (solved) - javascript

I am using laravel homestead. I am making a game that requires credits on the account of which it is played on. I want to make sure that after every play the credits of the user gets updated through an ajax request, however with this ajax request, I get the same error which is PATCH http://gamesite.test/updateBalance/13 419 (unknown status) if I change the data it gets the error: The GET method is not supported for this route. Supported methods: PATCH.
I already tried to change the methods of the ajax request and it is working on other pages.
The ajax request that I made is the following:
$(oMain).on("save_score", function(evt,iMoney) {
if(getParamValue('ctl-arcade') === "true"){
parent.__ctlArcadeSaveScore({score:iMoney});
}
//...ADD YOUR CODE HERE EVENTUALLY
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: 'updateBalance/'+{{ auth()->user()->id }},
type: 'PATCH',
data: {iMoney:iMoney, _method: "PATCH"},
success: function(res) {
}
});
});
I expected that it would update the users credits, instead got the error: "PATCH http://gamesite.test/updateBalance/13 419 (unknown status)"
EDIT:
Route:
Route::patch('/updateBalance/{id}', 'GamesController#updateBalance');
GamesController:
public function updateBalance(User $id) {
$selecteduser = User::find($id)->first();
$this->validate(request(), [
'credit' => 'int'
]);
$selecteduser->credit = request('iMoney');
$selecteduser->save();
}

Found the answer, I needed to add
to the header in the blade.

use HTTP default GET method, this works fine.
$.get (url, {iMoney:iMoney, _method: "PATCH"} , function(){
//success
})

Related

Ionic v1 AngularJS $http POST request not working

I'm trying to send a POST request to a rest API, but I don't seem to able to do it correctly, I don't know if it's the syntax, or what it could be, I've tried many different ways but nothing seems to work. Here's is some pictures of the service being consumed by POSTMAN (everything works fine here).
The Headers
And the body with the response
But then when I try to consume the service via AngularJS, it keeps sending me erros messages, the localhost server even detects that there is a request, because I can see it on the Eclipse's console, but it doesn't run through the debugger with togglebreakpoints and it does with POSTMAN.
This is one of the many attempts to send a $http request
var json = { practiceId: 1 };
$http({
method: "POST",
url: "https://localhost/GetAppointmentTypes",
data: JSON.stringify(json),
headers: {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
}
})
.success(function(data) {
$ionicPopup.alert({
title: 'WORKING'
});
})
.error(function (errResponse, status) {
if(status == 403){
$ionicPopup.alert({
title: '403'
});
}
});
But then
And here is another attempt
var url = 'https://localhost/GetAppointmentTypes';
var parameter = JSON.stringify({practiceId:1});
var headers = {
"Content-Type": "application/json",
"AERONA-AUTH-TOKEN": $window.localStorage['token']
};
$http.post(url, parameter, headers).then(function(response){
$ionicPopup.alert({
title: 'WORKING'
});
}, function(response){
$ionicPopup.alert({
title: ' NOT WORKING '
});
});
And the response
Note: the $window.localStorage['token'] is working correctly. I have tried so many things I don't even know what I'm doing wrong now, might be a syntax error, but then ERROR 403 wouldn't be showing.
EDITED (ADDED)
And the Response Variable

Laravel Using AJAX to pass Javascript variable to PHP and retrieve those

How can I use Ajax to pass a Javascript variable to Php and retrieving those?
I am using a Jquery Ui Slider and on each slide I want to pass the javascript slider value to php so to say.
I have no ( not much ) experience in Ajax and really appreciate help.
This is how my slider looks:
$("#sliderNumCh").slider({
range: "min",
min: 0,
max: 20,
step: 1,
value: numbersOfChapters,
change : function(e, slider){
$('#sliderAppendNumCh').empty();
var i = 0;
var sliderValue = slider.value;
var getSliderVal = document.getElementById('sliderValue').value = sliderValue;
$.ajax({
type: 'POST',
url: '',
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
value: getSliderVal
},
success: function (option) {
console.log(getSliderVal);
}
});
...
}
})
My route example:
Edit my route looks like this now:
Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController#editProduct']);
Edits what I have tried:
url: '{{ route("editProductWeb") }}',
and got this error:
POST http://localhost/myApp/public/product/edit/%7BproductID%7D 500 (Internal Server Error)
and tried this:
url: 'edit',
and got this error:
POST http://localhost/myApp/public/product/edit 500 (Internal Server Error)
Edit my edit controller method:
public function editProduct($productRomID = 0)
{
$product = ProductRom::find($productID);
$sheets = Chapters::where('product_id', '=', $productID)->get();
$productId = $product->id;
$sheetCount = count($sheets);
return view('product.edit', [
'productId' => $productId,
'product' => $product,
'sheets' => $sheets,
'sheetCount' => $sheetCount,
'type' => 'edit',
'route' => 'updateProductRom'
]);
}
Edit using haakym suggestion so far:
$.ajax({
type: 'post',
url: "{{ Route('editProduct', $product->id) }}",
headers: {'X-Requested-With': 'XMLHttpRequest'},
data: {
value: getSliderVal,
productId : getPrId
},
success: function (option) {
console.log(getSliderVal);
}
});
does print me the id + the current slider value in my debug, so that works so far. Now I need to get that value and use it in my view(php) any suggestion how to proceed?
using this in my controller method:
$sliderValue = $request->input('value');
returns me
null
Edit I also tried this:
$sliderValue = Input::get('value');
which also returned me
null
Edit I added a Log:
Log::info(Input::all());
This shows the correct slider value and product id on slide.
But my Input::get('value') still returns me null
Edit I think I should add this information:
I changed my routes to this now:
Route::get('edit/{productID}', ['as' => 'editProduct', 'uses' => 'ProductController#editProduct']);
Route::post('edit/{productID}', ['as' => 'editProductPost', 'uses' => 'ProductController#editProductPost']);
The get shows the data from the database for a specific product and shows them in my view, I added the post one to post the slidervalue data to the editProductPost method and returns afterwards the value(sliderValue) in the edit view, is this correct?(Btw still does not work)
EDIT
If I put this in my controller method:
if ($request->isMethod('post')){
return response()->json(['response' => 'This is post method']);
}
return response()->json(['response' => 'This is get method']);
I keep getting the following error (if I slide):
POST http://localhost/myApp/public/product/edit/54 500 (Internal
Server Error)
I have this in my head:
<meta name="csrf-token" content="{{ csrf_token() }}">
and put this before my ajax post:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
EDIT:
Doing this returns the correct current slider value in the logs:
Log::info($request->get('value'));
I tried this:
return view('productRom.edit', [
'value' => $value,
]);
But I get an error in the console:
Failed to load resource: the server responded with a status of 500
(Internal Server Error) http://localhost/myApp/public/product/edit/73
As #julqas stated you need to include the URL in your $.ajax() method.
As you have a named route editProduct, you can output the link using blade:
$.ajax({
type: 'POST',
url: '{{ route("editProduct" }}',
...
Edit 1:
Your route is get and your ajax method is post, I guess this is the issue. You need to make them the same.
If you change the route to post you will need to add the CSRF token to the ajax request when it is sent. There is some guidance on the docs how to do this here:
https://laravel.com/docs/5.2/routing#csrf-x-csrf-token
The docs recommend adding this in your HTML head:
<meta name="csrf-token" content="{{ csrf_token() }}">
then use the following code before sending the request:
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
alternatively you can add it to the request in the ajax call.
Edit 2
A side point - I was just guessing what the error is, it would have been better if I'd asked you if you could debug it yourself in order to see what the error was. Learning to debug ajax requests is very useful and not too difficult.
The best way to do that is by using the developer console in your browser of choice when making the ajax request. If you're using Chrome for example open Developer tools and then click on the Network tab before making your request. After making the request you can inspect the request and its details. Hope that helps!
Edit 3
I would change your editProduct() method to not accept any parameter and instead get the id value for the product from the request
public function editProduct()
{
// value here is referring to the key "value" in the ajax request
$product = ProductRom::find(\Request::get('value');
...
}
Consider changing the value key in your json to something more useful, such as productId
data: {
productId: getSliderVal
}
you haven't entered value for 'url'. Create any route then put it in url:'{any_route_name}' and then check in console weather your value has been posted or not
You have to do some R&D at your level for this .

Using Emotion API for Video (Javascript or Ruby)

So I'm working on posting a video to the Emotion API for video and I haven't been able to get a response.
I've been able to get it to work on the Microsoft online console, but when I try to implement it in my Rails app using (1) JavaScript Ajax, or (2) Ruby server-side code, I consistently get various errors.
Here's my code. At first I tried to Ajax way, but I had a suspicion that the API doesn't have CORS enabled. So then I tried Ruby, to no success.
Ruby attempt:
def index
uri = URI('https://api.projectoxford.ai/emotion/v1.0/recognizeinvideo')
uri.query = URI.encode_www_form({
})
data = File.read("./public/mark_zuck.mov")
request = Net::HTTP::Post.new(uri.request_uri)
# Request headers
request['Ocp-Apim-Subscription-Key'] = 'e0ae8aad4c7f4e33b51d776730cff5a9'
# Request body
request.body = data
request.content_type = "video/mov"
response = Net::HTTP.start(uri.host, uri.port, :use_ssl => uri.scheme == 'https') do |http|
http.request(request)
end
puts response.body
end
Here's my Ajax attempt:
function CallAPI(apiUrl, apiKey){
console.log("API called");
$(".loading").css("display", "inline-block");
$.ajax({
url: apiUrl,
beforeSend: function (xhrObj) {
xhrObj.setRequestHeader("Content-Type", "application/octet-stream");
xhrObj.setRequestHeader("Ocp-Apim-Subscription-Key", apiKey);
},
type: "POST",
data: '{"url": "http://localhost:5000/mark_zuck.mov"}',
processData: false,
success: function(response){
console.log("API success");
ProcessResult(response);
$(".loading").css("display", "none");
console.log(response);
},
error: function(error){
console.log("API failed");
$("#response").text(error.getAllResponseHeaders());
$(".loading").css("display", "none");
console.log(error);
}
})
Yes, I've regenerated my key. This is just to illustrate my point.
So you have to set Content-Type to application/octet-stream if it's a binary file you're sending, like I was.
If you use a url you should set Content-Type to application/json and the url must be publicly available.

Why does this AJAX POST fails with elasticsearch? [duplicate]

I am trying to send an Ajax POST request using Jquery but I am having 400 bad request error.
Here is my code:
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
},
error: function(e) {
console.log(e);
}
});
It Says: Can not build resource from request.
What am I missing ?
Finally, I got the mistake and the reason was I need to stringify the JSON data I was sending. I have to set the content type and datatype in XHR object.
So the correct version is here:
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: JSON.stringify({
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}),
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
May be it will help someone else.
In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.
It turned out to be the anti forgery token.
$.ajax({
url: "/Cart/AddProduct/",
data: {
__RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
productId: $(this).data("productcode")
},
The problem was that the .Net controller wasn't set up correctly.
I needed to add the attributes to the controller:
[AllowAnonymous]
[IgnoreAntiforgeryToken]
[DisableCors]
[HttpPost]
public async Task<JsonResult> AddProduct(int productId)
{
The code needs review but for now at least I know what was causing it. 400 error not helpful at all.
Yes. You need to stringify the JSON data orlse 400 bad request error occurs as it cannot identify the data.
400 Bad Request
Bad Request. Your browser sent a request that this server could not
understand.
Plus you need to add content type and datatype as well. If not you will encounter 415 error which says Unsupported Media Type.
415 Unsupported Media Type
Try this.
var newData = {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work", "facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
};
var dataJson = JSON.stringify(newData);
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: dataJson,
error: function(e) {
console.log(e);
},
dataType: "json",
contentType: "application/json"
});
With this way you can modify the data you need with ease. It wont confuse you as it is defined outside the ajax block.
The question is a bit old... but just in case somebody faces the error 400, it may also come from the need to post csrfToken as a parameter to the post request.
You have to get name and value from craft in your template :
<script type="text/javascript">
window.csrfTokenName = "{{ craft.config.csrfTokenName|e('js') }}";
window.csrfTokenValue = "{{ craft.request.csrfToken|e('js') }}";
</script>
and pass them in your request
data: window.csrfTokenName+"="+window.csrfTokenValue
You need to build query from "data" object using the following function
function buildQuery(obj) {
var Result= '';
if(typeof(obj)== 'object') {
jQuery.each(obj, function(key, value) {
Result+= (Result) ? '&' : '';
if(typeof(value)== 'object' && value.length) {
for(var i=0; i<value.length; i++) {
Result+= [key+'[]', encodeURIComponent(value[i])].join('=');
}
} else {
Result+= [key, encodeURIComponent(value)].join('=');
}
});
}
return Result;
}
and then proceed with
var data= {
"subject:title":"Test Name",
"subject:description":"Creating test subject to check POST method API",
"sub:tags": ["facebook:work, facebook:likes"],
"sampleSize" : 10,
"values": ["science", "machine-learning"]
}
$.ajax({
type: 'POST',
url: "http://localhost:8080/project/server/rest/subjects",
data: buildQuery(data),
error: function(e) {
console.log(e);
}
});
I'm hoping this may be of use to those encountering 400 errors while using AJAX in Wordpress going forward. Even though this question is many years old, the solutions provided have all been programmatic, and I'm sure many have stepped through their code to repeatedly find it's correct, yet continue to find it is not working.
I found dozens of results asking how to resolve "WP AJAX request returning 400 Bad Request" or "WP AJAX request returning 0" and nothing today worked.
Googling "How do I fix 400 bad request on Wordpress?" finally resulted in the answer appearing from https://wp-umbrella.com/troubleshooting/400-bad-request-error-on-wordpress/
Clear your Web Browser Cache and Cookies
You may be surprised, but most 400 errors in WordPress can be fixed by clearing your browser's cache and cookies. Browser caches temporarily store images, scripts, and other parts of websites you visit to speed up your browsing experience.
Clearing both my cache and cookies saw the 400 Bad Request code disappear and results return AJAX results as expected.

How to send ajax request when I process data from request before?

At start of my app I need to send three ajax get (Dojo xhrGET ) requests, but problem is that I need to send second when I process data from first and send third when I process data from second ( order is important ! ). I put this requests one behind other but it sometimes doesn't work. How to synchronize and solve this, is there any way to lock or wait like in Java ?
If you're using 1.6, check out the new Promises API (returned by dojo.xhrGet), or use deferreds in 1.5. They provide a 'neater' way to achieve this.
Essentially you can write:
dojo.xhrGet({
url: './_data/states.json',
handleAs: 'json'
}).then(
function(response) {
// Response is the XHR response
console.log(response);
dojo.xhrGet({
url: './_data/'+response.identifier+'.json',
handleAs: 'json'
}).then(
function(response2) {
// The second XHR will fail
},
// Use the error function directly
errorFun
)
},
function(errResponse) {
// Create a function to handle the response
errorFun(err);
}
)
var errorFun = function(err) {
console.log(err);
}
See http://dojotoolkit.org/documentation/tutorials/1.6/deferreds/ and http://dojotoolkit.org/documentation/tutorials/1.6/promises/ for more information
You can use option sync = true, and put the request one behind other. With this, 3rd will be sent after 2nd after 1st.
Or you can begin send 2nd request after 1st is done by using load function.
Example:
dojo.xhrGet({ //1st request
load: function(){
dojo.xhrGet({ //2nd request
load: function(){
dojo.xhrGet({ //3nd request
});
}
});
}
});
For more information: http://dojotoolkit.org/reference-guide/dojo/xhrGet.html
Can we make the second ajax request in the success callback method of the first request:
$.ajax({
'type' : 'get', // change if needed
'dataType' : 'text', // data type you're expecting
'data' : { 'className' : divClass },
'url' : url,
'success' : function(newClass) {
//make the second ajax request...
}
});
And do the same thing for the third request.

Categories

Resources