AJAX: "The requested URL was not found on this server" on localhost - ajax

Ajax can contact the remote server nicely(uses jsonp) and beautiful data is returned.
In localhost it says that the url was not found on this server.
I 'alert' the url right before the ajax, copy-paste it into the browsers address bar, and beautiful data is returned.
WHY?
Oh why isn't my ajax working in localhost when the url clearly works?
I use WAMP-server and I've created an alias directory for the project folder. Like I said, the url works because I can go to it through the address bar of the browser, but ajax fails for some reason.
The code:
var temp_url = "localhost/api/1.1/app_dev.php/getsomething/something";
$.ajax(
{
type: "GET",
url: temp_url,
timeout:5000, // 5 second timeout in millis!
data:{ 'get_data' : querystring},
dataType: "jsonp",
cache: false,
success: function( data, textStatus, jqXHR ) {
console.debug(data);
},
error: function(jqXHR, exception)
{
if (jqXHR.status === 0) {
alert('Not connect.\n Verify Network.');
} else if (jqXHR.status == 404) {
alert('Requested page not found. [404]');
} else if (jqXHR.status == 500) {
alert('Internal Server Error [500].');
} else if (exception === 'parsererror') {
alert('Requested JSON parse failed.');
} else if (exception === 'timeout') {
alert('Time out error.');
} else if (exception === 'abort') {
alert('Ajax request aborted.');
} else {
alert('Uncaught Error.\n' + jqXHR.responseText);
}
}
});

Since we don't have access to, or sufficient information to replicate, your dev server, the best we can do is suggest a few things that might fix it. Here are the three most likely causes (from my experience):
You're using a relative path instead of an absolute path.
It's possible, if your site is located at, say, [localhost]/site/page.html, that the AJAX request is being interpreted by your browser locally, since you used a relative path. So your actual request is possibly being sent to: [localhost]/site/localhost/api/1.1/app_dev.php/getsomething/something... This would also explain why you can copy & paste the URL from the alert(), since copying and pasting it into a URL bar automatically makes it an absolute path.
Solution: Try using an absolute path, like this:
var temp_url = "/api/1.1/app_dev.php/getsomething/something"
You can confirm the URL your app is requesting by checking the 'Network' panel in Dev Tools in either Chrome, Safari, or Firefox.
The current URL you're on ends with a /. See the second answer here; AJAX is picky about whether the current URL you're on ends with a forward slash or not.
Solution: Either add, or remove the forward slash from your current page, if possible.
Localhost might reject your request for CORS reasons. This is probably not your issue at the moment, since you're reporting a 404 error, but be aware that often I've encountered localhost not allowing AJAX requests due to some arcane cross-domain origin policy, so this is a good thing to mention in case you do run into it soon.
Solution: See http://enable-cors.org. If that doesn't work, you'll need to spin up a server to run locally instead of relying on retrieving files from your filesystem.
Good luck!

Make sure the file you has created is having valid file Type like PHP file or just copy paste the existing valid working php file and write you ajax code in it. It will work now. myAjax file shown in below image is invalid file and material is valid PHP file

Related

How to show the current status of the downloading file in the popup of the chrome extension?

There is a python server that receives a GET request with a file_id and it triggers downloading that file from another website to a local directory at the python server side. This is done by ajax request in popup.js. I can get the percentage of the downloading file and I can log it continuously in the console. Problem is that I want to show that status as a downloading bar in the popup.html. Is there a way to continuously listen on a event after request like socket.io? I really stuck thinking about how to implement that.
python server
app = Flask(__name__)
#app.route("/<file_id>", methods = ['GET'])
def main(course_id):
// trigger the file downloader this is running asynchronously and
// logs the amount of downloading
response = jsonify({'message': file_id + ' will be downloaded!!'})
response.headers.add('Access-Control-Allow-Origin', '*')
return response
popup.js
$(function(){
$('#download_button').click(function(){
chrome.storage.sync.get(['fileID'], function(result) {
$.ajax({
type: 'GET',
url: "http://localhost:80/"+result.fileID,
crossDomain: true,
success: function(response) {
alert("success: "+response.message);
// here I need to start showing the status of the downloading file
},
error: function (err) {
alert("error");
}
});
})
});
});
Please help me to design this use case, Thanks in advance!!
I'm answering my own problem. I got this resolved by generating urls for the files and send them as the respond to the jQuery request. Then downloading status of each file could be handled independently without much of struggle.

Ajax call not working in Virtual Host in WAMP

I am working on a CI project, and for that, I have created a virtual host in wamp. It's working good. But the main problem started now. Whenever I call Ajax request it with/without giving the ajax post URL it shows a result. I don't know what is the issue..
I am clicking on forgot password link and then it opens a popup with forgot password form.
Without URL
$.get('').done(function (msg) {
console.log('Yes');
console.log(msg);
}).fail(function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
});
Result
In this case I am getting the result (it's going in "done") but giving me the whole login page HTML.
With URL
$.get('http://fileupload.local/login/getresetpassword').done(function (msg) {
console.log('Yes');
console.log(msg);
}).fail(function (xhr, status, error) {
console.log(xhr);
console.log(status);
console.log(error);
});
Result
I have tried too many solutions over google, but couldn't find the right one. Now I am pulling my hair and want to complete it.
Your Ajax looks ok to me. It should work. I have some suggestions:
Open directly Url: http://fileupload.local/login/getresetpassword in your browser. We will see the result (Seem that it will return the whole page?)
Check the server code. I think it's our main issue. Will it return the JSON type or not?
It was a config issue. It resolved by just change $config['uri_protocol'] = 'QUERY_STRING'; to $config['uri_protocol'] = 'REQUEST_URI';

Chrome gives "XMLHttpRequest Exception 101" in some cases when doing an Ajax request

I have a JavaScript application that works like this:
Uploads a file, receives the uploaded file ID as a response
This is done using the BlueImp uploader
Uses the file ID to refer to the file in subsequent requests, in this case to receive a preview of the uploaded file.
This is the code for the file upload 'complete' handler. It's originally written in Coffee Script (http://pastebin.com/708Cf9tu).
var completeHandler = function(e, data) {
var url;
if (data.textStatus !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget i konsollen");
console.group('Upload failure');
console.error(data.textStatus);
console.error(data.result);
console.groupEnd('Upload failure');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
return;
}
self.fileUploadResponse = data.result;
url = "" + config.api_root + "/" + config.api_path_tabulardatafilepreview;
return $.ajax(url, {
type: 'POST',
dataType: 'json',
async: false,
data: {
'file_handle': data.result.file_handle,
'rownum': 5
},
complete: function(req, text_status) {
if (text_status !== 'success') {
alert("Noe gikk galt. Debug informasjon er logget " + "i konsollen");
console.group('Failed to receive data file preview');
console.log(text_status);
console.log(req.responseText);
console.log(req);
console.groupEnd('Failed to receive data file preview');
selectButton.removeClass('disabled');
uploadButton.removeClass('disabled loading');
uploadButton.html('Last opp');
}
self.previewData = JSON.parse(req.responseText);
return self.setStage(2);
}
});
};
This works brilliantly in FireFox, but in Chrome I just started to get an error in the second jQuery Ajax request. It now returns with status "error", with no responseText and with statusText set to "Error: NETWORK_ERR: XMLHttpRequest Exception 101". Though this doesn't happen in all cases. The uploaded file doesn't seem to have anything to do with the issue, because a 10KB csv file works, a 120KB xlsx file fails but a 1.2MB xlsx works. Additionally it's the second Ajax request that fails, and it doesn't do anything but send two small integers to the server. Why does that fail!?
Also this just started happening today. I haven't changed anything that I know of, and I have not updated Chrome.
Does anyone have a clue as to why Chrome is doing this? Can it have anything to do with an Ajax request being launched in the complete handler of a previous Ajax request?
Thanks for any guesses that can help me solve this
Turns out it's a bad idea to start lengthy processes inside Ajax event handlers. In my case, starting a new synchronous Ajax request in the event handler was the mistake. I have since made both requests asynchronous and separated the code into neat functions, and I'm no longer bothered by the exception.

Error handling when downloading a file from a servlet

I have a web application that must work with IE7 (yeah i know..) where the frontend is entirely made with ExtJS4, and theres a servlet used to download files. To download a file i send some parameters so i cant simply use location.href. it must be a POST.
So far it works, but when an exception is thrown in the servlet i dont know how to handle it to show the user some alert box or some message without redirecting to another page.
In my webapp im also using DWR and im aware of the openInDownload() function, but it triggers a security warning in IE.
So, (finally!) the question is
Using this code:
post = function (url, params) {
var tempForm=document.createElement("form");
tempForm.action=url;
tempForm.method="POST";
tempForm.style.display="none";
for(var x in params) {
// ...snip boring stuff to add params
}
document.body.appendChild(tempForm);
tempForm.submit();
return tempForm;
}
is it possible to stay in the same page after submitting ?
or with this other one:
Ext.Ajax.request({
url: './descargaArchivoNivs',
method: 'POST',
autoAbort: true,
params: {
nivs: jsonData
},
success: function(response){
// HERE!!
// i know this is wrong
document.write('data:text/plain,' + response.responseText );
/* this looked promising but a warning pops up
var newwindow = window.open();
newwindow.document.open();
newwindow.document.write('data:text/plain, ' + response.responseText );
newwindow.document.close();*/
},
failure: function(resp){
alert('There was an error');
}
});
is it possible to open the file download dialog // HERE!! with the response content??
or is there some other way to open the file download dialog on success, and on failure show a friendly message without losing the users input (the params of the POST) ?
(sorry if this post was too long)

JQuery $.post() doesn't work

Can any one help me with the following code:
$(document).ready(function() {
$("#add_user").submit(function() {
$.post( "../php/register_sql_ins.php",
{r_fname: $("#fname").val(),
r_lname: $("#lname").val(),
r_uname: $("#uname").val(),
r_pass: $("#pass").val(),
r_authLevel: $("#authLevel").val(),
r_email: $("#email").val(),
r_company: $("#company").val(),
r_phone: $("#phone").val(),
r_address: $("#add").val()}, function(result) {
alert(result);
}
);
return false;
});
});
This should store my user data in a sql table. the php part of code(register_sql_ins.php) works fine. but this query piece of code just doesn't work!! and I have no idea what is the problem!
With Firebug it returns false every time!
By the way sorry for bad english. It's not my mother tong!
There are two places where I would look for the cause of such error:
Network tab in Firebug. Check what is sent to the server and what is the response. If data sent is correct and server replies with status 200, then you have to debug your PHP script, else
Server logs. If the request failed to complete succesfully, log will contain the reason.

Resources