AJAX call responseText empty - javascript

I have a small,simple application.Its on Tomcat 7.Testing on Firefox browser.
My html page resides in
%CATALINA_HOME%\webapps\examples\servlets.
So, I access my html page using the URL:
http://localhost:8080/examples/servlets/userinputs.html
My java servlet(calls a third party API and returns a text/html response) resides in %CATALINA_HOME%\webapps\examples\WEB-INF\classes.
I am using AJAX call in my js file to call this servlet via the URL:
http://localhost:8080/examples/servlets/servlet/challengetask
The responseText returned is empty.If I access the servlet from browser,I can see the response.
I did go through the same-domain policy and searched
the internet for similar problems.However, I am unable to figure out as to why the responseText is empty and what EXACTLY is the problem.
My AJAX call :
var request =false;
if(window.XMLHttpRequest){
request = new XMLHttpRequest();
}
else {
if (window.ActiveXObject) {
try{
request = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e){
}
}
}
if(request){
request.open("GET",url,true);
request.onreadystatechange = callBack;
request.setRequestHeader("Connection","Close");
request.setRequestHeader("Method","GET"+url+"HTTP/1.1");
request.send();
}
else {
alert("Sorry could not create an XMLHttpRequest");
}
}
function callBack(){
if(request.readyState == 4){
if(request.status == 200){
alert(request.responseText);
}
} }
P.S: Both the html and js are in the same folder.
Please help.

In your code there's unwanted curly bracket (see like in the and of my snippet), remove it.
Second thing is why are you using connection=close, remove it if you don't really need it.
if(request){
request.open("GET",url,true);
request.onreadystatechange = callBack;
request.setRequestHeader("Connection","Close");
request.setRequestHeader("Method","GET"+url+"HTTP/1.1");
request.send();
}
else {
alert("Sorry could not create an XMLHttpRequest");
}
}

Fixed it by replacing localhost with 127.0.0.1.

Related

Using AJAX to execute a PHP script through a JavaScript function

I have an anchor link with no destination, but it does have an onClick event:
<li><a href onClick='deletePost()'> Delete </a> </li>
I understand that I cannot directly execure PHP code blocks in JavaScript due to the nature of PHP and it being a server side language, so I have to utilize AJAX to do so.
When the delete link is clicked, I need it to execute this query (del_post.php)
<?php include("connect.php");
$delete_query = mysqli_query ($connect, "DELETE FROM user_thoughts WHERE id = 'id' ");
?>
I have tried to understand AJAX using similar past questions, but due to being relatively new, I cannot completely grasp it's language. Here is what I have tried:
function deletePost() {
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
}
}
But clicking the link just changes the URL to http://localhost/.
I believe the (main) problem is your empty "href" attribute. Remove that, or change it to href="#" or old school href="javascript:void()" (just remove it, imo).
It's been a while since I used XMLHttpRequest and not something like jQuery's .ajax, but I think you need to do it like so (mostly you need to .open/send before you watch for the state change):
var xmlHttpReq = new XMLHttpRequest();
if (xmlHttpReq) {
xmlHttpReq.open('GET', 'your-uri-here.php', true/false);
xmlHttpReq.onreadystatechange = function () {
if (xmlHttpReq.readyState == 4 && xmlHttpReq.status == 200) {
console.log('success! delete the post out of the DOM or some other response');
}
else {
console.log('there was a problem');
}
}
xmlHttpReq.send();
}
Can you please provide your : del_post.php file?
Normally you can show a text or alert in a
<div id="yourname"></div>
by using callback in an AJAX request :
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("yourname").innerHTML = xmlhttp.responseText;
}
This response is coming from your PHP file for example :
function remove_record(ARG){
if ($condition==true)
echo "TRUE";
else
echo "FALSE";
}
You should remove href attribute from anchor tag and style the element with CSS.
Also, your script should look like this:
<script>
function deletePost() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
// Do something if Ajax request was successful
}
};
xhttp.open("GET", "del_post.php", true);
xhttp.send();
}
</script>
You are trying to make the http request inside the callback.
You just need to move it outside:
function deletePost() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
xmlhttp.open("GET", "del_post.php", false);
xmlhttp.send();
}
Removing the href attribute will prevent the refresh. I believe that is valid in HTML5.
Ok... I'm just a hobbyist, so please forgive me any inaccuracies in the typing but this works: A format I use for an ajax call in an <a> element is:
<a href="javascript:" onclick="functionThatReallyCallsAjax()">
So that I have more flexibility(in case I need to check something before I send the ajax). Now, for an ajax call you need:
What file to call
What to do with the response from the file you called
What to do if an I/O error happens
So we have this function - not mine, leeched amongst thousands from somewhere - probably here :) - and probably well known, my apologies to the author, he is a genius: This is what you call for the ajax thing, where 'url' is the file you want to 'ajax', 'success' is the name of the function that deals with results and error is the name of the function that deals with IO errors.
function doAjaxThing(url, success, error) {
var req = false;
try{
// most browsers
req = new XMLHttpRequest();
} catch (e){
// IE
try{
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
// try an older version
try{
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
return false;
}
}
}
if (!req) return false;
if (typeof success != 'function') success = function () {};
if (typeof error!= 'function') error = function () {};
req.onreadystatechange = function(){
if(req.readyState == 4) {
return req.status === 200 ?
success(req.responseText) : error(req.status);
}
}
req.open("GET", url, true);
req.send(null);
return req;
}
You will naturally need to include the success+error functions:
function dealWithResponse(textFromURL)
{
//textFromURL is whatever, say, a PHP you called in the URL would 'echo'
}
function ohNo()
{
//stuff like URL not found, etc.
alert("I/O error");
}
And now that you're armed with that, this is how you compose the real call inside the function you called at the <a>:
function functionThatReallyCallsAjax()
{
//there are probably many scenarios but by having this extra function,
//you can perform any processing you might need before the call
doAjaxThing("serverFile.php",dealWithResponse,ohNo);
}
One scenario might be when you need to pass a variable to the PHP you didn't have before. In this case, the call would become:
doAjaxThing("serverFile.php?parameter1=dogsRock",dealWithResponse,ohNo);
And now not only you have PHP sending stuff to JS, you have JS sending to PHP too. Weeeee...
Final words: ajax is not a language, its a javascript 'trick'. You don't need to fully understand what the first 'doAjaxThing' function does to use this, just make sure you are calling it properly. It will automatically 'call' the 'deal WithResponse' function once the response from the server arrives. Notice that you can continue doing your business (asynchronous - process not time-tied) till the response arrives - which is when the 'deal WithResponse' gets triggered -, as opposed to having a page stop and wait (synchronous - time tied) until a response arrives. That is the magic of ajax (Asynchronous JAvascript and Xml).
In your case you want to add the echo("success") - or error! - in the PHP, so that the function 'dealWithResponse' knows what to do based on that info.
That's all I know about ajax. Hope this helps :)

My IP gets blocked for odd reasons by my server each time i do ajax continuous update

Everytme when i call ajax and i use timeout to repeat the ajax function, after a few minutes, i can't have access to my website, it;s like my IP address gets blocked from my server, by the way i am using 000webhost for hosting my server. The code is below .Can someone assist me and tell me what i can do solve this problem without telling me to use websockets/comets, i want to use AJAX for very frequent update maybe up to 10 seconds. Not a most but it will be great if someone can show solutions without the use use of JQuery Thank you.
function display_message(user,id){
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE 8 and older
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
/**********************************************************/
var data = "user="+user+"&id="+id;
xhr.open("POST", "message_read.php", true);
xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xhr.send(data);
xhr.onreadystatechange = display_data;
function display_data() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
document.getElementById("message_box").innerHTML =xhr.responseText;
mymessage =setTimeout(display_message(user,id), 5000);
} else {
alert('There was a problem with the request.');
}
}
}
}

Ajax POST never gets sent?

I'm having an issue with my ajax POST for some reason the POST is never made! can't for the life of me work it out?
yeah so I used the network debug tool in firefox to check the POST request but the POST request never gets made..
The function is definitely getting called too as I have added an alert alert("start") to the beginning of the function which does run.
AJAX
<script>
function updateContentNow(pid2, status2) {
var mypostrequest = new ajaxRequest();
mypostrequest.onreadystatechange = function() {
if (mypostrequest.readyState == 4) {
if (mypostrequest.status == 200 || window.location.href.indexOf("http") == -1) {
document.getElementById("livestats").innerHTML = mypostrequest.responseText;
} else {
alert("An error has occured making the request");
}
}
}
var parameters = "cid=clientid&pid=6&statusinfo=approve";
mypostrequest.open("POST", "http://mydomain.com.au/content-approval/ajax.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
</script>
UPDATED WORKING: thanks peps..
<script>
function updateContentNow(pid2,status2)
{
var mypostrequest=new XMLHttpRequest()
mypostrequest.onreadystatechange=function(){
if (mypostrequest.readyState==4){
if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
document.getElementById("livestats").innerHTML=mypostrequest.responseText;
}
else{
alert("An error has occured making the request");
}
}
}
var parameters="cid=<?=$clientID?>&pid="+pid2+"&statusinfo="+status2;
mypostrequest.open("POST", "http://mydomain.com.au/content-approval/ajax.php", true);
mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
mypostrequest.send(parameters);
}
</script>
Are you using some external Ajax classes, at least ajaxRequest() object doesn't exist in plain JavaScript. Try to substitute this line
var mypostrequest = new ajaxRequest();
by that:
var mypostrequest=new XMLHttpRequest();
Then even calling your method with
updateContentNow("","");
at least makes the POST request as you easily can see with Firebug.

Using JavaScript code for navigating (InnerHTML)

I'm using this code below for the navigation system on my site, the purpose is to open an HTML page within a div .. (InnerHTML), but, when I'm clicking one of my menu links I'm getting the JavaScript notification "Problem: " (see "else" in the JavaScript code block). This code is fixed (good) for SEO aspect.
Can someone please tell me what the problem with it is? I'm trying to preserve the code as it is as much as possible.
Thank you in advance for your help!
JavaScript code:
function processAjax(url)
{
if (window.XMLHttpRequest) { // Non-IE browsers
req = new XMLHttpRequest();
req.onreadystatechange = targetDiv;
try {
req.open("GET", url, true);
}
catch (e) {
alert(e);
}
req.send(null);
} else if (window.ActiveXObject) { // IE
req = new ActiveXObject("Microsoft.XMLHTTP");
if (req) {
req.onreadystatechange = targetDiv;
req.open("GET", url, true);
req.send();
}
}
return false;
}
function targetDiv() {
if (req.readyState == 4) { // Complete
if (req.status == 200) { // OK response
document.getElementById("containerDiv").innerHTML = req.responseText;
} else {
alert("Problem: " + req.statusText);
}
}
}
In HTML body:
<a onclick="return processAjax(this.href)" href="example.html">CLICK ME</a>
<div id="containerDiv"></div>
The server returned a non-200 response. If you're using a debugger like Firebug, Chrome Developer, or IE Developer, check the Network tab to see exactly where your XHR went, and what the response was.

Reading Server Side file with Javascript

Does anyone know of a tutorial on how to read data from a server side file with JS? I cant seem to find any topics on this when I google it. I tried to use but it does not seem to work. I just want to read some data from a file to display on the page. Is this even possible?
var CSVfile = new File("test.csv");
var result = CVSfile.open("r");
var test = result.readln();
To achieve this, you would have to retrieve the file from the server using a method called AJAX.
I'd look into JavaScript libraries such as Mootools and jQuery. They make AJAX very simple use.
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/mootools/1.6.0/mootools-core.min.js"></script>
<script type="text/javascript">
//This event is called when the DOM is fully loaded
window.addEvent("domready",function(){
//Creating a new AJAX request that will request 'test.csv' from the current directory
var csvRequest = new Request({
url:"test.csv",
onSuccess:function(response){
//The response text is available in the 'response' variable
//Set the value of the textarea with the id 'csvResponse' to the response
$("csvResponse").value = response;
}
}).send(); //Don't forget to send our request!
});
</script>
</head>
<body>
<textarea rows="5" cols="25" id="csvResponse"></textarea>
</body>
</html>
If you upload that to the directory that test.csv resides in on your webserver and load the page, you should see the contents of test.csv appear in the textarea defined.
You need to use AJAX. With jQuery library the code can look like this:
$.ajax({ url: "test.csv", success: function(file_content) {
console.log(file_content);
}
});
or if you don't want to use libraries use raw XMLHTTPRequest object (but you I has different names on different browsers
function xhr(){
var xmlHttp;
try{
xmlHttp=new XMLHttpRequest();
} catch(e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
alert("Your browser does not support AJAX!");
return false;
}
}
}
return xmlHttp;
}
req = xhr();
req.open("GET", "test.cvs");
req.onreadystatechange = function() {
console.log(req.responseText);
};
req.send(null);
UPDATE 2017 there is new fetch api, you can use it like this:
fetch('test.csv').then(function(response) {
if (response.status !== 200) {
throw response.status;
}
return response.text();
}).then(function(file_content) {
console.log(file_content);
}).catch(function(status) {
console.log('Error ' + status);
});
the support is pretty good if you need to support browser that don't support fetch API you can use polyfill that github created

Categories