Sending GET and POST AJAX requests at the same time - javascript

i just would like to know if it is possible sending GET and POST AJAX requests at the same time and if it is how to do it using the XMLHttpRequest object.
Thanks all for helping :D

Send the request as a POST. An HTTP request can only have one method, but nothing is stopping you from using parameters on a POST URL.
If you POST to http://example.com/form?foo=bar, you'll still be able to access foo as a GET parameter.
Here's an example using jQuery:
$.post("http://example.com/form?" + $.param({foo: "bar"}), {text: tinyMCEBody})
Without jQuery, that would look more like this:
…
request.open("POST","form?foo=bar",true);
request.send("text=" + encodeURIComponent(tinyMCEBody));
…

Do you mean you'd like to send some query string values along with your POST? Surely it's just a case of appending them the post URL?

Could you just make two instances of the XMLHttpRequest? So you could have:
Get
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp1=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp1.onreadystatechange=function()
{
if (xmlhttp1.readyState==4 && xmlhttp1.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp1.responseText;
}
}
xmlhttp1.open("GET","ajax_info.txt",true);
xmlhttp1.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
POST
<html>
<head>
<script type="text/javascript">
function loadXMLDoc2()
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp2=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp2.onreadystatechange=function()
{
if (xmlhttp2.readyState==4 && xmlhttp2.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp2.responseText;
}
}
//Set POST params
var params = "lorem=ipsum&name=binny";
xmlhttp2.open("POST","ajax_info.txt",true);
xmlhttp2.send(params);
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc2()">Change Content</button>
</body>
</html>
All I changed was the name of the object xmlhttp1=new ActiveXObject("Microsoft.XMLHTTP") and xmlhttp2=new ActiveXObject("Microsoft.XMLHTTP")
Taken from W3Schools
http://www.w3schools.com/ajax/default.asp

Related

Converting Text input to an actual parameter for javascript function

I need to convert the messbox value so it can be passed into the loadPHPDoc function, but i cannot seem to successfully transfer the data. It successfully loads the php document when i place quotation marks around the actual parameter, but i do not, it simply does not use the function, and does not work. Here's my code:
<!DOCTYPE html>
<html>
<body>
<p id="myDiv">no</p>
<script>
function loadPHPDoc(str){
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var url = "testSubmit.php";
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("POST","testSubmit.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
var sender = "q=" + str;
xmlhttp.send(sender);
document.getElementById("myDiv").innerHTML = str;
}
</script>
<p>Message <input type= "text" id="messbox"></p>
<button type= "button" onclick="loadPHPDoc(document.getElementById(messbox).value)">input</button>
</body>
</html>
document.getElementById() receives a string as a parameter, so:
<button type= "button" onclick="loadPHPDoc(document.getElementById('messbox').value)">input</button>

ajax php call not returning anything

I want php to return a value to ajax. I'm following W3 schools example but no joy.
Here is the javascript/ajax code:
function createReport() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
I have the following call inside an event handler that I know is triggering (other stuff it does is working fine)
createReport();
and later in the body section of the html I have:
<div id="report">Report will be placed here...</div>
If I run test.php by itself, it correctly shows "return this to ajax" so I know that's working. Here is the php code:
<?php
echo 'return this to ajax';
?>
My understanding is that "Report will be placed here..." will be replaced with "return this to ajax". But nothing happens. I don't see any errors listed in the firefox or IE consoles either. Any ideas?
I personally do not think the w3cschools a good place to learn ( see http://www.w3fools.com/ ).
It may be that the problem occurs because of the order that you set the ajax, you did:
XMLHttpRequest/onreadystatechange/open/send
is preferable (if you do not follow this order may occur several flaws in older browsers):
XMLHttpRequest/open/onreadystatechange/send
Note: do not worry, the "open(...)" does not start listeners.
Listeners only work after the "send(...)"
Another reason may be that you did not create "error handling" of XMLHttpRequest.status, it serves to verify faults in the server response.
Try this:
<script>
function XHR(){
if(window.XMLHttpRequest){//outers browsers
return new XMLHttpRequest();
} else if(window.ActiveXObject){//IE
try{
return new ActiveXObject("Msxml2.XMLHTTP");
} catch(ee) {//IE
try{
return new ActiveXObject("Microsoft.XMLHTTP");
} catch(ee) {}
}
}
return false;
}
function createReport(){
var xhr = XHR();// call ajax object
if(xhr){
xhr.open("GET", "test.php", true);//setting request (should always come first)
xhr.onreadystatechange = function(){//setting callback
if(xhr.readyState==4){
if(xhr.status==200){
document.getElementById("report").innerHTML=xhr.responseText;
} else {//if the state is different from 200, is why there was a server error (eg. 404)
alert("Server return this error: " + String(xhr.status));
}
}
};
xhr.send(null);//send request, should be the last to be executed.
} else {
alert("Your browser no has support to Ajax");
}
}
</script>
<div id="report">Report will be placed here...</div>
<script>
createReport();//prefer to call the function after its div#report
</script>
To prevent cache, replace:
xhr.open("GET", "test.php", true);
by
xhr.open("GET", "test.php?nocache="+(new Date().getTime()), true);
At first glance I don't see anything wrong on your js code, so I bet it will probably be a problem locating test.php in your folder structure.
With firebug check the call your javascript AJAX it's doing, and check if the file test.php is being correctly assesed.
I did not find anything wrong with W3Schools' Ajax example, after testing the code that follows (which was pulled from their Website).
Possible factors:
Missing <script></script> tags
Make sure you have JS enabled.
Make sure your browser supports it.
You may have forgotten to change the button's call to the proper function.
Working and tested code using FF 26.0 and IE version 7
Pulled from W3 Schools Website (example) and slightly modified to prove this works.
Result when clicking on the Change Content button:
return this to ajax - as per your PHP code.
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="report"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
PHP used: (test.php)
<?php
echo 'return this to ajax';
?>
Other possible factors:
If on a local machine, your server doesn't support PHP or is not parsing PHP properly, or is either not installed or configured properly.
If on a hosted service, make sure PHP is available for you to use.
Files are not in the same folder as executed from.
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 Create_Ajax_Query(LinkToFile,Parametrs)
{
window.document.body.style.cursor='progress';
request = new XMLHttpRequest();
var url = LinkToFile;
var params = Parametrs;
request.open("POST", url, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
request.setRequestHeader("Content-length", params.length);
request.setRequestHeader("Connection", "close");
request.onreadystatechange = newinfo;
request.send(params);
}
function newinfo()
{
if(request.readyState==4 && request.status == 200){
window.document.body.style.cursor='default';
alert(request.responseText);
}
}
Hope its useful!
The code looks correct. it runs just fine on a local environment.
I would advise to look at the "Network" tab in the developer tools to detect any errors may occurs on the server side. You can also use console.log() to follow the javascript actual flow:
function createReport() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
console.log(xmlhttp); //to show the entire object after statechage.
console.log(xmlhttp.readyState); //to show specific parameter.
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("report").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","test.php",true);
xmlhttp.send();
}

Javascript code using xhr is not working?

Below is the response from server (as per google chrome rest-client):
Below is the code snippet I'm using to post some data to our server. I want to get back data as xml ouput.
Keeping in mind the concept of same origin policy i uploaded this piece of code onto our sever as a html page, but not getting any response.
Is there anything wrong with my code or is my approach wrong?
<html>
<head>
<script type="text/javascript">
function getToken()
{
var xmlhttp;
var txt,x,i;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
alert("stage 1");
xmlhttp.onreadystatechange=function()
{
alert("stage 2");
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
alert("stage 3");
xmlDoc=xmlhttp.responseXML;
txt="";
x=xmlDoc.getElementsByTagName("token");
alert("stage 4");
for (i=0;i<x.length;i++)
{
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
}
document.getElementById("myDiv").innerHTML=txt;
}
}
alert("stage 5");
xmlhttp.open("POST","http://abc.mysite.com:9090/myapi/xxx",true);
xmlhttp.send("op=login&pass=xxx");
}
</script>
</head>
<body>
<center><h2>UserPreview:</h2></center>
<br />
<div id="myDiv"></div>
<br />
<button type="button" onclick="getToken()">GetToken</button>
<div data-role="footer" data-position="fixed" data-theme="a"><h4>Ver: 1.1(17112)</h4> </div>
</body>
</html>
<response><token>8768768768768768</token></response>
You have to take into account that: for AJAX calls, you can only access the same hostname (and port / scheme) as your page was loaded from. The same domain always and the same PORT:
How exactly is the same-domain policy enforced?
In the past I use this for the IE version, I suppose for possible compatibility issues:
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(e)
{
try
{
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}catch(e){}
I always put the code like this:
var THEURL="http://mysite.abc.com:8080/myapi/xxx"
var data="op=login&pass=xxx";
http.open("POST",THEURL, true);
http.onreadystatechange = function(){
};
xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", data.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(data);
Can't you use jquery? It is much more efficient.
To make an ajax call:
http://api.jquery.com/jQuery.ajax/
For example:
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
The sooner you use Jquery the sooner your work will get faster.
If the element called token in your xml file is an xml element, and not an attribute then you replace the following lines by -
txt=txt + x[i].childNodes[0].nodeValue + "<br />";
by -
txt += (window.ActiveXObject)?x[i].childNodes[0].text : x[i].childNodes[0].textContent;
I didn't ask you wheter your XHR is returning you the XML properly or not.

How to "search" through the response of an XMLHttpRequest

I have a question regarding the followng code
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.html",true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Now I want to search through the xmlhttp.responseText (in other words call the function loadXMLDoc()) for key words, like for example "testfile" and if it exists multiple example "testfile_1" and "testfile_2"....."testfile_n" then "doSomething"
like this
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
return xmlhttp.responseText;
}
}
}
function searchADocument(wordToSearchFor){
xmlhttp.open("GET","index.html",true);
xmlhttp.send();
int numberOfTimesWordOccurs=0;
var thePageToSearchThrough [] = loadXMLDoc();
for (i=0; i<thePageToSearchThrough.length; i++){
if(thePageToSearchThrough[i]==wordToSearchFor)
numberOfTimesWordOccurs++;
}
If (numberOfTimesWordOccurs > 1)
document.write(" testfile_1" testfile_2 testfile_n
)
Else
window.location="http://selnc05.go.se:8080/component_test/build/testfile.html";
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="searchADocument("testfile")">Change Content</button>
</body>
</html>
I don't know where to start since I don't know what type xmlhttp.responseText is, can I store it in an array and scan it using for loop etc?
Thanks in advance. =)
EDIT
What am Im doing wrong here
<html>
<head>
<script type="text/javascript">
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
return xmlhttp.responseText;
}
}
xmlhttp.open("GET","index.html",true);
xmlhttp.send();
}
function searchADocument(){ //wordToSearchFor
var txt=loadXMLDoc();
if(txt.test('hello'))alert('responseText contains "hello"');
else{
document.getElementById("myDiv").innerHTML ="helloaj";
}
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="searchADocument()">Change Content</button>
</body>
</html>
get the following error message on if(txt.test('hello')) Jscript error:'undefined' is null or not an object
EDIT 3
Im guessing im just dumb as hell, but I still can't get this to work, why can't I store the xmlhttp.responseText into a variable?
Like this
<html>
<head>
<script type="text/javascript">
var xmlhttp;
function loadXMLDoc(url,cfunc)
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=cfunc;
xmlhttp.open("GET",url,true);
xmlhttp.send();
}
function myFunction()
{
loadXMLDoc("ajax_info.txt",function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var txt=xlmhttp.responseText;//This aint working, why, how can I store xlmhttp.responseText into a variable, that I can peform a search on?
document.getElementById("myDiv").innerHTML=txt;//This aint working, why?????
}
});
}
</script>
</head>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="myFunction()">Change Content</button>
</body>
</html>
I can add that the above actually works if I replace the following
var txt=xlmhttp.responseText;
document.getElementById("myDiv").innerHTML=txt;
with this
document.getElementById("myDiv").innerHTML=xlmhttp.responseText;
I haven't got the call back function to work as mentiond below, all I get is that xmlhttp is undefined, so I ask on this that works(at least half the way I want it to).
Again sorry for not understanding, but there must be something obvious that I don't get about this, that this simply isn't possible to store this in a variable or something.
var txt=loadXMLDoc();
loadXMLDoc doesn't return anything, so txt is undefined after this. Of course undefined doesn't have the test method, which is a method of String.prototype.
Instead assign a callback handler to your XMLHttpRequest and do whatever you want there.
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4)
if (xmlhttp.status==200) {
// do something with xmlhttp.responseText
} else {
// do something appropriate with status
}
}
Update: Though I think it's usually not preferrable to have these kind of copy-pasta examples, I can show you where you should put this piece of code. Instead of doing this:
function searchADocument() { //wordToSearchFor
var txt = loadXMLDoc();
if (txt.test('hello'))
alert('responseText contains "hello"');
else
document.getElementById("myDiv").innerHTML = "helloaj";
}
where you test the return value of loadXMLDoc (which, as already stated, returns immediately, so before the request is completed), you should put your code inside the callback handler, that you assign by setting onreadystatechange:
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
var txt=xmlhttp.responseText; /* manipulate the DOM here */
if (txt.test('hello'))
alert('responseText contains "hello"');
else
document.getElementById("myDiv").innerHTML = "helloaj";
}
}

How to parse HTML from JavaScript in Firefox?(2)

Im trying to parse a HTML result of **XmlHttpRequest** in Firefox. Im expecting to receive the HTML result from XmlHttpRequests *responseText* but when Im calling an alert(responseText) nothing is displayed.
Ive followed the example from http://stackoverflow.com/questions/888875/how-to-parse-html-from-javascript-in-firefox but that doesnt work either.
Here is thecode to make myself clear:
<html>
<head>
<script type="text/javascript">
var http1;
var result;
function onPageLoad()
{
http1=getXmlHttpObject();
http1.open("GET", "https://login.yahoo.com/config/login_verify2?&.src=ym", true);
http1.send(null);
http1.onReadyStateChange=stateChanged();
}
function stateChanged()
{
if(http1.readyState==4)
{
result = http1.responseText;
alert("result"+ result);
var tempDiv = document.createElement('div');
tempDiv.innerHTML = result.replace(/<script(.|\s)*?\/script>/g, '');
// tempDiv now has a DOM structure:
alert(tempDiv.getElementById('username').size);
}
else
alert("mircea geoana la zoo");
}
function getXmlHttpObject()
{
var objXMLHttp=null;
if (typeof XMLHttpRequest!= 'undefined')
{
objXMLHttp=new XMLHttpRequest();
}
else
{
objXMLHttp=new ActiveXObject(Microsoft.XmlHttp);
}
return objXMLHttp;
}
</script>
</head>
<body onload="onPageLoad()">
<p>aaa<p>
</body>
</html>
http1.onReadyStateChange=stateChanged();
should be
http1.onReadyStateChange=stateChanged;
I see a big mistake there.. the message on the else branch should read 'miRcea', not 'micea'.. Tell me if this solves your issue, Mr claudiu ;))
this is how you should define the xmlhttp Object:
var xmlhttp;
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else if (window.ActiveXObject)
{
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
else
{
alert("Your browser does not support XMLHTTP!");
}
Check out this w3School tutorial to read about how to properly use AJAX calls and the like.
edit - my bad, only saw the line defining the call for IE6/5. Either way this method is much more clean.
You can only send AJAX requests to the same domain from which the JavaScript originates. And I'm guessing you're not sending your requests from "login.yahoo.com"...

Categories

Resources