Post data to RESTful Invalid HTTP status code 405 - ajax

I create a method to post json data to web service :
function WishList() { }
WishList.prototype.addToWishList = function(redirectURL, postURL, userObj) {
$.ajax({
type: "POST",
url: postURL,
data: JSON.stringify(userObj),
dataType: 'json',
contentType: "application/json",
success: function(data){alert(data);},
failure: function(errMsg) {
alert(errMsg);
}
}
This is my object:
var user1 = {
ID:1,
Sex:1,
Name:"titi",
Company:"ABC",
Address:"Phnom Penh",
Email:"test.abc#gmail.com",
Phone:"011123456",
WebAccount:"test.abc#gmail.com",
Password:"123456",
GroupCustomerID:125,
Stars:1,
IsVIP:0,
PriceLevel:1,
LastDateSale:"\/Date(-62135596800000)\/",
TotalCredit:150.12,
AgingData:null,
TotalRedeemPoint:1000.00,
RedeemData:null,
ExchangeRate:155.00,
HistoryData:null
};
Calling function :
$(document).ready(function () {
var myWishList = new WishList();
$('#addToWishList').click(function(){
myWishList.addToWishList('http://www.blahblahblah.com' , 'http://blahblah/Website/Products/Product.svc/Wishlist/' , user1);
});
});
Then I got errors in my console :
"NetworkError: 405 Method Not Allowed in firefox and Invalid HTTP status code 405 , XMLHttpRequest cannot load url in chrome.
Note: When I use Rest Client of Chrome to POST to web service, it worked.
Any help would be much appreciated, thank you.

Not sure what you are using as the service on the other end but this may be due to cross domain posting. I hate to post a link and run but this may be of some use to you.
http://praneeth4victory.wordpress.com/2011/09/29/405-method-not-allowed/
Looks like they could get it working in IE but had some issues as you with the other browsers. Perhaps these couple changes will help access the service better.
This post was good at explaining the error and parts to it as well so if the above link is not helpful this one may help you diagnose the issue further.
http://www.checkupdown.com/status/E405.html
ok ok last edit, just wanted to make sure you have enough info to hopefully resolve your issue, here is a good article on the underlying problem I believe you are having..
http://www.d-mueller.de/blog/cross-domain-ajax-guide/

Related

Shopify order API returns OK but does not update order using JS

I'm trying to create an order using JS. I've authenticated my app and have a function that POST's to orders.json. I see a status code of 200, indicating that the request submitted OK (right?) but the order itself never gets created. I've heard something about disabling cookies in my request, but I don't know how to do that, so if that's what I need to do please let me know.
I'm putting up my entire function, since I'm new to this entire thing and it seems that it's probably the structure of my request, not the API call. I'm seeing the "Error" log in the console, so clearly the error function is running.
function submitShuffle(prodid)
{
console.log(prodid);
var params = {
"order": {
"line_items": [
{
"variant_id": prodid,
"quantity": 1
}
]
}
};
$.ajax({
type: 'POST',
url: 'https://<my-usrnam>:<my-pass>#toyboxshufflesandbox.myshopify.com/admin/orders.json',
dataType: 'application/json',
data: params,
success: function(data){
console.log(data);
},
error: function(data){
console.log("Error");
console.log(data);}
});
}
You cannot retrieve information from Shopify Admin API by AJAX. There is a limitation about this because you have to expose your username/key and password which is not a good idea.
You have to use some service/app or just to create a custom app.
Shopify returns an Object when you make a call. Hence 200 OK status. Inspect the object returned. A failed create POST object will not have an ID. So there is clue number one. Secondly, you'll see that Shopify tells you what the problem was in the Error key of the returned object. If you cannot figure out what you did with the message from Shopify, make the same call to the GraphQL endpoint if you can, as the error messages Shopify returns from those endpoints are currently much better. They are backporting them to the older REST API, but for now, GraphQL is more expressive.

October CMS - API Generator - how to create and update data in database

I try to send data to the database using AJAX and plugin in October CMS called "API Generator".
I can't find in its documentation or in Google anything that will help me.
The code I have is this:
$data = [{'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01', 'departure': '2018-04-03,', 'reservation_type': 'owner'}]
$.ajax({
url: '/api/v1/booking/create',
data: $data,
type: "post"
})
.done(function() {
console.log('Success')
})
.fail(function() {
console.warn('Something went wrong');
});
I don't get any error, in fact, I get 'Success' message in console, but data is not added to the database.
What am I doing wrong?
Please help.
Thanks.
Actually you are doing it little wrong [ You are firing Ajax request at wrong end-point ] that Api Plugin is based on https://laravel.com/docs/5.6/controllers#resource-controllers Resource Controller
So, To create an item you need to fire only POST request to Created Api-End Point. You don't need to send Array just send simple plain Object
Refactored your code ( this should work ):
// Plaing object no array
$data = {'room_id': {{room.id}}, 'amount': amount, 'arrival': '2018-04-01',
'departure': '2018-04-03,', 'reservation_type': 'owner'};
$.ajax({
url: '/api/v1/booking', // <- just your Api-End [no create/store]
data: $data,
type: "post" // <- this post request indicates that you want to create/insert
})
.done(function(response) {
// this will always fire when status code is 200
console.log('Success', response);
})
.fail(function() {
// when status code is not 200 this will execute
console.warn('Something went wrong');
});
Why you get success although its not Creating Record ?
Because according to Resource Controller there is no method create in api generator controller so October CMS is treating /api/v1/booking/create [POST] request as 404 page not found and its serving [200] status code with 404 page not found as ajax response.
And 404 page is having 200 status code so it fall in to success category and Ajax thinks it's a successful request and prints success message in console.
if any doubts please comment.

I can't seem to generate content for dynamic content load

I am using wordpress and php along with ajax to create a random loading of customer reviews on our main page
function loadContent() {
$.ajax({
type: "GET",
url: 'http://skillsetsonline.ssosv.com/contentLoader.php',
data: {
company: 1
},
success: function(data) {
alert(data);
var currReview = document.getElementById('reviewRand');
currReview.innerHTML = data;
}
});
}
setTimeout(loadContent, 10000); // milliseconds, so 10 seconds = 10000ms
<div id="reviewRand" class="elementToFadeInAndOut" style="font-color:#FFF;">Hi how are you</div>
I pasted the ajax command in from a stackoverflow posting that was an accepted answer but may not have it exactly right this does not include the fading CSS code I use but that is working I just need to change the content.
Currently "Hi how are you" fades in every 10 seconds. One thing I have not learned about yet with this ajax command is the
data:{company:1}
I know it simply passes &company=1 to the GET URL but in my case I do not need to send anything and since it should not break anything if it is sent I left it alone not sure if
data:{}
would work and be cleaner
I have verified that the url used does get a random review
formatted like this
I love this program.blah blah.<br>
A USER<br>
A location<br>
June 2016<br>
Each line is formatted in CSS via a class tag
Any ideas would be greatly appreciated
Since the domain you're making the AJAX request to is on a different domain/origin, what you're running in to is a CORS issue. By default, the client will not allow you to update the page with data from an AJAX request that is served on a different origin than the site where the request originated. You can read about making CORS changes here https://enable-cors.org/
A common way around this is to serve the response via JSONP. You can do this in your script at http://skillsetsonline.ssosv.com/contentLoader.php if you have access to change that file. There are also third-party sites that will request that URL for you and create a proxy that serves the response via JSONP, then you can use it on your website.
Here's an example utilizing a JSONP proxy on https://crossorigin.me
function loadContent() {
$.ajax({
type: "GET",
url: 'https://crossorigin.me/http://skillsetsonline.ssosv.com/contentLoader.php',
success: function(data) {
var currReview = document.getElementById('reviewRand');
currReview.classList.add('ready');
currReview.innerHTML = data;
}
});
}
setTimeout(loadContent, 0); /* changed this for the demo */
#reviewRand:not(.ready) {
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="reviewRand"><img src="http://thinkfuture.com/wp-content/uploads/2013/10/loading_spinner.gif"></div>

AJAX explained in detail

I found allot of examples of AJAX and I think I can get some code with it to work on my own. If only I knew what the use of all the terms of the AJAX code where.
I think in general it lacks the availability of these guides or special pages where constructed code is explained in detail for new programmers.
This would help enormously because of the misunderstanding of the syntax in many cases. Me for example spend 8 hours a day on my internship to learn PHP, Jquery, HTML from scratch and there is allot of information out there but its not structured and in most cases to technical. Any tips on that maby ? :)
$.ajax({
type: 'POST',
url: 'http://kyleschaeffer.com/feed/',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
Ajax is asynchronous, which mean you can use it to get new informations from the server without reloading the whole page.
Here's an explanation of your code :
$.ajax({
$ is the JQuery object, on which you're calling the ajax function
type: 'POST',
You're gonna send your data by post, which mean that you'll have to get them in php with $_POST['variable_name']. You could also put GET instead
url: 'http://kyleschaeffer.com/feed/',
the url you want to reach
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
as you're sending your request with POST, you cannot pass data directly from the URL.
So you have to pass them like that. { nameVar: 'value', .... }
If you were sending with GET, you could directly write them into url like : "http://my_url.php?var1=val1&var2=val2 etc ...
beforeSend:function()
You can define an action before sending your ajax request
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
Here, inside your div "ajax-panel" you want to write some content. (a div "loading" and a picture inside "loading").
success:function(data)
If your request is successful, you can do something. By successful it means if server answer 200 i guess, anyway ... If you have a response from server... ;)
$('#ajax-panel').empty();
You delete content into ajax-panel
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
You're adding some html AFTER (append) the ajax-panel div
error:function()
Not sure you were looking for that, hope that help you ;)
AJAX is an acronym standing for Asynchronous JavaScript and XML and this technology help us to load data from the server without a browser page refresh.
If you are new with AJAX, I would recommend you go through our Ajax Tutorial before proceeding further.
JQuery is a great tool which provides a rich set of AJAX methods to develope next generation web application
Take a took at this
$.ajax({
type : varType, //GET or POST or PUT or DELETE verb
url : varUrl, // Location of the service
data : varData, //Data sent to server
contentType : varContentType, // content type sent to server
dataType : varDataType, //Expected data format from server
processdata : varProcessData, //True or False
success : function(msg) {//On Successfull service call
},
error : function() {// When Service call fails
}
});

sencha touch - ajax call to server (url , extra parameter formation)

I am using this to get the result from server
controller.allVisitStore = new Ext.data.Store({
model: 'allVisit',
autoLoad : true,
proxy: {
type: 'ajax',
id: 'allvisit_app_localstore',
url: '/RadMobApp/api',
extraParams:{
action:'query',
queryName:'GET_ALL_VISIT',
authToken: localStorage.getItem("auth_token"),
patTicketId: localStorage.getItem("patientId"),
retFormat:'XML',
keyValuePair:'yes'
},
// the return will be XML, so lets set up a reader
reader: new Ext.data.XmlReader({
// records will have an "T4" tag
record: 'data'
})
}
});
but i am not getting any thing.But i formed this url in browser and checked this i got the correct result. now here i want to check is there any problem in the url formation.How to check the url formation with extra parameter which is pass through ajax. I have checked in Inspect element-> network -> api there is no any api request found there.Is anything wrong in my code. Thanks in advance...
Use Firebug for Firefox or Chrome's developer tools to see what's going on when that store attempts to load itself. My hunch is that your url is incorrect and should be url: '/api' because RadMobApp is probably your app root.

Resources