Json giving 301 Moved Permanently - javascript

on Firefox, only on firefox it will popup and give you a warning "This web page is being redirected to a new location. Would you like to resend the for form you have typed to the new location."
I got no form , i use javascript to extract values from textbox
I checked on firebug it says
PUT /admin/submit-scan/ 301 moved permanently
PUT submit-scan 302 Found
My JS
function submitGoods(){
var registeredNo = $('input[name=registeredno]').val();
var weight = $('input[name=weight]').val();
$.ajax({
type: 'PUT',
url: '/admin/submit-scan/',
data: {
registeredNo: registeredNo,
weight: weight,
_token: csrfToken
},
dataType: 'json'
}).done(function(data){
data = $.parseJSON(data);
});
}
My Route
Route::put('submit-scan', 'Controllers\Admin\DashboardController#putUpdateSubmitScan');
My controller
public function putUpdateSubmitScan()
{
if (Request::ajax())
{
return Response::json(array('success' => 1, 'data' => "test"));
}
}
Any idea what went wrong?

Removing the trailing slash should do the trick (most probably prior to Laravel 4.1, see below).
url: '/admin/submit-scan'
Update
As mentioned in Laravel4 POST unexplained redirect to GET
Laravel bootstrap/start.php is calling $app->redirectIfTrailingSlash(); which seems to be the culprit. This has been changed in Laravel 4.1:
http://laravel.com/docs/upgrade#upgrade-4.1

Related

Cookies not being sent on cross-sub-domain request on an api call

I have a page stored on https://page.domain.com.
Here, I'm using javascript (mainly Bootstrap) to get data from https://api.domain.com.
The first call, when the page is loaded, is a "sort of" authentication call which return a cookie in the headers:
set-cookie: oauth=emd4YWgybTJobmJnZjVrbXl2ZjdlZThiOzkzczg1YWt2YzNyZW42cjk3M2U4dXlweA==; domain=.domain.com; path=/; expires=Fri, 16 Apr 2021 11:58:07 GMT;
I can see in the developer tools (Chrome) that the cookie is stored correctly.
But then, when I make the next api call (example, filling a dropdown list - bootstrap autocomplete ) the cookie is not in the request.
This was working fine when I was building it in localhost (same "domain", I guess) but now, having the html and the apis running on different domains, it seems cookies are not being shared.
I thought it could be because of the two different domains, but according to the documentation, when a cookie is set to the main domain, all sub-domains should be able to share it. (also, I' including the "withCredentials" flag)
This is the code of the initial call (and setting up the subsequent one):
$.ajax({url: 'https://api.domain.com/get-cookie',
xhrFields: {
withCredentials: true
}
})
.done(function (response) {
$('.selectpicker').selectpicker().ajaxSelectPicker({
ajax: {
// data source
url: 'https://api.domain.com/data.json',
// ajax type
type: 'GET',
// data type
dataType: 'json',
// Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
// automatically replace it with the value of the search query.
data: {
q: '{{{q}}}'
}
},
// function to preprocess JSON data
preprocessData: function (data) {
var i, l = data.length, array = [];
if (l) {
for (i = 0; i < l; i++) {
array.push($.extend(true, data[i], {
text : data[i].name,
value: data[i].code,
data : {
subtext: data[i].code
}
}));
localStorage.setItem(data[i].code, data[i].name);
}
}
// You must always return a valid array when processing data. The
// data argument passed is a clone and cannot be modified directly.
return array;
}
});
}
);
I'm using AWS API Gateway and Lambda functions, but that should not be relevant...
When taking the url from the selectPicker (eg: https://api.domain.com/data.json ) and putting it directly in the browser I see the cookie being sent.
This seems to indicate the issue might be in the Bootstrap Select component that is not sending the headers correctly.
I'm not sure if I can make it work as expected or I have to find some other alternative.
The solution was to also include the withCredentials on the selector request:
$('.selectpicker').selectpicker().ajaxSelectPicker({
ajax: {
// data source
url: 'https://api.domain.com/data.json',
// ajax type
type: 'GET',
// data type
dataType: 'json',
// Use "{{{q}}}" as a placeholder and Ajax Bootstrap Select will
// automatically replace it with the value of the search query.
data: {
q: '{{{q}}}'
},
xhrFields: {
withCredentials: true
}
},
// function to preprocess JSON data
preprocessData: function (data) {
// ...
}
});
}
);
Thanks #CBroe for the idea in the comments.

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 .

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.

Ajax post not received by php

I have written a simple code. In order to avoid flooding a JSON server, i want to break up the JSON response in pieces. So my jquery code should be parsing one variable ("page") to the php page that handles the JSON Oauth Request. On success, it should append the DIV with the latest responses.
My code should be working, except for the fact that my ajax post is not being received by my php file.
Here goes
archief.html
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: page,
success: function() {
console.log(page);
$.get("trytocombinenewageandgettagsendates.php", function(archief) {
$('#archief').append(archief);
});
},
error: function(err) {
alert(err.responseText);
}
});
return false;
});
The php file doesn't receive anything.
var_dump($_POST);
gives me array(0) { }.
Very strange, i'd really appreciate the help!
You are sending a string instead of key-value pairs. If you want to use $_POST you need to send key-value pairs:
...
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function() {
...
If you send a single value or string, you would need to read the raw input.
Also, you are sending 2 GET requests and 1 POST request to the same file. Is that intentional? Note that only the POST request will have the $_POST variable set.
Thank you for your help and not letting me post "this still doens't work" posts :)
I made the mistake of loading the "unConsulted" php file [$.get("trytocombinenewageandgettagsendates.php"] upon success. Instead, i append the response of the PHP.
The working code below:
$("#klik").click(function() {
console.log("fire away");
page = page + 1;
//$("#archief").load("trytocombinenewageandgettagsendates.php");
console.log(page);
$.ajax({
type: 'POST',
url: "trytocombinenewageandgettagsendates.php",
data: { 'page': page },
success: function(response){
$("#archief").append(response);
},
error: function(err) {
alert(err.responseText);
}
});
return false;

Calling a C# method from JavaScript

I want to to call a method GetAccount from my controller AccountController.cs, in my JavaScript factory LoginFactory.js. Something like this:
AccountController.cs:
public Account GetAccount(string userName)
{ ... }
LoginFactory.js:
if(x>y) {
var account = <%AccountController.GetAccount(someParam);%>
}
I've tried using [WebMethod] and Ajax, but I can't get it to work: I get a 404 response.
Assuming your GetAccount method can be reached at /Account/GetAccount when your application runs, you could use the following:
$.ajax({
type: 'GET',
url: '/Account/GetAccount',
data: { 'username' : 'a-username' },
dataType: 'json',
success: function(jsonData) {
alert(jsonData);
},
error: function() {
alert('error');
}
});
Note - this is dependant on jQuery.
This causes the browser to make a request to /Account/GetAccount as if you had done so by entering the URL in the URL bar, but of course, captures the returned json for use in your client side (javascript) script.
If this returns a 404, it would be worth checking your routing.

Categories

Resources