Jquery mobile page navigation corrupts base url and causes ajax on main page to fail - jquery-mobile

My main page is here:
http://www.mydomain.com/main/main.php
My login page is here:
http://www.mydomain.com/main/pages/login.php
Main.php uses ajax to fetch data in response to a tap event. This works fine until I navigate to my login page and then back to my main page. After going to the login page and back, the relative paths get messed up such that the ajax looks for server file in the wrong place.
here is the ajax:
1. function get_more_data() {
2. more_data_index += 15;
3. var formData = "index=" + more_data_index;
4. $.ajax({
5. type: "POST",
6. url: "genxml.php", // file located here: http://www.mydomain.com/main/genxml.php
7. cache: false,
8. data: formData,
9. dataType: "xml",
10. success: showFiles3,
11. error: onErrorMoreData
12. });
13. }
After I navigate back to main.php from login.php the ajax tries posting to the wrong location:
http://www.mydomain.com/main/pages/genxml.php
(genxml.php is not in the "pages" subdirectory; it's in the main directory.)
I tried updating the ajax to use an absolute path:
url: "http://www.mydomain.com/main/genxml.php"
This made the post successful, but my data parsing failed because relatives paths are used in the main file for things like images. So instead of getting images from here: http://www.mydomain.com/main/ the script was trying to get images from here: http://www.mydomain.com/main/pages/
I've found a few posts with people having similar issues, but I've not come across a solution. I've also tried reading the jquerymobile docs and it's very possible that the jquery developers attempt to cover this issue here, but I admit I don't completely understand everything on this page:
http://jquerymobile.com/demos/1.0b3/#/demos/1.0b3/docs/pages/page-navmodel.html
If anyone can help I would really appreciate it. Thanks.
P.S. This issue happens on Android and Google Chrome, but not in Firefox.

I have created a working example of what you're trying to do. You should be able to look at this and see what I've done. Be sure to checkout the master.js. I think that the key to making it work in your situation is to nest the ajax calls within the "pageshow" event to be sure that your baseURL has been updated. You can download the example at http://www.roughlybrilliant.com/stackoverflow/7372909.7z
View the example in action as it pulls in weather.xml with relative URLs.
$("div").live("pageshow", function(){
var $page = $(this);
get_more_data();
});

Why don't you use one of this:
use "../main.php" when redirecting back from login page, or
remember UrlRefer from Headers when you entering login.php and use that to redirect back to any previous page with 301

Related

Allowing POST method to an HTML page in ASP.NET MVC

Allowing POST method to an HTML page in ASP.NET MVC
I am using ASP.NET with MVC 5.2 and I am integrating RoxyFileManager to my CKEditor.
The integration was fine, the problem is when I try to upload some file to my web server, I got this error:
NetworkError: 405 Method Not Allowed - http://localhost:35418/FileManager/index.html?...
The RoxyFileManager uses the POST method to upload the file and my webserver does not accept it. I can't figure out how can I fix it.
If I put manually an image to my directory I can see it in the file manager, also I can create and exclude folders there.
To clarify my question: I want to know how can I make my webserver accept the POST method to a HTML page, just it. All the relevant information are above. I have a HTML page and want to make it accept POST.
#UPDATE:
I've figured out the problem is a browser issue.
In Google Chrome everything works fine;
In Firefox I get the error above;
In IE things seens to work fine, but it have cache problems (I can upload and edit previously sent files, but I can't see the changes neither the recent file uploads until cache expires);
I'll work on these problems and post the answer here, if successful.
To solve the IE bug it's simple but it's hard-work: You need to add in every ajax call of RoxyFileMan the line cache: false. You need to do it in every .js file on the RoxyFileMan folder.
Example:
$.ajax({
url: d, dataType: "json", async: true, success: function (h) {
for (i = 0; i < h.length; i++) { e.push(new File(h[i].p, h[i].s, h[i].t, h[i].w, h[i].h)) }
g.FilesLoaded(e)
},
error: function (h) { alert(t("E_LoadingAjax") + " " + d) },
cache: false
})
With this, all the ajax made by Roxy will have no cache, solving the IE issue.
To solve the Firefox bug I've changed this in the main.min.js:
BEFORE:
document.forms.addfile.action = RoxyFilemanConf.UPLOAD
AFTER:
$('form[name="addfile"]').attr('action', RoxyFilemanConf.UPLOAD);
I've found this solution here.
And now my file manager is working on all modern browsers.

AJAX Call returning 404(Local) in IIS 7.5 but same works in other IIS

Am having the AJAX calls to my controller in my MVC Application
Controller/FunctionName
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '/Controller/FunctionName',
.
.
.
)};
Am using MVC 4 and making use of JQUERY Ajax function as shown in the above code. It works totally fine when i run from Visual studio.
I depolyed this to the server machine and as expected it works fine. No issues found in AJAX calls.
Now am trying to deploy this in my local machine IIS which is same as my server version (IIS 7.5) but am getting 404 for all the ajax calls in firebug.
I verified the build and even i pointed to my web folder and am still looking for what went wrong !!
It works in other IIS so It wont be a URL resolving issue is my gues. Am i missing any settings or Any timely idea to fix this would be great.
Thanks
That's normal. You have hardcoded the url to your controller action:
url: '/Controller/FunctionName',
If you deploy your application in a virtual directory in IIS the correct url should be:
url: '/YourAppName/Controller/FunctionName',
That's the reason why you should absolutely never hardcode urls in an ASP.NET MVC application but ALWAYS use url helpers to generate it:
url: '#Url.Action("FunctionName", "Controller")',
and if this AJAX call is in a separate javascript file where you cannot use server side helpers, then you could read this url from some DOM element that you are AJAXifying.
For example let's suppose that you had an anchor:
#Html.ActionLink("click me", "FunctionName", "Controller", null, new { id = "myLink" })
that you AJAXify:
$('#myLink').click(function() {
$.ajax({
url: this.href,
contentType: 'application/json; charset=utf-8',
type: 'GET',
.
.
.
)};
return false;
});
Notice how we are reading the url from the DOM element which was generated by a helper.
Conclusion and 2 rules of thumb:
NEVER EVER hardcode an url in an ASP.NET MVC application
ABSOLUTELY ALWAYS use url helpers when dealing with urls in an ASP.NET MVC application
Just a complement of Darin's answer that if "the AJAX call is in a separate javascript file where you cannot use server side helpers", use a hidden field to store the url endpoint in the view:
#Html.Hidden("URLEndpointName", Url.Action("FunctionName", "Controller"))
and read that hidden field in your js:
url: $("#URLEndpointName").val(),
You can use double dot in the url:
$.ajax({
url: '../ControllerName/ActionName',
.......
});
What I'd found on my setup of IIS7.5 is that the 'Handler Mapping' has a resource named 'OPTIONSVerbHandler' is not set in the right order hence return back as Unknown.
This work for me where my localhost ajax was calling my network server, which has a different name, that it shouldn't give me a CORS issue, but it did and this was my solution.
Open IIS and click on your server name on the left pane. On the right pane double-click 'Handler Mappings' in the middle pane. On the right pane, select 'View Ordered List'. From there find 'OPTIONSVerbHandler' and 'svc-ISAPI-4.0_32bit', move 'OPTIONSVerbHandler' up until it is above 'svc-ISAPI-4.0_32bit'.
Make sure your 'handler' inside your ajax call does not have 'Access-Control-Allow-Origin' in it.

jQuery Mobile Site using an ajax $.get() to check username availability returning previous page code in return data

I have a simple JQM site I'm working on. I'm trying to validate the availability of a username on the fly in a form. I'm using jquery $.get() ajax to return "success" or "fail" however the return data is being replace with the code of the previous page.
$(document).on('pageinit', function () {
// check to see if username is available
$("#username").change(function() {
$.get("controller.php", { action: "check_username", username: username }, function(data) {
console.log(data);
}
});
The controller.php is checking for availability of the username and return "pass" or "fail" When I do the console.log(data) which I'm expecting to be pass or fail, it's logging out the code from the previous page??
I'm thinking maybe it's a JQM caching issue so I tried to disable cache with no effect. I was orginally using a JQM dialog box to display the form. Thinking that had something to do with it I pulled that out and loaded a straight link. That didn't fix it so I tried to load the page directly using
$.mobile.changePage( "user-new.php", { reloadPage: true});
I am stumped. Why would a $.get ajax call return data be returning code from the previous page?
Here's a face palm! My controller was authenticating and kicking it back out to a login page. Apparently php redirects act funky with ajax return data. Rather then returning the login page code it was returning the previous page code. I Removed the authentication and it works fine. Unbelievable! I'm going to go work at a gas station or something :)

ajax request in rails 2 not working

function ajaxRequest(){
$.ajax({
type: 'GET',
url: 'client/orders/send_mail_to_notaries',
data: { subject: "hi" }
});
return false;
}
It doesn't pass any params in controller.Can any one trigger this out?
Following the question that you have asked today morning page.replace_html method in rails 2 i guess you are using prototype.
Can you check if jQuery is included? Unless jQuery is included this ajax request will not work.
I just tried the method you're using and it worked for me. Perhaps there's a problem with the router/controller?
When debugging ajax it's very handy to use the Chrome developer toolbar. Bring it up, run the javascript and see what happens.
To see the response from the server you can then flip to the Network tab to see what the response is.

Modify URL before loading page in firefox

I want to prefix URLs which match my patterns. When I open a new tab in Firefox and enter a matching URL the page should not be loaded normally, the URL should first be modified and then loading the page should start.
Is it possible to modify an URL through a Mozilla Firefox Addon before the page starts loading?
Browsing the HTTPS Everywhere add-on suggests the following steps:
Register an observer for the "http-on-modify-request" observer topic with nsIObserverService
Proceed if the subject of your observer notification is an instance of nsIHttpChannel and subject.URI.spec (the URL) matches your criteria
Create a new nsIStandardURL
Create a new nsIHttpChannel
Replace the old channel with the new. The code for doing this in HTTPS Everywhere is quite dense and probably much more than you need. I'd suggest starting with chrome/content/IOUtils.js.
Note that you should register a single "http-on-modify-request" observer for your entire application, which means you should put it in an XPCOM component (see HTTPS Everywhere for an example).
The following articles do not solve your problem directly, but they do contain a lot of sample code that you might find helpful:
https://developer.mozilla.org/en/Setting_HTTP_request_headers
https://developer.mozilla.org/en/XUL_School/Intercepting_Page_Loads
Thanks to Iwburk, I have been able to do this.
We can do this my overriding the nsiHttpChannel with a new one, doing this is slightly complicated but luckily the add-on https-everywhere implements this to force a https connection.
https-everywhere's source code is available here
Most of the code needed for this is in the files
IO Util.js
ChannelReplacement.js
We can work with the above files alone provided we have the basic variables like Cc,Ci set up and the function xpcom_generateQI defined.
var httpRequestObserver =
{
observe: function(subject, topic, data) {
if (topic == "http-on-modify-request") {
var httpChannel = subject.QueryInterface(Components.interfaces.nsIHttpChannel);
var requestURL = subject.URI.spec;
if(isToBeReplaced(requestURL)) {
var newURL = getURL(requestURL);
ChannelReplacement.runWhenPending(subject, function() {
var cr = new ChannelReplacement(subject, ch);
cr.replace(true,null);
cr.open();
});
}
}
},
get observerService() {
return Components.classes["#mozilla.org/observer-service;1"]
.getService(Components.interfaces.nsIObserverService);
},
register: function() {
this.observerService.addObserver(this, "http-on-modify-request", false);
},
unregister: function() {
this.observerService.removeObserver(this, "http-on-modify-request");
}
};
httpRequestObserver.register();
The code will replace the request not redirect.
While I have tested the above code well enough, I am not sure about its implementation. As far I can make out, it copies all the attributes of the requested channel and sets them to the channel to be overridden. After which somehow the output requested by original request is supplied using the new channel.
P.S. I had seen a SO post in which this approach was suggested.
You could listen for the page load event or maybe the DOMContentLoaded event instead. Or you can make an nsIURIContentListener but that's probably more complicated.
Is it possible to modify an URL through a Mozilla Firefox Addon before the page starts loading?
YES it is possible.
Use page-mod of the Addon-SDK by setting contentScriptWhen: "start"
Then after completely preventing the document from getting parsed you can either
fetch a different document from the same domain and inject it in the page.
after some document.URL processing do a location.replace() call
Here is an example of doing 1. https://stackoverflow.com/a/36097573/6085033

Resources