Ajax response problem - javascript

I'm handling a very (VERY) simple ajax error, but I cannot manage to fix it:
I have the following structure:
\manager\javascript\ajax.js
\manager\manager.jsp
\manager\test.jsp
In my ajax.js file I have a VERY simple function (without parameter, to make things easier)
function makeAjaxRequest() {
http.open('get', 'test.jsp');
http.onreadystatechange = processResponse();
http.send(null);
}
function processResponse() {
alert("Ready State: " + http.readyState);
if(http.readyState == 4){
var response = http.responseText;
document.getElementById('ajaxResult').innerHTML = response;
}
}
And finally, my test.jsp file contains only:
<% out.print("JSP result");%>
In my manager.jsp I call the function but I receive only one "alert" from the processResponse with readyState = 1...
For sure there is something I'm missing in some step.
Could you help?
Thanks a lot.
Cheers,
Lucas.
EDIT
For sure in my ajax.js file there is also the function to get a xmlHttpObject.

This line is wrong
http.onreadystatechange = processResponse();
Remove the () to assign the actual function, not the result of the function.

Related

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

Calling JavaScript function after updating table with PHP

I have a simple website that uses JavaScript to collect user input and sends data to PHP script (script is an external php file) via AJAX request. PHP script updates database with this information.
Now, i have a JS function on my website that i want to call only after PHP script is sucessfuly run and database updated. I don't need any data from database or PHP script, i only want to make sure that database is updated before calling this Javascript function.
This is what AJAX request looks like:
function ajax_post(){
if (typeof featureId !== 'undefined') {
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "parse_file.php";
var fn = featureId;
var vars = "featureId="+fn;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(vars); // Actually execute the request
document.getElementById("status").innerHTML = "processing...";
hilites.destroyFeatures();
featureId = undefined;
}
else {
window.alert("Select polygon first");
}
}
What is the best way to do this? Some examples would really help.
Looking at your code, you simply need to call the function around this part:
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
// CALL YOUR FUNCTION HERE
}
}
The best solution is to use a Promise. However, this is not supported in IE 11, so you will need to use a polyfill on some browsers.
Here is an example using jQuery.
// This is the function you want to call after the script succeeds
function callbackSuccess() {
console.log('Done!');
}
// This is the data you want to submit to the PHP script
var myData = {
hello: "world"
};
// This is the actual AJAX request
$.post('/my-script.php', myData).done(function(){
callbackSuccess();
});
Add this to the end of your php save-function:
header('Content-Type: application/json; charset=utf-8');
echo json_encode(array('status' => 'SUCCESS'));
Making the call:
$.getJSON('url_to_your_php_file.php', function(data) {
if (data.status == 'SUCCESS') {
console.log('Save complete');
}
else {
console.log('oops, something went wrong!!');
}
});
It's possible to return something like ERROR, this will return:
console.log('oops, something went wrong!!');
You may try the following:
In php you can use return code from sql statement
echo $sqlResult = $conn->query($sqlStatement);
On Javascript, you can try the following
$.ajax({
url: 'file.php',
type: 'POST',
data: {
data1 : data1,
data2: data2
},
success: function(data){
if(data == success_code){
alert("Success")
}
}
Hope this helps!
Completing ajax request without errors does not mean that the data is saved to DB without errors.
Even if your PHP script fails to save the data, it probably echos some error message or even empty output as regular HTTP response, and it would show as success as far as the ajax request goes.
If your intention is to make sure that the data is really saved before calling the JS function, then the PHP script should containg enough error handling.
If you write the PHP script to return response status code based on the real outcome of save operation, then you can rely on those status codes in ajax response handling (success = ok, error = not ok).
Bu what I usually do, is that instead of using HTTP status codes, I echo "OK" or something similar at the end of succesfull PHP execution (and "ERROR" if there are any errors), and then check for those strings in ajax response handler (hr.responseText in your code).
Maby you have to try this:
setTimeout(function(){
//your function here...
}, 500);

AJAX - PHP - Content Not Loading

I am new in AJAX.
I am trying to load some content from my PHP file into the load.html. i made the function on the onKeyUp Event of a textbox.
But its always showing "UNDEFINED" as the output . :(
Please help me
The load.html file
<!DOCTYPE html>
<html>
<head>
<script>
function NickName(nick){
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function(){
if(xmlhttp.status==200 && xmlhttp.readyState ==4){
document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
}
}
xmlhttp.open("GET","myphp.php?key="+nick,true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="divNick"></div>
<input type="text" id="text_box" onKeyUp="NickName(this.value)">
</body>
</html>
And the myphp.php file
<?php
if(isset($_GET['key']))
{
$key = $_GET['key'];
$choice1 = "Shifar";
$choice2 = "Nidal";
if($key==$choice1)
{
echo "Shifz";
}
else if($key==$choice2)
{
echo "Steavz";
}
else
{
echo "No Match Found";
}
}
?>
Thanks in Advance.
Shifar Shifz
its because you dint specify the correct function name.
You defined a function named NickName and called another named NicKName
updated to comments
its coming as undefined because of another typo u made xmlhttp.reponseText instead of xmlhttp.responseText
There is typo. your function name is NickName you are calling NicKName. K is capital
Change document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
to document.getElementById("divNick").innerHTML = xmlhttp.responseText;
again a typo. reponseText --> responseText
Try like this :
xmlhttp.open("GET","myphp.php?key="+nick,true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send();
xmlhttp.onreadystatechange = function()
{
if(xmlhttp.status==200 && xmlhttp.readyState ==4)
{
document.getElementById("divNick").innerHTML = xmlhttp.reponseText;
}
}
I think the order is important and NickName is not NicKName
I can see there is a typo error in your function name. When you call the function you have used NicKName but the function is actually defined as NickName. the (k) is capitalized in your calling statement.
Other advice for you, write Ajax like you have done is a very old approach. And most importantly you will have a great deal of coding for many browsers...you are supposed to deal with all the browsers out there. So why don't you use other ajax approach. I advice you to use jQuery $.ajax. Its very simple and handles all the cross-browser compatibility issues.
For eg. the above line of code could be replaced with....
$('#divNick').load('myphp.php?key='+nick);
Just one line. the other is you can also use the $.ajax which can let you do both POST and GET requests as you wish.
Most important you have said you are new to Ajax. If so why don't you already start reading about jQuery...besides its very rewarding in both by saving you time and when you are done, you will see how many job position require jquery as a skill set.
Hope this will help.
Spelling mistake on your ajax code
Instead of - document.getElementById("divNick").innerHTML = xmlhttp.responseText;
You typed - document.getElementById("divNick").innerHTML = xmlhttp.reponseText;

I can't send PHP variables to JavaScript

I'm trying to send parametres from a .php file to my Javascript but I can't even manage to send a String.
Javascript fragment:
var params = "action=getAlbums";
var request = new XMLHttpRequest();
request.open("POST", PHP CODE URL, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.send(params);
request.onreadystatechange = function() {
var phpmessage = request.responseText;
alert(phpmessage);
};
PHP fragment:
$deviceFunction = $_POST["action"];
if ($deviceFunction == "") $deviceFunction = $_GET["action"];
// Go to a function depending the action required
switch ($deviceFunction)
{
case "getAlbums":
getAlbumsFromDB();
break;
}
function getAlbumsFromDB()
{
echo "test message!";
}
The alert containing phpmessage pops up but it's empty (it actually appears twice). If I do this the alert won't even work:
request.onreadystatechange = function() {
if(request.status == 200) {
var phpmessage = request.responseText;
alert(phpmessage);
}
};
The readystatenchange event will be called each time the state changes. There are 5 states, see here: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest#readyState
Rewrite your JS:
request.onreadystatechange = function () {
if (request.readyState == 4) {
console.log('AJAX finished, got ' + request.status + ' status code');
console.log('Response text is: ' + request.responseText);
}
}
In your code, you only check for the returned status code. The code above will check for the ready state and then output the status code for debbuging.
I know that this answer is more a comment than an answer to the actual question, but I felt writing an answer in order to include nicely formatted code.
I faced a similar problem working with Django. What I did:
I used a template language to generate the javascript variables I needed.
I'm not a PHP programmer but I'm going to give you the idea, let me now if works. The following isn't php code, is just for ilustrate.
<?php
<script type="text/javascript" ... >
SOME_VARIABLE = "{0}".format(php_function()) // php_function resolve the value you need
</script>
?>
The I use SOME_VARIABLE in my scripts.
Please specify your onreadystatechange event handler before calling open and send methods.
You also should make your choice between GET and POST method for your request.
If you want to popup your message only when your request object status is OK (=200) and readyState is finished whith the response ready (=4), you can write :
request.onreadystatechange = function() {
if (request.readyState==4 && request.status==200) {
var phpMessage = request.responseText;
alert(phpMessage);
}
};

Javascript web service request not working

I have a working PHP web service that returns data (if I input the url into the browser I get the results). I need to use Javascript to retrieve this data from my web service, but I'm not too great with Javascript. Based on all the tutorials, examples, and StackOverflow questions and answers I've read this should work, but it doesn't. Please Help!
<script type="text/javascript">
var url = '*working url*';
var xmlhttp = null;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
else { document.write('Perhaps your browser does not support xmlhttprequests?'); }
xmlhttp.open('GET', url, true);
xmlhttp.send(null);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myObj = eval ( xmlhttp.responseText );
} else {
// wait for the call to complete
}
};
</script>
Also, I need help making sure that I'm calling this correctly. Currently I do it like this, which may be the problem:
<script type="text/javascript">
document.write(myObj);
</script>
I'm aware this doesn't directly answer your question but if you are "not too great" with javascript I would recommend just going straight to jQuery instead of messing with the lower level objects.
It will also help you with cross browser compatibility.
http://jquery.com/
http://api.jquery.com/category/ajax/
However if you have a particularly boring day some time in the future, going back and learning what's going on behind the scenes is always beneficial.
This would be a simple ajax post using jQuery (with a text response):
$.post(
"test.php",
{ postValue1: "hello",
postValue2: "world!" },
function(data){
alert("Success: " + data);
},
"text");
To answer your second question (in comments), the code looks correct but perhaps you're getting a bad response. You can attach additions events onto the ajax call to get additional information.
This code is borrowed and modified from jQuery's site:
http://api.jquery.com/jQuery.post/
I got the function parameter info from:
http://api.jquery.com/jQuery.ajax/
// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.post("example.php", function() {
alert("success");
})
.success(function(data, textStatus, jqXHR) { alert("second success"); })
.error(function(jqXHR, textStatus, errorThrown) { alert("error"); })
.complete(function(jqXHR, textStatus) { alert("complete"); });

Categories

Resources