AJAX doesn't send POST query - ajax

$(document).ready(function() {
function ajaxselectrss(rssurlvar) {
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('news');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
//var rssurlvar = $(this).attr("title");
var queryString = "rurl=" + rssurlvar;
var urltofile = "rssget.php";
ajaxRequest.open("POST", urltofile, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(queryString);
}
$(".rshownews").click(function() {
window.setInterval(function() {ajaxselectrss($(this).attr("title"))}, 1000);
});
});
The POST query is "undefined" (Firebug).

You should use $.ajax - it will standardise the whole XmlHTTPRequest thing across browsers.
$.ajax({
type: "POST",
url: "rssget.php",
data: queryString,
success: function(data) {
$('#news').html(data);
}
});
(And, BTW, if you setInterval in your click handler, you will start a new periodic call to your ajaxselectrss function every time the button is clicked.)
Also, your context has changed due to the wrapper function. Try changing your click handler like so:
$(".rshownews").click(function() {
var _this = this;
window.setInterval(function() {ajaxselectrss($(_this).attr("title"))}, 1000);
});

Since you seem to use jquery anyway ($(document).ready) you could use it's wrapper for simplifying ajax-requests.
http://api.jquery.com/jQuery.post

Related

Can i use and is secure to use AJAX in my Server Node?

i would like to use native ajax to make some calls inside my node.js server.
Is this secure ?? Can i do it without problems ???
Here's and example:
.... NODE
app.post('/postReceptor', function(req, res, next) {
var data1 = req.body['input1'];
var data2 = req.body['input2'];
var xhr;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
xhr = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
try {
xhr = new ActiveXObject('Msxml2.XMLHTTP');
}
catch (e) {
try {
xhr = new ActiveXObject('Microsoft.XMLHTTP');
}
catch (e) {}
}
}
xhr.open('GET', encodeURI('HTTP://WWW.WEBSITE.COM'), true);
xhr.send(null);
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) { // done
if(xhr.status === 200) { // complete
res.render('renderPage', {
sendingData: xhr.responseText
});
}
}
};
});
This is to verify an external page some customer data sent by the client !
Thanks !
Doing AJAX calls is a concept that is originated from the client side and you are in the server so you don't have the XMLHttpRequest function available on Node.JS.
So to make a HTTP request from Node.JS, you could use http.request or use another library like request helping you to code without complexities, here is an example using the request library:
var request = require('request');
var URL = 'http://www.google.com';
request(URL, function(error, response, body) {
if (!error && response.statusCode === 200) {
console.log(body);
}
});
Thanks for the answers. I got the answer to the question using the library https://www.npmjs.com/package/xmlhttprequest
Risto Novik, this is a simple example and of course i have to validate the fields!

How to show please wait while ajax request process in complete

this code is working fine, all that i want is to make ajax say please wait while still requesting for information: here is this code.
function products(){
if (document.getElementById('date').value.length == 0) {
alert("Please Pick Date");
document.getElementById('date').focus();
return false;
}
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('sum');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var usr = document.getElementById('usr').value;
var date = document.getElementById('date').value;
var queryString = "?usr=" + usr + "&date=" + date;
ajaxRequest.open("GET", "ajax_prom.php" + queryString, true);
ajaxRequest.send(null);
}
In your page, add a div with the id - divAjaxRequestInProgress. Add the text you want to show while the ajax request is in progress to this div. You could have an animated gif as well. Now, show this when you start your ajax processing and hide it once the request is complete.
function products(){
if (document.getElementById('date').value.length == 0) {
alert("Please Pick Date");
document.getElementById('date').focus();
return false;
}
$("#divAjaxRequestInProgress").show();
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('sum');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
$("#divAjaxRequestInProgress").hide();
}
var usr = document.getElementById('usr').value;
var date = document.getElementById('date').value;
var queryString = "?usr=" + usr + "&date=" + date;
ajaxRequest.open("GET", "ajax_prom.php" + queryString, true);
ajaxRequest.send(null);
}
I have just added 2 lines to your code - one to show and one to hide the div.

XDomainRequest Errors, but developer tools shows response body

I am using XDomainRequest to send a cross domain request. The onerror handler is firing; however, nothing is logged and when tracing network in developer tools I can see the response in the response body.
Anyone have any ideas? Below is the code I am using. Thanks in advance for any help.
var createCORSRequest = function(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Most browsers.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// IE8 & IE9
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
};
var url = 'https://myurl';
var method = 'GET';
var xhr = createCORSRequest(method, url);
xhr.onload = function() {
// Success code goes here.
//alert("load");
alert(xhr.responseText);
};
xhr.onprogress = function(){
alert("Progress");
}
xhr.onerror = function() {
alert("error");
};
xhr.send();
XDomainRequest object does not provide anyway to determine what is the status code of error, and returns empty string in xdr.responseText.

AJAX Ready State stuck on 1

Hi I can see this has been discussed but after perusing the issues/answers I still don't seem to be able to get even this simple AJAX call to bump out of ready state 1.
Here's the Javascript I have:
<script language="javascript" type="text/javascript">
var request;
function createRequest()
{
try
{
request = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
request = false;
}
}
}
if (!request)
alert("Error initializing XMLHttpRequest!");
}
function loadClassesBySchool()
{
//get require web form pieces for this call
createRequest(); // function to get xmlhttp object
var schoolId = getDDLSelectionValue("ddlSchools");
var grade = getDDLSelectionValue("ddlGrades");
var url = "courses.php?grades=" + escape(grade) + "&schoolId=" + escape(schoolId);
//open server connection
request.open("GET", url, true);
//Setup callback function for server response
//+++read on overflow that some fixed the issue with an onload event this simply had
//+++the handle spitback 2 readystate = 1 alerts
request.onload = updateCourses();
request.onreadystatechanged = updateCourses();
//send the result
request.send();
}
function updateCourses()
{
alert('ready state changed' + request.readyState);
}
function getDDLSelectionValue(ddlID)
{
return document.getElementById(ddlID).options[document.getElementById(ddlID).selectedIndex].value;
}
</script>
The PHP is HERE just a simple print which if i navigate to in the browser (IE/Chrome) loads fine:
<?php
print "test";
?>
I'm quite new at this but seems like I can't get the most bare bones AJAX calls to work, any help as to how work past this would be greatly appreciated.
All I get out of my callback function 'updateCourses' is a 1...
Well after more digging I actually gave up and switched over to jQuery which should for all intents and purposes be doing the EXACT same thing except for the fact that jQuery works... I was just less comfortable with it but so be it.
Here's the jQuery to accomplish the same:
function loadCoursesBySchool(){
var grades = getDDLSelectionValue("ddlGrades");
var schoolId = getDDLSelectionValue("ddlSchools");
jQuery.ajax({
url: "courses.php?grades=" + grades + "&schoolId=" + schoolId,
success: function (data) {
courseDisplay(data);
}
});
}
function courseDisplay(response)
{
//check if anything was setn back!?
if(!response)
{
$("#ddlCourses").html("");
//do nothing?
}
else
{
//empty DLL
$("#ddlCourses").html("");
//add entries
$(response).appendTo("#ddlCourses");
}
}

Mootool ajax readystate response is always 1?

I've been trying to make this mootools (ver: 1.2.4) Class to process my ajax requests. But my scripts only returns readystate 1. never gets to 2,3 ,or 4, the method handleHttpResponse only seems to run once. I'ves put alerts to see and I only get 1. any ideas?
var replyXML = new Class ({
/* GDW AJAX REQUEST SCRIPT */
/* By: Jonathan Robidas 2011-05-13 */
initialize : function(url){
this.http = this.getHTTPObject(); // We create the HTTP Object
this.url = url; // Requested server-side script
this.response = ''; // String returned by AJAX, Set after positive response
},
returnResponse : function() {
return this.response;
},
handleHttpResponse : function() {
alert(this.http.readyState);
if (this.http.readyState == 4) {
if(this.http.status==200) {
alert("YA YA 2");
this.response = this.http.responseText;
return true;
}
}
},
requestXML : function() {
this.http.open("GET", this.url, true);
//this.http.onreadystateshange = this.handleHttpResponse();
this.http.onload = this.handleHttpResponse();
},
getHTTPObject : function() {
var xmlhttp;
if(window.XMLHttpRequest){
xmlhttp = new XMLHttpRequest();
}
else if (window.ActiveXObject){
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
if (!xmlhttp){
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
}
}
return xmlhttp;
}
});
This is how i launch it for now. my content is null but my url is a working XML file. so it shouldnt be blank... ?
<script language="Javascript" type="text/Javascript">
window.addEvent('domready', function() {
loadXML = new replyXML('gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59');
loadXML.requestXML();
content = loadXML.returnResponse();
alert(content);
/*
x=content.documentElement.childNodes;
for (i=0;i<x.length;i++) {
document.write(x[i].nodeName);
document.write(": ");
document.write(x[i].childNodes[0].nodeValue);
document.write("<br />");
}
*/
});
</script>
Tested on Google chrome, Firefox 4, Internet explorer 7 & 8, all same result.
Here is an example of XML the script is suppose to output: http://jerenovici.net/gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59 so I know my php generating the xml is fine.
Thanks!!
Why are you reinventing the wheel? If you're using mootools, making an ajax request is extremely easy (docs, referring to newest version, but in this case Request hasn't changed):
new Request({
url : './gdwcommreply_genxml.php?getfield=idvideo&fieldid=64&parentid=59',
onSuccess : function(responseText, responseXML){
/* here, do stuff with your response */
},
onFailure : function(xhr){
/* the XMLHttpRequest instance. */
}
}).send();
Then, are you sure the url is correct?

Resources