Sending ajax request by jquery doesn't working - javascript

I'm trying to send ajax request to api. My code is
$(".doit").click(function(){
console.log("GG");
$.ajax({
type: 'POST',
url: "localhost:8000/api/get-user/1",
data: {id:1},
success: function(res) {
console.log(res);
}
});
})
It's just a simple code. Everyone know. But it works in "console.log("GG"). Not working in ajax part.
I monitored the network traffic by firefox, but I ddin't see any network traffic.
Do you have any idea about that case?

Update your ajax URL as below
url: "http://localhost:8000/api/get-user/1",
or
url: "api/get-user/1",
Hope this will fix your issue

This is because you are specifying the port number, and also not including the scheme.
Simply removing your domain should be enough:
$(".doit").click(function(){
console.log("GG");
$.ajax({
type: 'POST',
url: "/api/get-user/1",
data: {id:1},
success: function(res) {
console.log(res);
}
});
})

The problem is that you do not specify the URL scheme. So, instead of localhost:8000/api/get-user/1 you should use //localhost:8000/api/get-user/1, or better specify just the relative path /api/get-user/1.

I think because your url in the same url as you want to make request and that didn't make you will see the network traffic. just using the different url will show the request ajax from the network traffic.
just try to change your url to this: https://jsonplaceholder.typicode.com/posts
and read about this further information: https://github.com/typicode/jsonplaceholder#how-to

Related

How to do a POST request with headers?

Right now, I'm trying to do a post request:
https://aleapisoap.azure-api.net/httpbin/listSearchFields
And I need a body which is this:
{
"listSearchFields": {
"email": "sample"
}
}
I tried this in postman and works but with this code in JavaScript doesn't work.
$.ajax({
url: 'https://aleapisoap.azure-api.net/httpbin/listSearchFields',
headers: {
'Content-Type':'application/json',
'Cache-Control':'no-cache',
'Ocp-Apim-Trace':'true',
'Ocp-Apim-Subscription-Key':'19f2a7fd474840bfb5fc729cd97b7335'
},
type: 'POST',
dataType: 'jsonp',
data: '{"listSearchFields":{"email":"sample"}}',
success: function(data){
console.log('succes: '+data);
}
});
This is the error:
net::ERR_ABORTED 404 (Resource Not Found)
The headers in your $.ajax() call look correct to me. I think the "listSearchFields" endpoint doesn't exist at https://aleapisoap.azure-api.net/httpbin/ like you're expecting. Check your spelling first - if you're spelling "listSearchFields" correctly, you'll have to dive deeper to figure out why it's not being found.
dataType: 'jsonp',
JSONP requests are incompatible with setting custom request headers or making POST requests. They work by injecting a <script> element with a src attribute (which makes a GET request).
If you need to make a POST request, don't use that dataType. You probably want 'json'.
JSONP is a hack that was used to work around the Same Origin Policy before CORS was available. You might have to take other steps to ensure the endpoint is available to your origin.

Ajax Post request example

I was wondering if anyone could help me with a simple ajax request example just so I can wrap my head around the whole idea. I tried testing an ajax request to search the word "rails" on github. So my code looks something like this:
$.ajax({
url: 'www.github.com',
type: 'post',
contentType: 'application/x-www-form-urlencoded',
data: {
q: 'rails'
},
success: function(data) {
console.log(data);
}
});
This request is responding with a 404 response. So, I'm just curious how are you supposed to know what the key names for the "data" element should be? When I inspected the search bar on github, it told me the name of the element was q. Hence why I used the key "q" and I wanted to search for say "rails". If anyone could help me with this example or perhaps provide a better one that would be greatly appreciated. Thanks!
Try to add http in your url, but, for security reason you can't do Ajax Crossdomain request without autorisation of the github.com domain in your case.
http://api.jquery.com/jquery.ajax/

Unable to perform a Cross domain ajax call. - JQuery

I have checked many post and tried every logic that were mentioned in various blogs and posts. But I am unable to perform a cross domain ajax call to an IIS server. Please anybody advice what else I should look into or configure it to get working. All your help is greatly appreciated.
Here is my ajax call:
var url = "http://mydomain .com/myauthorizeservice";
var jsonParam = JSON.stringify({ username: 'user007', password: 'pass007' });
$.ajax({
type: "POST",
url: url,
crossDomain: true,
data: jsonParam,
success: fnSuccess,
error: fnError,
dataType: "json",
contentType: "application/json"
});
function fnSuccess() {
alert("Success");
}
function fnError() {
alert("Error");
}
My config in the root web.config:-
Error:-
Access Denied.
I really struggled a lot to make this thing work. Here some points that also matters and restrict the cross domain calls-
Note: I am using WCF REST service. and configurations are for IIS 7.5.
1: Make sure your OPTIONSVerbHandler looks like-
2: Make sure you have the correct ordering in HandlerMappings-
Rest settings and the way to perform ajax call is mentioned in the question.
Happy coding!

GET request caching page response

I do not want the requested page to be cached by the browser. Would a post request fix this? Is there much downside to making a POST instead of a GET?
At the moment I am using like:
$.get("/Client/JSON_GetInvoiceLines/" + ClientID, function (data) {
//do stuff
});
you can use the cache option in jQuery.
$.ajax({
url: '/Client/JSON_GetInvoiceLines/',
type: 'GET',
cache: false,
success: function(data){
// do stuff
}
});
It will append a random character string as a GET parameter to the end of your URL, so the browser won't cache it.
However, the ideal solution would be to disable caching on the server-side by setting headers, assuming you have control over the resource that you're requesting.

Jquery unable to get the response from WCF REST service

I have developed WCF rest service and deployed it on a link that can be accessed via the browser because its action is "GET".
I want to get that data using jQuery. I tried my best to get WCf get response using jQuery
but in vain. I also tried $.Ajax with 'jsonp' with no luck. Can any one help me?
The url is: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation
You can check that url response by pasting url in browser.
You need to set Access-Control-Allow-Origin to value [*] in your response header.
this blog gives the more details how it can be done in WCF REST service
if you were to do this in Web API you could have just added
Response.Headers.Add("Access-Control-Allow-Origin", "*")
calling the service using a fiddle
$(function() {
$.ajax({
url: "http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation",
datatype: 'json',
type : 'get',
success: function(data) {
debugger;
var obj = data;
}
});
})​;​
I got the error
XMLHttpRequest cannot load
http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation.
Origin http://fiddle.jshell.net is not allowed by
Access-Control-Allow-Origin.
I can't make a cross domain example to show you but
$('#a').load('http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation​​​​​​​​​​​​​​​​​?callback=run');​
would work had those things been set.
Your service needs to either enable JSONP callbacks or set the Access-Control-Allow-Origin header for cross domain requests to work, or you need to run the script from the same domain. Given that your url says AndroidApp I'm thinking you want cross domain.
Sample code below:
$.ajax
(
{
type: 'GET',
url: http://www.lonestarus.com/AndroidApp/AndroidLocation.svc/RestService/getLatestLocation,
cache: false,
async: true,
dataType: 'json',
success: function (response, type, xhr)
{
window.alert(response);
},
error: function (xhr)
{
window.alert('error: ' + xhr.statusText);
}
}
);

Categories