Ajax call not working in Virtual Host in WAMP - ajax

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';

Related

jQuery-Mobile: ajax request stops working after changePage failure

I am presently developing a web application with jQuery mobile. However, I found that when a "changePage" fails, I can no longer send ajax requests. After the failure, all ajax requests return an error. Here's the code executed when the submit button on the form is clicked (it's a basic user login screen):
// Event when user click the Submit login button
$('#submitLogin').on("click", function () {
// submit the user credentials to the server
$.ajax({
type: "POST",
url: "./LogUser",
data: {
EmployeeID: $('#EmployeeID').val(),
EmployeePIN: $('#EmployeePIN').val()
},
dataType: "text",
async: true,
cache: false,
error: function (rqst, text, thrownError) {
$('#dlg-login-error-message').text(thrownError);
$('#dlg-login-error-popup').popup("open");
},
success: function (data) {
if (data == "Success") {
$.mobile.changePage("./LoadScreen/Menu");
}
else {
$('#dlg-login-error-message').text(data);
$('#dlg-login-error-popup').popup("open");
}
}
});
return false;
});
If the post itself fails, I can resubmit without problem. If the .mobile.changePage fails, a "page not found" is displayed, but I am not able to resubmit, ajax no longer making request to the server and jumping directly to the error callback with a "not found" error.
I am guessing the problem comes from the fact that jQuery mobile uses AJAX request to load pages, and that somehow, ajax calls are getting mixed up somewhere.
I did more tests, even intercepted the pageloadfailed event, but nothing works. After the page change failure, AJAX calls no longer sends anything to the server and jump automatically to the error callback function.
I tried with async=false, same problem. I tried debugging jQuery-mobile, but I am still not able to find the "changePage" function itself ( the .code is quite confusing ).
I just spent the last two days trying to figure out a way to resolve this and I am seriously thinking of using something else than jQuery-mobile for our development.
I have found a workaround for my problem, but I do not know the full impact of this solution yet.
To prevent the problem, I had to set the "pushStateEnabled" configuration option to "false".
So if you find yourself with the same problem, try putting the following in a script right before the loading of the "jQuery-mobile" script.
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
Example:
<!-- Load the script for jQuery -->
<script src="~/Scripts/jquery-2.1.4.js"></script>
<!-- Set default for jQuery-Mobile, before it is actually loaded -->
<script>
$(document).bind("mobileinit", function () {
$.mobile.pushStateEnabled = false;
});
</script>
<!-- Load the script for jQuery-Mobile -->
<script src="~/Scripts/jquery.mobile-1.4.5.js"></script>

Custom Error Message after Datatables ajax exception

I am displaying a table of data using datatables 1.10.12. The user can specify input parameters that cause an error on the server. An appropriate error message should be displayed to the user so they can modify their setup, however the only error options seem to be:
SHow the following generic error in an alert: "DataTables warning: table id=trackingTable - Ajax error. For more information about this error, please see http://datatables.net/tn/7"
Show the generic error in the browser console
Modify the server to return no rows, that is fail silently.
Does anyone know how to show a custom error after a datatables ajax request fails?
The following code sample is taken from the datatables documentation. Datatables handles the ajax call and handles success and error.
$(document).ready(function() {
$('#example').DataTable( {
"ajax": '../ajax/data/arrays.txt'
} );
} );
A 4th option I could add to the list would be to modify the datatables source code to handle the an error response myself. Which I'm not that keen on.
This question was asked in 2015 however it did not get an answer. See:
display server side exception
If you pass an object to the ajax property you can override the jQuery.ajax() error method:
$(document).ready(function () {
$('#example').DataTable({
ajax: {
url: '../ajax/data/arrays.txt',
error: function (jqXHR, textStatus, errorThrown) {
// Do something here
}
}
});
});
https://datatables.net/reference/option/ajax#object
This will stop the standard error message in the alert box.
Please note, it is not recommended to override the success method of jQuery.ajax() as it is used by DataTables.
You can implement your own custom error message globally like the example below.
$(document).ready(function() {
$.fn.dataTable.ext.errMode = () => alert('Error while loading the table data. Please refresh');
$('#example').DataTable( {
"ajax": '../ajax/data/arrays.txt'
});
});
Answering just in case someone is still looking for a solution.
In my case, I did the following
At server side set DataTablesOutput object.setError("ErrorMsg")
In my js method $.fn.dataTable.ext.errMode = 'none'; to avoid the error popup.
Created an error div in my page to display the custom error message
Added the below to my js method to handle error
$('#myDataTable')
.on('error.dt',
function(e, settings, techNote, message) {//Logic to set the div innertext
}
try {
$.ajax({
-------
-------
success: function (data){
//ShowDataTable is a js Function which takes ajax response data and display it.
ShowDataTable(data);
},
//this error will catch server-side error if request fails
error: function (xhr, textStatus, errorThrown) {
alert(errorThrown);
ShowDataTable(null);
}
})
}
//this catch block will catch javascript exceptions,
catch (Error) {
if (typeof console != "undefined") {
console.log(Error);
ShowDataTable(null);
alert(Error);
}
}
EDIT
If you are willing to accept the error (for example if you cannot alter the backend system to fix the error), but don't want your end users to see the alert() message, you can change DataTables' error reporting mechanism to throw a Javascript error to the browser's console, rather than alerting it. This can be done using:
$.fn.dataTable.ext.errMode = 'throw';

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

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

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