AJAX and Javascript not working - javascript

NO JQUERY. I am using peoplecode which is similar to JSP, ASP, and ZXZ. The ajax request is triggered am I am trying to pull the text 'Hello World' from this script...
Function IScript_AJAX_Test()
%Response.Write("<div id='hello'>Hello World</div>");
End-Function;
My javascript function that makes the ajax call looks like this...
function AJAX_test (ajax_link) {
if (typeof XMLHttpRequest == 'undefined') {
XMLHttpRequest = function() {
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch(e) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch(e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch(e) {}
throw new Error('This browser does not support XMLHttpRequest or XMLHTTP.');
};
}
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (request.readyState == 4 && request.status == 200) {
document.getElementById('ajax').innerHTML = request.responseText.document.getElementById('hello').innerHTML;
//document.getElementById('ajax').innerHTML = 'Testing';
}
}
request.open('GET', ajax_link, true);
request.send();
//document.getElementById('ajax').innerHTML = ajax_link;
}
As you can see in this line..
document.getElementById('ajax').innerHTML = request.responseText.document.getElementById('hello').innerHTML;
...I am trying to grab the text by getting the innerHTML from the id. This isn't working though. When I click the button nothing happens.
I tried using the line below, but it returns an entire new page where the id would be (probably because of Peoplesoft)...
document.getElementById('ajax').innerHTML = request.responseText;
Can someone help me achieve this...

I tried your code and it works for me, with
Function IScript_AJAX_Test()
%Response.Write("<div id='hello'>Hello World");
End-Function;
and in the javascript
document.getElementById('ajax').innerHTML = request.responseText;
Make sure you call the content servlet (psc), not the portal servlet (psp), e.g.
'http://peoplesofturl/psc/ps/EMPLOYEE/HRMS/s/WEBLIB_Z_SYS.FUNCLIB.FieldFormula.IScript_AJAX_Test', otherwise you'll get the response wrapped in the peoplesoft portal.
You can generate the url from peoplecode with the GenerateScriptContentRelURL or GenerateScriptContentURL functions.

Make it simple:
Function IScript_AJAX_Test()
%Response.Write("Hello World");
End-Function;
Javascript:
document.getElementById('ajax').innerHTML = request.responseText;

Ajax might be two types. One is server-side and the other one is client-side. You are trying to get data from client side. In this case ajax fetch nothing but the whole page result of a page not a portion. You will have the whole page result(HTML output) if you write
document.getElementById('ajax').innerHTML = request.responseText;
But you cannot fetch just only the innerHtml part of certain portion of another page. On that case you will get the whole page.

Related

writing to a file with php and javascript

So I want to use buttons on my HTML page to call a php program that will write to a text file. What I currently get is a success package from my Ajax function, but the file that it has supposed to have written does not exist.
my HTML
<button type = "button" onclick = "getRequest('changeState.php', changeState('1'), 0)"></button>
my Javascript functions:
function getRequest(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;
}
function changeState(input)
{
state = input;
document.GetElementById("state_current").innerHTML = state;
}
My PHP file:
<?php
$f = fopen("file.txt");
fwrite($f, "Hello World");
fclose($f);
?>
I'll be honest, I'm very new to php, but my syntax seems fine because I'm not dropping any error messages, and I know that the program runs successfully because I get the success function to run. Have I missed something glaringly obvious?
file.txt should be created, if calling your PHP-script directly. If not probably PHP is not allowed to create it. Unfortunately its not that easy to understand which user is used to run PHP, and this user must have the rights to write to the webroot-folder of the server. As far as I know this depends on how PHP is executed (module vs CGI).
I would give it a try to change the folders access rights to "777" (anyone is allowed to do anything).
The changeState function doesn't get called on success because you are passing the value returned by the changeState function not the function reference, should be:
<button type = "button" onclick = "getRequest('changeState.php', changeState, 0)"></button>
You can also check on the Network Tab on the Developers Tools to see if you actually sent the request to the URL. If you didn't, then there's something wrong with your URL or your server.

Reload search results on new search in web application (without jQuery)

I have a simple web app that uses an API to return search results from a database and uses ajax to insert them into an empty ul element on the page. (Using JSONP with a cross domain request)
I cant figure out how to do it using javascript, everywhere I've found uses jQuery. I want to be able to have them enter another search term and have it clear the existing content from the page.
Currently if you conduct a second search it just appends the new results to the bottom of the existing list.
Once you have the content (returned from your API call using AJAX) you just can assign it to your ul or div e.g. document.getElementById('YourULID').innerHTML = "The content you got from your AJAX call"
From vanilla.js (so you can compare with jQuery):
var r = new XMLHttpRequest();
r.open("POST", "path/to/api", true);
r.onreadystatechange = function () {
if (r.readyState != 4 || r.status != 200) return;
alert("Success: " + r.responseText);
};
r.send("banana=yellow");
if i understand what you want. You want to get result from server and insert them into a ul form field of your webpage.
This is just an example and might help
function createRequest(){
try{
request = new XMLHttpRequest();
}catch (tryMS){
try{
request = new ActivXObject("Msxml2.XMLHTTP");
}catch (otherMS){
try{
request = new ActivXObject("Microsoft.XMLHTTP");
}catch (failed){
request = null;
}
}
}
return request;
}
function loggin(user_id,password){
request = createRequest();
data = new FormData();
data.append('user_id',user_id.value);
data.append('password',password.value);
request.onreadystatechange=function(){
if(request == null){
alert('Unable to connect');
}else{
if(request.readyState==4){
if(request.status==200){
if(request.responseText){
document.location.href = request.responseText;
}
}
}
}
}
This will create and HTTP request. Post data to your server then fetch the result and throw it back to your javascript, then staight to your webpage. Use request.responseText to append/insert to the appropriate field
I figured it out by using a few simple lines of html when onsubmit occurs with the search field:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}

Simultaneous ajax calls

I'm trying to make 2 (or more) ajax calls simultaneously. I don't want to use jQuery, only pure JavaScript.
Most of the time, it works. data1 will output data from sample.com/ajax1 and data2 will output data from sample.com/ajax2, but sometimes (1 from 10) the second AJAX call will display result from the first one.
Why is this happening? Both AJAX requests are requesting data from the same domain, but from different URLs. Is there any way how to prevent this behavior?
Here is the script:
// First AJAX
var xmlhttp1;
// Second AJAX
var xmlhttp2;
if (window.XMLHttpRequest) {
xmlhttp1 = new XMLHttpRequest();
} else {
xmlhttp1 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange = function() {
if (xmlhttp1.readyState == 4 && xmlhttp1.status == 200) {
data = JSON.parse(xmlhttp1.responseText);
console.log('data1: ' + data);
}
}
xmlhttp1.open("GET", "http://sample.com/ajax1", true);
xmlhttp1.send();
if (window.XMLHttpRequest) {
xmlhttp2 = new XMLHttpRequest();
} else {
xmlhttp2 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
data = JSON.parse(xmlhttp2.responseText);
console.log('data2: ' + data);
}
}
xmlhttp2.open("GET", "http://sample.com/ajax2", true);
xmlhttp2.send();
First of all, I recomment wrapping your xmlHttpRequest generation/handling in a function, so you don't duplicate code that much.
The problem you have there is that the data variable is global, so both ajax callbacks are using the same variable. You can fix it using the var keyword in both calls.
xmlhttp2.onreadystatechange = function() {
if (xmlhttp2.readyState == 4 && xmlhttp2.status == 200) {
var data = JSON.parse(xmlhttp2.responseText);
console.log('data2: ' + data);
}
}
Because you're not properly encapsulating data. The way you have it written, data is a global object, so it's available to be modified by either ajax call. Since ajax calls are asynchronous, this will lead to unpredictable values for data.
The problem is probably because you forgot to define data inside your function
anyway with this function you can create multiple requests and have more control over them..
var req={};
function ajax(a){
var i=Date.now()+((Math.random()*1000)>>0);
req[i]=new XMLHttpRequest;
req[i].i=i;
req[i].open('GET',a);
req[i].onload=LOG;
req[i].send();
}
function LOG(){
console.log(this.i,this.response);
delete req[this.i];//clear
}
window.onload=function(){
ajax('1.html');
ajax('2.html');
ajax('3.html');
}
uses xhr2... you need to modify the code to make it work with older browsers.

Ajax response works after two clicks?

I just wrote a basic user-login system where the html page uses javascript to send the ajax request to a servlet which accesses through database.
Here's the js code
var res;
function getXMLObject()
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
res=xmlhttp.responseText;
}
else {
return false;
alert("Error during AJAX call. Please try again");
}
}
function ajaxFunction() {
var veid=document.getElementById("eid").value;
var vpwd=document.getElementById("pwd").value;
//window.alert('here inside ajaxFunction'+vconf+' '+vseid);
if(xmlhttp) {
xmlhttp.open("GET","check_login?eid="+ veid +"&pwd="+ vpwd,true); //this is the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function def()
{
//window.alert('hi');
ajaxFunction();
//alert('res:'+res);
if(res=='y')
{
return true;
}
else
{
document.getElementById("uhidden").style.color="#CC0000";
document.getElementById("uhidden").innerHTML="Invalid E-Mail ID or Password"
return false;
}
}
But the code works only after two clicks :(
Any help guys?
Your def function calls ajaxFunction and then straight away checks the res variable. However ajaxFunction just sends the AJAX request; it does not wait for the AJAX response to arrive. Your code is checking the res variable before it is being set from the AJAX response.
This is why it works on the second click - not because the res variable is being set by the second click's AJAX response, but because it is still set from the first click's AJAX response.
The solution is to re-arrange your code a bit. Move the code to display the invalid login message to where the AJAX response is received. In other words, replace the res=xmlhttp.responseText; line with some code to check if xmlhttp.responseText is not y and display the invalid login message.
I guess you call def()
Your Request ist asynchron(because you set the 3rd argument of open() to true ), but in def() you immediately after sending the request work with the the result:
ajaxFunction();
//alert('res:'+res);
if(res=='y')
At this time the request usually is not finished, the result not available yet
Put all code that has to work with the server-response into handleServerResponse()

How do I force or add the content length for ajax type POST requests in Firefox?

I'm trying to POST a http request using ajax, but getting a response from the apache server using modsec_audit that: "POST request must have a Content-Length header." I do not want to disable this in modsec_audit.
This occurs only in firefox, and not IE. Further, I switched to using a POST rather than a GET to keep IE from caching my results.
This is a simplified version of the code I'm using for the request, I'm not using any javascript framework.
function getMyStuff(){
var SearchString = '';
/* build search string */
...
/* now do request */
var xhr = createXMLHttpRequest();
var RequestString = 'someserverscript.cfm' + SearchString;
xhr.open("POST", RequestString, true);
xhr.onreadystatechange = function(){
processResponse(xhr);
}
xhr.send(null);
}
function processResponse(xhr){
var serverResponse = xhr.responseText;
var container = document.getElementById('myResultsContainer');
if (xhr.readyState == 4){
container.innerHTML = serverResponse;
}
}
function createXMLHttpRequest(){
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e) {}
try { return new ActiveXObject("Microsoft.XMLHTTP"); } catch (e) {}
try { return new XMLHttpRequest(); } catch(e) {}
return null;
}
How do I force or add the content length for ajax type POST requests in Firefox?
xhr.setRequestHeader("Content-Length", "0");
would be my best guess.
BTW, if you want to stop caching in IE, just add a random number onto the end, as in:
var RequestString = 'someserverscript.cfm' + SearchString + '&random=' + Math.random();
Try to actually send something instead of null (xhr.send(null);).

Categories

Resources