Get proper root in javascript file - javascript

I'm having a problem with resolving the root of a URL between my local machine and after deploying an application on IIS to our dev server.
The url when running locally is something like this.
http://localhost:57173/
the url when running on the dev server is something like this.
http://ServerName/AppName
I have JQuery Ajax calls to a web api and it won't find the location on the dev server if the trailing slash is left off.
Here's the call
$.ajax({
type: "GET",
url: "api/MyApi/Get",
data: { period: selectedPeriod },
cache: false,
success: function (data) {
}
});
If I look in FireBug at the api call on the dev server, with the trailing slash left off, it will show
http://ServerName/api/MyApi/Get
If I do have the trailing slash, it will resolve correctly to this. (Notice the AppName now included.)
http://ServerName/AppName/api/MyApi/Get
What am I missing here? It looks like it's not finding the proper root of the application when I move it to this server. The trailing slash makes no difference locally. It will find the api either way. Any ideas how to resolve this?

I also had this issue, the way to solved it was declare a javascript variable that contains the part of the url that differs in both environments (dev and local) and prepend that to every ajax request:
I put that variable in the layout file (Views/Shared/_Layout.cshtml), so that it could be automatically filled by ASP.NET and then used globally (make sure to create the script before the #RenderSection call):
...
<script>
var baseUrl = #Html.Raw(Json.Encode(Url.Content("~")));
</sctipt>
#RenderSection("scripts", required: false)
</body>
...
Then prepend that variable in the url of the ajax call (for example View/Home/Index.cshtml):
#section scripts {
$.ajax({
type: "GET",
url: baseUrl + "api/MyApi/Get",
data: { period: selectedPeriod },
cache: false,
success: function (data) {}
});
}

A url without a leading slash is considered a relative url. Your url "api/MyApi/Get" will be resolved by the browser relative to the url of the page containing the script.
http://ServerName/AppName appears to the browser as if it is a page request, with AppName being the name of the page and the AppName is not considered when resolving the url.
http://ServerName/AppName/ (trailing slash) appears to the browser as a directory request and becomes the base of your relative url.
The best fix for this is probably to redirect requests for http://ServerName/AppName to http://ServerName/AppName/
To do the redirect from within your application, insert the following into your /Home/Index controller action (before any other code)
if (!Request.Url.AbsolutePath.EndsWith("/"))
{
return Redirect("~/");
}
This will redirect any request for http://ServerName/AppName to http://ServerName/AppName/ As a side effect, it would also redirect any requests for http://ServerName/AppName/Index to http://ServerName/AppName/ but I don't think that would cause you any problems.

Javascript typically doesn't run unless the user causes an event to occur. I prefer to use the following because it allows MVC to get the exact route properly everytime no matter where you deploy.
Html
<button data-url="#Url.Action("MyApi", "Get")"></button>
Javascript
$(document).ready(function()
{
$('button').on('click', function()
{
var url = $(this).data('url');
$.ajax({
type: "GET",
url: url,
data: { period: selectedPeriod },
cache: false,
success: function (data) {
});
});
});
Hard coding a url in javascript I consider bad-practice.

Related

Relative path in Ajax works differently in different environment

It is a SpringBoot website. The html page url is http://xxxxx/trex/index/ And javascript code segment in index page as below
$(function(){
jQuery.ajax({
contentType:'application/json;charset=UTF-8',
type: "POST",
url: "getSignTypes",
cache: false,
dataType: "json",
success:function(data){
if(data !== 'NA'){
console.log(data);
$('#signType').combobox({
valueField:'id',
textField:'title',
editable:false,
data:data,
value:data[0].id
});
}
},
error:function(msg){
console.log(msg)
}
});
})
You can see I use relative path in url parameter of this ajax request. I guess since it is relative url, it should be converted into http://xxxxx/trex/index/getSignTypes. I test it in my local, and yes, it is as expected http://localhost:8088/trex/index/getSignTypes.
But when I deploy it to UAT, I find that the url is converted to http://hswcfc-trainexp-web.uat.homecreditcfc.cn/trex/getSignTypes. The index part is gone.
Why relative path in Ajax works differently in different environment? The ajax code is exactly the same. Any clue I can trace to find the difference? Thanks.
I past the UAT screen shot here.
A HTTP URL consists of several parts: protocol, hostname, port, username, password, path, query string (?....) and fragment (#....).
As suspected, your URL path ends in / in dev, but not in UAT. Think of it as "directories": /trex/index/ is the empty file name in /trex/index directory, while /trex/index is the file index in /trex directory. Web servers often treat the two the same way, but clients do not: when you do a relative path from there, you get /trex/index/getSignTypes in the first case, but /trex/getSignTypes in the second.
This is usually fixed by creating a redirect rule so that you can never accidentally write the same URL in two different ways (e.g. by redirect /trex/index to /trex/index/).

Wikipedia API. File not found Error

I'm trying to make a wikipedia search bar. The idea is to send a new AJAX request every time search input is changed. I'm using https://www.mediawiki.org/wiki/API:Search_and_discovery as a guideline.
var search = $('#search');
search.keyup(function() {
if (search.val() === '') {
result.html('');
}
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: {
action: 'query',
list: 'search',
format: 'json',
srsearch: search.val()
},
dataType: 'jsonp',
success: function(response) {
console.log("success!");
}
});
});
However, success function is not even triggered.
On any keypress the error I get is this ("d" pressed):
jquery-2.1.1.min.js:4 GET file://en.wikipedia.org/w/api.php?>callback=jQuery21107844703783826772_1484403407494&action=query&list=search&srse>arch=d&format=json&_=1484403407495 net::ERR_FILE_NOT_FOUND
Thank you in advance for any help or guidance!
Well, you're probably trying to do a AJAX request without a local server (opening your file directly in the browser).
First of all, your url options starts with //en... (without the protocol). It indicates that it'll construct your full url using the same protocol you're using. In this case: file://. That's because your browser is trying to reach file://en.wikipedia.org/....
So, you can set your url to https://en.wikipedia.org/w/api.php to make it work.
Just replace:
url: '//en.wikipedia.org/w/api.php',
with:
url: 'https://en.wikipedia.org/w/api.php',
Looks like you're running it from a simple html file located in your filesystem, in other words not running it from a web server (even local).
Try calling the api with
url: 'https://en.wikipedia.org/w/api.php'
or run the file from a web server (can be a local one).

JavaScript URL issue with Permalinks enabled

I am using the following JavaScript function to fetch the data using ajax call
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
It calls the following php file and works fine.
http://127.0.0.1/osclass/oc-content/themes/bender/ajax-test.php
But when I enable SEO friendly Permalinks in my CMS current page URL is appended in start of link and I get the following error in Chrome Console.
GET http://127.0.0.1/osclass/fashion-beauty/oc-content/themes/bender/ajax-test.php?name=Jhon 404 (Not Found)
Anybody tell me how to solve this issue?
The url you've provided in the ajax call is document relative. When you changed the server's url generation scheme, you also caused the url pointed at by the ajax call to change.
Adjust the ajax url, changing:
url: "oc-content/themes/bender/ajax-test.php",
To:
url: "/osclass/oc-content/themes/bender/ajax-test.php",
Why don't you make the URL server-relative? Something like this:
function findName() {
var name = "Jhon";
$.ajax({
method: "POST",
url: "/osclass/oc-content/themes/bender/ajax-test.php",
data: { name : name },
success: function (data) {
alert(data);
},
})
}
As you have not posted the php code. I would mention that any url directly navigated through addressbar of browser causes in the GET request and i can see you have a POST request in the ajax, so, it can't work.
Workaround would be to use $_REQUEST super globals at php end. $_REQUEST would work for $_GET/$_POST requests.

Implementing Ajax calls for a REST API

I have built a back end REST API using Slim Framework and followed the REST format as close as I could.
Once I started working on the Front End I realized that AJAX works great with parameters and not paths
(param file?param=value , paths file/object/method/id)
I am planning on out sourcing or building an APP with xamarin or other 3rd party to consume the API, but for now a Alpha test will be done with HTML and AJAX calls.
Example call example.com/user/test or example.com/advertiser/2
So how do I query the API, do I just concat URL strings?
.ajax({ ... url : 'example.com/user/'+user ...});
EDIT:
Yes I know AJAX is domain sensitive, and Yes I am using verbs GET,POST,PUT and DELETE.
What is going on is the following :
When passing variables in an AJAX request they get appended as
PARAMS example.com/users/?user=Pogrindis
in an REST API at least as far as I read it goes
example.com/users/Pogrindis that's a path
reference parse.com/docs/rest#general-quick
Ajax has set definitions how to do this : https://api.jquery.com/jQuery.ajax/
Your passing user as a param, over get // post method and you are specifying what you expect back.
If i understood the question correctly you are looking at something like:
$.ajax({ url: 'example.com/user/',
data: {user: user}, // Params being sent
type: 'post',// Or get
dataType: 'json' // Or whatever you have
success: function(output) {
//.. do what you like
}
});
There should be no problem.
The data being passed into it will append to the url for GET-requests, i think thats what you mean.. Your data object can be constructed before sending via ajax.
There needs to be a route to query for data. Unless you define some flag on the server to point to the correct location, then you could pass through a route param but you need to have a pointer URL. Building the route can be painful, and subsequent calls will be more challenging but you can do it ?
After doing some research here is a solution used
FRONT END
$.ajax({
url: '/user/'+getid,
data: getdatastring,
type: 'GET',
datatype: 'json',
cache: false,
success: function(data) {
data = JSON.parse(data);
}
});
BACK END
SLIM PHP FRAMEWORK
$app->put('/user/:id', function($id) use ($app,$_pdo) {
$obj = new dbModel($_pdo);
$objApi = new Controller($obj);
$arrParams = json_decode($app->request()->getBody(),true);
$arrUser= $objApi->getUserInfo($id,$arrParams);
print json_encode($arrUser);
});

Ajax get request to wsdl web-service

i have wsdl file and i need get data from. How i can do this ? i'm trying do this with ajax
like this:
jq.ajax({
url: 'http://url.wsdl',
type: 'get',
success: function(data){
alert("OK " + data);
},
error: function (x, y, z) {
alert("ERROR");
}
});
what i do wrong ?
Any other way to get data from wsdl web service using javascript, jquery and etc. is?
I think what you are missing is a data: {}
I read that there was some sort of bug if you did not include that when using $.ajax
Oh, and most likely you are going to need dataType: "json" or whatever datatype the service is using.
Here is an example i am using against an online webservice:
jQuery.support.cors = true; //enables cross domain queries for Ajax
$('#jqueryBtn').click
(function ()
{
$.ajax
(
{
type: "GET",
url: "http://www.webservicemart.com//uszip.asmx/ValidateZip",
data: { 'ZipCode': '22553' },
dataType: 'html',
success: jqSuccess,
error: jqError
}
);
}
Hopefully you can use this example to fix your own code
http://forum.jquery.com/topic/jquery-ajax-to-call-a-wsdl-web-service
The following link should explain why you cannot use AJAX for cross domain queries:
http://www.w3schools.com/xmL/xml_parser.asp:
Access Across Domains
For security reasons, modern browsers do not allow access across
domains.
This means, that both the web page and the file it tries to load,
must be located on the same server.
The examples on W3Schools all open XML files located on the W3Schools
domain.
If you want to use the example above on one of your web pages, the file you load must be located on your own server.
You can create a proxy web page in your web server to access to WSDL web service and return result to the AJAX request

Categories

Resources