Why do url variables cause issues with ajax relative url? - javascript

So, I'm doing a normal ajax call like this:
$.ajax({
type: "GET",
url: this.Controller + "/" + this.Action,
data: data,
cache: false,
dataType: "json",
success: function (data) {
var json = $.parseJSON(data);
$("#Debug").html(JSON.stringify(json, undefined, 4));
},
error: function (jqXHR, textStatus, errorThrown) {
var errorMessage = "Unable to retrieve data."
if (jqXHR.responseText != null) {
errorMessage += "\n\nError Message: " + jqXHR.responseText;
}
alert(errorMessage);
}
});
When I use a relative path for the ajax url, it works fine, as long as there are no url variables in the current page's url. It will correctly go to http://domain.com/controller/action
If there is a url variable, the ajax url tries to hit http://domain.com/controller/controller/action, which does not exist.
If I add a slash like so:
url: "/" + this.Controller + "/" + this.Action
This fixes the issue of that the url variables cause, but only locally. When I deploy to our servers, my app is located in a sub-directory, so the url is http://domain.com/myapp. The slash solution does not work as the root is http://domain.com and not http://domain.com/myapp.

you can try this $.ajax({url: document.domain + this.Controller ... }) .

I tried all kinds of ways to do this via JS and none of them worked for both server (with sub-directory) and local (without).
So, my solution was to add the name of the sub-directory in my web.config's appsettings. In the main web.config, I have: <add key="Subdirectory" value="" />
In the web.release.config, I have: <add key="Subdirectory" value="SubDirectoryName" xdt:Transform="SetAttributes" xdt:Locator="Match(key)" />
By leaving it blank in the web.config and setting it in web.release.config, the sub-directory will be transformed and set only when published to the server.
On the _Layout.cshtml page, I have:
<script>
var subdirectory = '#ConfigurationManager.AppSettings["Subdirectory"]';
if (subdirectory != '') {
subdirectory = '/' + subdirectory;
}
</script>
Then, anywhere in my JS that I am trying to do an ajax call, I set the url to:
url: subdirectory + "/" + this.Controller + "/" + this.Action, // subdirectory comes from _Layout.cshtml

Related

Ajax URL Path not Replacing current URL

get a problem with ajax url.
Here's the code:
onConfirm: function(){
var id = $(".branchid").data('id');
var url = "view-merchants-branch/" + id;
console.log(url);
$.ajax({
url: url,
type: "POST",
data: {_method: "DELETE", id:id},
success: function() {
alert("Data has been deleted");
location.reload();
},
error: function(){
console.log(url)
}
});
},
onCancel: function(){
return;
}
my url not replacing the current url and its become 404.
the result is:
http://localhost/admin/public/view-merchants/9/view-merchants-branch/273
expected result is:
http://localhost/admin/public/view-merchants-branch/273
I've tried change the type to "DELETE" but still no hope.
is there wrong with my ajax?. as i know ajax url will replace current url.
use
url: '<?php echo "http://" .$_SERVER['SERVER_NAME']."/admin/public/";>'+url,
type: "POST",
Hi instead pass absolute url like,
onConfirm: function(){
var id = $(".branchid").data('id');
var url = SITE_URL+"view-merchants-branch/" + id;//SITE_URL IS GLOBAL VARIABLE,WHICH IS ABSOLUTE PATH COMES UPTO http://localhost/admin/public/
console.log(url);
Check your network requests to see how the url is constructed,
Also visit this link to get better understanding about how ajax works
http://www.sitepoint.com/use-jquerys-ajax-function/
also this link
https://learn.jquery.com/ajax/key-concepts/#ajax-and-firebug

Symfony2: How to get the current route in javascript?

I'm using Ajax to change data in a page. So, I want to know that what is the current route in order to call to different functions. I have read many solutions used to retrieve the current url and also to get the current route in Controller and Twig. However, is there any possible way to achieve this in javascript or jQuery?
$(document).ready(function(){
$('#form_patient').change(function(){
var id = $(this).val();
// Get the current route
var route = ??; // <----------------Want to get the current route
if(route === 'route1'){
functionForRoute2(id,route)
}
else{
functionForRoute2(id,route);
}
});
});
** Function for the Route1 **
function functionForRoute1(id,route){
$.ajax({
type: "POST",
url: Routing.generate(route),
data: JSON.stringify({id:id}),
dataType: "json",
success: function(data){
// Execute some specific data for route1
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
** Function for the Route2 **
function functionForRoute2(id,route){
$.ajax({
type: "POST",
url: Routing.generate(route),
data: JSON.stringify({id:id}),
dataType: "json",
success: function(data){
// Execute some specific data for route2
},
error: function(XMLHttpRequest, textStatus, errorThrown)
{
alert('Error : ' + errorThrown);
}
});
}
What I would do is to output route (any route you want) in a html tag for example (twig version):
<div id="my-route" data-route"{{ path("my_route") }}"></div>
Then in your code I would retrive that route via jquery like this:
$(document).ready(function(){
$('#form_patient').change(function(){
var id = $(this).val();
var route = $('my-route').data('route');
});
});
You can also change path("my_route") to a string with a name of the route and then you are doing your if/else statement. However I dont think its a good idea as if your route name changes then your code will be affected as well
You will not get current route using just Javascript or JQuery. You can, however, get current URL with Javascript or current route using Twig.
Another possible solution is to issue one more AJAX call to server passing current URL, then match it to the correct route and send it back. However, if I were you, I would just get the current route from Twig.
var route = "{{ app.request.attributes.get('_route') }}";

Javascript url 404 error

I'm have a problem loading a site. Using this code:
$.ajax({
type: "POST",
//url: '#Url.Action("/TellFriendPopup")',
url: '/Property/TellFriendPopup',
data: { "SenderName": SenderName, "senderMail": senderMail, "receiverMail": receiverMail, "comments": comments, "urlLink": urlLink, "subjectId": subjectId },
success: function (data) {
$("#result").html("<ul><li>Name: " + data.nameret + "</li><li>Email: " + data.emailret + "</li><li>Message: " + data.messageret + "</li></ul>");
$(".dialog").dialog("close");
},
The problem is that I had to move the code to a JavaScript file, instead of the MVC4 View, where i could use the #Url.Action method. But it is not working in JavaScript. It Just gives me this error POST http://localhost:54717/Property/ContactPopup 404 (Not Found). The reason as I can see is that it's the Globalization that it's missing. Because the url should look like this http://localhost:54717/da/Property/ContactPopup or http://localhost:54717/en/Property/ContactPopup
You could get the first folder of the pathname. As long as that is where the language code is on every page.
var language = location.pathname.split("/")[1];
url: language + '/Property/TellFriendPopup'
You can have language in hidden field.
var language = document.getElementById('language`).value;
url: '/' + language + '/Property/TellFriendPopup'
Can you try changing this: url: '/Property/TellFriendPopup',
to this url: '../Property/TellFriendPopup',

jquery $ajax not working as expected

I Have to do a cross-domain request and fetch content from a url using $.ajax function.
But the below code only displays the first alert i.e alert(myUrl),
After that the execution stops.The second alert is not displayed. I don't know what is wrong with the code i have written.
Can somebody tell me what i am doing wrong here?Thanks in advance.
function getContentFromUrl(){
var myUrl="http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" +
"q=select%20*%20from%20html%20where%20url%3D%22" +
encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
success: function () {
alert("***********"+data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function() {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
});
}
Same Origin Policy:
The policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions, but prevents access to most methods and properties across pages on different sites.
You can't use regular JSON for cross-domain requests because of the same-origin policy. Instead, you'll need to use JSONP. In jQuery, you can do so like this:
$.ajax({
dataType: 'jsonp',
crossDomain: true
// other info
});
Note that there are security issues involved with JSONP. Only use JSONP if you trust the host domain.
I assume this is jQuery?
Try the following:
url = "http://query.yahooapis.com/v1/public/yql?" +"q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?";
getContentFromURL(url);
function getContentFromURL(url)
{
$.get(url, function (data) {
console.log(data);
});
}
If it dumps out to the console a response, you can build from there.
The data here is not defined
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: data,
and you forget to add a param for the callback function
success: function (data) {
....
}
The finally code should like this
function getContentFromUrl() {
var myUrl = "http://icant.co.uk";
alert(myUrl);
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?" + "q=select%20*%20from%20html%20where%20url%3D%22" + encodeURIComponent(myUrl) + "%22&format=xml'&callback=?",
dataType: 'json',
data: {},
success: function (data) {
alert("***********" + data.results[0]);
if (data.results[0]) {
var htmlText = data.results[0];
var jsonObject = parseAndConvertToJsonObj(htmlText);
} else {
document.getElementById("displayerrors").innerHTML = "Could not load the page.";
}
},
error: function () { document.getElementById("displayerrors").innerHTML = "Could not load the page."; }
});
}

$ajax is not working with ASP.Net

I am debugging my solution on localhost and this piece of code is not hitting the server
var cartInfo = $j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val() + '&email=' + email.val() + '&phone=' + phone.val() + '&date=' + date.val() + '&cart=' + cartInfo;
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
What am I missing here?
the are 2 potential problems
the url
the data
aspx assumes webforms, the page life cycle, etc. when all you want is to send response and get a reply. instead try targeting either a
web service (asmx)
generic handler (ashx)
a static pagemethod think ajax server hanlders embedded within a page object
second is the data. instead of passing a string as the data try passing a json object
data = {
name: "john",
email: "john#email.com",
...
}
Since you are passing the cartInfo as an html, it should be url encoded before it is posted. I think this is wat causing this issue. Try this
var cartInfo =
$j("#ctl00_BaseContentPlaceHolder_ctl00_updateShoppingCart").html();
var dataString = 'name=' + name.val()
+ '&email=' + email.val()
+ '&phone=' + phone.val()
+ '&date=' + date.val()
+ '&cart=' + encodeURIComponent(cartInfo);
$j.ajax({
type: "POST",
url: "LightBoxContactSender.aspx",
data: dataString,
success: OnSuccess,
error: OnError
});
As suggested by in other answer you can also pass data as a key/value pair object to ajax method, jQuery will take care the rest but you still have to encode the html content.
Url Doesnt call any method ?
url: "LightBoxContactSender.aspx",
If yoy are trying to call a WebMethod inside aspx
url :"LightBoxContactSender.aspx/callStaticMethod",
Try to form Data as
dataString = "{'name=' + '"+name.val()+"'}"

Categories