I am trying to update a JSON object (e.g: customer). But, I have the following error:
"NetworkError: 405 Method Not Allowed - http://prestashop/api/..."
This is my code (index.js):
var testWebService = angular.module('testWebService', []);
testWebService.controller('testWebServiceCtrl', function ($scope, $http) {
var $baseDir = "http://prestashop/api";
var $objectDir = "customers";
var $idObjectDir = "1";
var $keyDir = "F517VWPRREG7TA25DEY8UIZT8V79E5OV";
var $urlDir = $baseDir + "/" + $objectDir + "/" + $idObjectDir + "?ws_key=" + $keyDir + "&output_format=JSON";
// TEST DE LA METHODE PUT SUR L ID D UN CUSTOMER
$.ajax({
type: "PUT",
url: $urlDir,
dataType: "json",
async: false,
contentType: "application/json; charset=utf-8",
data: {"id": "93"},
crossDomain: true,
success: function () {
console.log("Ok PUT");
},
error: function() {
console.log("Erreur PUT");
}
});
});
Before, I tried to GET the id of an object (same: customer) and I succeeded with an almost similar method.
I precise that I gave rights about "customer" in Advanced Settings / webservice (for method GET, PUT, POST ...).
Thanks in advance for your help, I tried so many things, but whitout success.
PS: If you have any suggestion about my code to "clean" it, you were pleased.
My webservice JSON:
{"customer":{"id":1,"id_default_group":"3","id_lang":"1","newsletter_date_add":"2013-12-13 08:19:15","ip_registration_newsletter":"","last_passwd_gen":"2015-06-08 03:38:27","secure_key":"7036cdf99ea12125ad1b3789f298f686","deleted":"0","passwd":"2e372235eb5213bc004ce72bcfef16a2","lastname":"DOE","firstname":"John","email":"pub#prestashop.com","id_gender":"1","birthday":"1970-01-15","newsletter":"1","optin":"1","website":"","company":"","siret":"","ape":"","outstanding_allow_amount":"0.000000","show_public_prices":"0","id_risk":"0","max_payment_days":"0","active":"1","note":"","is_guest":"0","id_shop":"1","id_shop_group":"1","date_add":"2015-06-08 09:38:27","date_upd":"2015-06-08 09:38:27","associations":{"groups":[{"id":"3"}]}}}
EDIT:
When I tried with the method GET, I did:
$.ajax({
type: "GET",
url: $urlDir,
dataType: "json",
async: false,
success: function (data) {
$scope.customer1 = data;
console.log("Ok GET");
console.log(data);
},
error: function() {
console.log("Erreur GET");
}
});
Reading the status code definition of the http protocol, try adding the following property to the ajax request:
$.ajax({
type: "PUT",
...
beforeSend: function (xhr) {
xhr.setRequestHeader("Allow", "GET, HEAD, PUT, DELETE");
},
...
});
PS: If you have CORS disabled on your server, look this answer and set the headers to allow your server access to requests from different origins.
Related
I'm trying to push some data via ajax in Laravel. Unfortunally it does not work. When I was watching at the network traffic, i found this:
Request Method:POST
Status Code:302 Found
I'm trying to get data from a JSGrid, which works fine. The data-object is filled. I checked it. For testing I just returned a short message in my controller. But it's not even called when I send the POST request...
Here is my code
Javascript:
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=token]').attr('content')}
});
$('#save_list').click(function (e) {
e.preventDefault();
var url = '{{ route("account.save_accounts_to_user") }}';
var post = {};
post.account_list = $("#jsGrid").jsGrid("option", "data");
$.ajax({
type: "POST",
url: url,
dataType: 'JSON',
data: post,
cache: false,
success: function (data, textStatus, jqXHR) {
console.log(textStatus + " - " + data);
return data;
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR.responseText + textStatus + " - " + errorThrown);
}
});
return false;
});
Route:
Route::post('save_accounts_to_user', ['as' => 'account.save_accounts_to_user', 'uses' => 'AccountController#saveAccountsToUser']); //ajax request
Controller:
/**
* Save all used accounts for a user.
*
* #param \Illuminate\Http\Request $request
* #return \Illuminate\Http\Response
*/
public function saveAccountsToUser(Request $request)
{
$response = array();
$response["status"] = "ok";
$response["message"] = trans('account.accounts_saved');
return \Response::json($response);
}
I was expecting that I will get the JSON text from the controller method as the responsemessage. But instead i get redirected without calling the wanted method.
I don't know what happens there. There is no middleware assigned to this route, which could be the reason for this redirect.
Do you have an ideas?
After all it was a middleware of an outter group which was redirecting the request -.-
May be 'X-CSRF-Token' used by you instead of 'X-CSRF-TOKEN' mentioned in Laravel docs is the issue here? Try to follow the Laravel docs completely.Please refer below link.
https://laravel.com/docs/5.3/csrf
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
add this code:
$.ajaxSetup({
headers: {'X-CSRF-Token': $('meta[name=token]').attr('content')}
});
after this:
var url = '{{ route("account.save_accounts_to_user") }}';
Use headers in AJAX call
Example:
$.ajax({
type: "POST",
url: link, // your link
data: DataObject, // data to pass
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
success: function (result) {
}
});
I want to use jQuery POST method to call an xsjs service that does some modifications in Database.My xsaccess file prevents xsrf, so I need to handle it in my controller method.
Below is my controller code-
var obj= {};
obj.name= "John";
obj.age= "abc#xyz.com";
obj.loc= "Minnesota";
jQuery.ajax({
url: "serviceTest.xsjs",
type: "GET",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", "Fetch");
},
success: function(responseToken, textStatus, XMLHttpRequest) {
var token = XMLHttpRequest.getResponseHeader('X-CSRF-Token');
console.log("token = " +token);
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
xhr.setRequestHeader("X-CSRF-Token", token);
},
success : function(response) {
// will be called once the xsjs file sends a
response
console.log(response);
},
error : function(e) {
// will be called in case of any errors:
var errMsg = e.responseText
console.log(e);
}
});
},
And here is my xsjs code-
var csrf_token = $.request.headers.get("X-CSRF-Token");
if(csrf_token === "Fetch") {
var content = $.request.body.asString();
var args = $.parseJSON(content);
var xsName= args.name;
var xsemail= args.email;
var xsLoc= args.loc;
//then execute DML statement by passing these 3 parameters as arguments.
catch (error) {
$.response.setBody(content);
$.response.status = $.net.http.INTERNAL_SERVER_ERROR;
}
I am not able to do the update and getting error Err 500 - Internal server Error.
Any suggestions would be extremely helpful
Edit:
If I forgot the token then I got a 403 Access denied error ("CSRF token validation failed") and not a 500 internal. So I think something is wrong with your services
You can add your X-CSRF-Token as header of your POST request with setup your ajax requests before your fire your POST.
$.ajaxSetup({
headers: {
'X-CSRF-Token': token
}
});
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
beforeSend: function(xhr) {
Otherwise add it to each POST request.
jQuery.ajax({
url: "serviceTest.xsjs",
type: "POST",
data: JSON.stringify(obj),
headers: {
'X-CSRF-Token': token
},
beforeSend: function(xhr) {
Your way with using beforeSend event should work too.
For example, I'm currently implementing client side javascript that will use a POST if the additional parameters exceed IE's safety limit of 2048ish charachers for GET HTTP requests, and instead attach the parameters to the body in JSON format. My code looks similar to the following:
var URL = RESOURCE + "?param1=" + param1 + "¶m2=" + param2 + "¶m3=" + param3();
if(URL.length>=2048) {
// Use POST method to avoid IE GET character limit
URL = RESOURCE;
var dataToSend = {"param3":param3, "param1":param1, "param2":param2};
var jsonDataToSend = JSON.stringify(dataToSend);
$.ajax({
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
});
}else{
// Use GET
$.ajax({
type: "GET",
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("GET error");
},
success: function(data) {
alert("GET success");
}
});
}
Is there a way of me avoiding writing out this ajax twice? Something like
if(URL.length>=2048) {
// Use POST instead of get, attach data as JSON to body, don't attach the query parameters to the URL
}
N.b. I'm aware that using POST instead of GET to retrieve data goes against certain principles of REST, but due to IE's limitations, this has been the best work around I have been able to find. Alternate suggestions to handle this situation are also appreciated.
The $.ajax method of jQuery gets an object with properties. So it's quite easy, to frist generate that object and a "standard setting" and modify them based on certain logic and finally pass it to one loc with the ajax call.
Principle:
var myAjaxSettings = {
type: "POST",
data: jsonDataToSend,
dataType: 'json',
url: URL,
async: true,
error: function() {
alert("POST error");
},
success: function(data) {
alert("POST success");
}
}
if ( <condition a> )
myAjaxSettings.type = "GET";
if ( <condition b> )
myAjaxSettings.success = function (data) { ...make something different ... };
$.ajax(myAjaxSettings);
I have to issues:
1) I've tried using JsonP, but can't get POSTing to work. Essentially, I'm trying to authenticate with an API, passing a Base64-encoded namevaluepair in the header over HTTPS.
2) How do I pass this key/value in the header? Any help would be appreciated! Here is an example of what I want, though this obviously doesn't work:
// where does this go?
var headerString = 'user=' + encodeURIComponent(username + ':' + password);
$.ajax({
type: "POST",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
success: function(data) {
},
error: function(data){
}
});
add headers to ajax call:
var headerObj = {'user': encodeURIComponent(username + ':' + password)};
$.ajax({
type: "GET",
url: "https://anotherurl.on.another.server/LOGIN",
data: "I have no data, I'm logging in with header authentication",
dataType: "json",
headers: headerObj,
success: function(data) {
},
error: function(data){
}
});
The best way to do this is probably through a server side proxy on your own domain.
See this page for tips.
This way you will be able to get the response from the other server
I am trying to post a request to the google authSub for youtube. I use jQuery for AJAX posts etc. When I make the POST I get a 405 error: "405 Method Not Allowed".
Here is my js:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
},
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
});
The page I am using in the API for this is here.
Here is what the error looks like:
Your data parameters for the request are misplaced see below:
$.ajax({
type: 'POST',
url: "https://www.google.com/accounts/AuthSubRequest",
data: {
scope: 'http://gdata.youtube.com',
alt: 'json',
next: 'http://' + globalBrand + '/sitecreator/view.do',
session: 1
},
beforeSend: function(xhr){
xhr.setRequestHeader('X-GData-Key', 'key="' + ytKey + '"');
},
success: function(oData){
//alert(oData);
}
});
Now it may be something youre doing wrong additionally, but this for sure needs to be corrected.
Ah, here is a solution to the problem. If I make the request with the url built out and assigned as an href to an anchor or call it in window.open(); it works.
window.open('https://www.google.com/accounts/AuthSubRequest?scope=http://gdata.youtube.com&next=http://' + globalBrand + '/sitecreator/view.do&session=1');
As for why jQuery's method with the ajax was being rejected I know not. It seems to be an issue elsewhere also.
Solution to error HTTP HEADER OPTIONS in JQuery, this request is ok for me:
var word = 'search+word';
$.ajax({
type: "GET",
url: "http://gdata.youtube.com/feeds/api/videos?q="+word+"&max-results=10&alt=json-in-script&format=5,
cache: false,
dataType:'jsonp',
success: function(data){
//json 'data' var treatment
},
error: function(XMLHttpRequest, textStatus, errorThrown, data){
alert("Not able to fetch the data due to feed unavailability!!!");
}
});
Reference: http://www.mohammedarif.com/?p=180