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

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.

Related

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

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
})

Array is flattened when it's sent through AJAX jQuery request

I have the following endpoint written in Express, using the body-parser middleware.
app.post("/api/poll/new",api.NewPoll);
api.NewPoll = function(req,res){
if(!req.body) return res.status(400).send("MISSING BODY");
console.log(req.body,typeof(req.body));
if(!req.body.name) return res.status(400).send("MISSING NAME");
if(!req.body.options) return res.status(400).send("MISSING OPTIONS");
//rest of the endpoint goes here
};
The data that the endpoint expects looks like this:
{
"name":"Poller",
"options":[
{
"name":"Jojo's Bizarre Adventure",
"desc":"A great show"
},
{
"name":"Bakemonogatari",
"desc":"A real good show"
},
}
When I send this data through Postman, everything works. req.body.options exists and is an array. However, when I do the exact same thing in a jQuery AJAX call, the result is signficantly different:
var payload = {
name:"Poller",
options:g.newPollInfo
//g.newPollInfo contains the same array
}
$.ajax({
method:"POST",
url:"/api/poll/new",
data:payload,
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});
I get a 400 error, reporting missing Options. The printed req.body looks like this:
{ name: 'Poller',
'options[0][name]': 'Jojo'\s Bizarre Adventure',
'options[0][desc]': 'A great show',
'options[1][name]': 'Bakemonogatari',
'options[1][desc]': 'A real good show' } 'object'
I have never had this problem before. The problem is not in express, as a request through Postman using the same data and it works. The only problem I can think of lies in the fact that the request is made from an iframe serviced through a secure connection, but that doesn't make sense.
I have no idea what causes this error.
According to both these questions, the problem is solved specify the header type on the AJAX Request and stringify.
$.ajax({
method:"POST",
url:"/api/poll/new",
data:JSON.stringify(payload),
contentType:"application/json",
success:function(data){
console.log(data);
},
error:function(req, status, error){
console.log(req,status,error);
}
});

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;

Json giving 301 Moved Permanently

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

Loathing IE and it's refusal to respond to JQuery Post

Ladies / Gents:
Doing a $.post which works fine in Chrome & FireFox. IE - not so much...the success callback (addTicketAndRender()) never gets hit:
http://jsfiddle.net/AeQxJ/1/
I've read something about needing to do "cache-busting" against IE with my POST, but I'm relatively new to this stuff so don't know if that's the appropriate thing to try and if so, how to do it.
Source:
function addTicketAndRender(incomingTicket) {
console.log("Add and Render");
alert(incomingTicket);
}
$(document).ready(function() {
console.log('ready');
// variables to feed trusted ticket retrieval
var trustedURL = "http://tableau.russellchristopher.org/trusted",
userName = "foo",
serverURL = "http://tableau.russellchristopher.org/";
$.post(trustedURL, {
username: userName,
server: serverURL,
client_ip: "",
target_site: "",
cache: "false"
}, function(response) {
addTicketAndRender(response);
});
});​
Little help, please?
Update1: Switched this out to an ajax post: No difference. Still good on Chrome and Firefox, still dead in IE:
$.ajax( {
url : trustedURL,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
Update2: Integrated additional cache-busting technique. Same behavior - Chrome/FF works, nothing from IE - Using Fiddler, I can see the POST go out when running the code below from http://jsfiddle.net/AeQxJ/3//. In IE, that never happens. Tested outside of jsfiddle and see the same result. Next step: Rule out stupid IE browser settings on my part by testing on a box where I haven't touched browser settings.
function addTicketAndRender(incomingTicket){
alert(incomingTicket);
}
$(document).ready(function() {
// variables to feed trusted ticket retrieval
var trustedURL = "http://tableau.russellchristopher.org/trusted",
userName = "foo",
serverURL = "http://tableau.russellchristopher.org/";
var number=Math.floor(Math.random()*1);
$.ajax( {
url : trustedURL + "?" + number,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
});​
Update 4: Ruled out my copy of IE as an issue. Added error trapping code to the POST, and ONLY when running in IE, I see this thrown:
error: function(xhr, textStatus, error){
alert(xhr.statusText);
alert(textStatus);
alert(error);
//output:
// xhr.StatusText: No Transport
// testSttus: Error
// error: No Transport
Searching on "IE No Transport jquery POST" leads me here:
jQuery Call to WebService returns "No Transport" error
Post indicates adding jQuery.support.cors = true; should resolve the issue, but when I do, errors are returned:
//output:
// xhr.StatusText: Error: Access is denied
// testSttus: Error
// error: Error: Access is denied
Change
$.post( ...
cache: "false"
...
To:
$.ajax(...
cache: false,
...
Note, The first cache is a meaningless string, while the later is a Boolean false.
If the cache: false is not working for you, the old school way was to add a get parameter to the url, like a random number, so:
var number=Math.floor(Math.random()*1)
$.ajax( {
url : trustedURL + "?" + number,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false
} ).done( addTicketAndRender );
This should help you debugging as well (change from random number to sequential). If still doesnt work I remove .done and use something like complete i.e.
$.ajax( {
url : trustedURL,
type: "POST",
data : {
username : userName,
server : serverURL,
client_ip : "",
target_site : ""
},
cache : false,
complete : function() {
addTicketAndRender
}
});
One last thing, if your doing this using your jsfiddle page, make sure you remove console.log() from your code, as this will cause IE to break (it doesn't understand console.log).
$.post is only a shorthand version of $.ajax() link: http://api.jquery.com/jQuery.post/
If you need more control I suggest using $.ajax() since you have a lot more option with the "native" method. Link: http://api.jquery.com/jQuery.ajax/
Besides a good coding tips concerning jQuery.ajax() is always set $.ajax({cache: false}) somewhere as a default, since IE is (surprise) the only browser with cache: true as default
IE tends to trip on console.log(''); statements. Try to wrap it into a Log() function:
function Log(text) {
try {
console.log(text);
}
catch (e) {
}
}
If that fixes your problem, you'll want to use this approach to using console.log() throughout your project.

Categories

Resources