more than one ajax call in the same page? - javascript

I have the following code
function ajaxCall(action,parameters){
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//xmlhttp.overrideMimeType('text/html');
xmlhttp.onreadystatechange=function(){
if (xmlhttp.readyState==4 && xmlhttp.status==200){
var rtrv_data=xmlhttp.responseText;
alert(rtrv_data);
}
}
parameters='action=' + action + '&' + parameters;
xmlhttp.open("POST","ajax_calls.php" ,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", parameters.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(parameters);
}
Assuming that i have this function called by some timer , and a click on the page called the function again , i only get one output ! one response ! hwo can i get the 2 ?
thanky you .

The variable "xmlhttp" is a global (you used no "var") so this will never allow two simultaneous ajax calls because when the second call starts you will overwrite the same variable and that's the variable that's used inside the callback to retrieve the data.
You need to create a new variable each time to store the xml request object and also you need to use a closure for your completion callback... something like
var xmltthp = ... // this is a local variable
xmlhttp.onReadyStateChange = function() {
// here you can use xmlhttp even if it's a local
// it will be a different variable for each ajax request
}

Thanks! That worked for me! Did this:
function refreshpage(){
var mycode=document.getElementById("bcode").value;
if (window.XMLHttpRequest){
xmlhttpf=new XMLHttpRequest();
}else{
xmlhttpf=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpf.onreadystatechange=function(){
if (xmlhttpf.readyState==4 && xmlhttpf.status==200){
document.getElementById("zones").innerHTML=xmlhttpf.responseText;
}
}
xmlhttpf.open("GET","ajaxaki.php?code="+mycode,true);
xmlhttpf.send();
}
function refresh_vehs(){
var asma=document.getElementById("newasma").value;
if (window.XMLHttpRequest){
xmlhttpf_vehs=new XMLHttpRequest();
}else{
xmlhttpf_vehs=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttpf_vehs.onreadystatechange=function(){
if (xmlhttpf_vehs.readyState==4 && xmlhttpf_vehs.status==200){
document.getElementById("vehicles").innerHTML=xmlhttpf_vehs.responseText;
}
}
xmlhttpf_vehs.open("GET","AJAX_vehicle_cards.php?asma="+asma,true);
xmlhttpf_vehs.send();
}

Related

AJAX function( ) part alone not working

After function() it is not working, i don't know why. If I put an alert before that statement it's working but after that statement it isn't working.
<script>
function new_order() {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
alert("asdasd");
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("order_id").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("POST", "item_sort.php?sort=" + str, true);
xmlhttp.send();
}
</script>
3 things you can check
If an element corresponding to id order_id exists on the page
if the str is not null or not defined
If you are using older IE versions IE5 or 6 you need to add the
following in your code.
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
Also you need to use the following way if you want to do POST ajax call.
xmlhttp.open("POST", "item_sort.php", true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("sort=" + str);

2 functions onchange event at same time separately

So what i'm looking for is a way to trigger 2 function events onchange with my first option, i've looked up a few examples on other sites an neither of them works. But what i want is when this.value is selected, for the function to open 2 separate options via the selection.
So if category is Dogs it does showSub(Dogs) and showSize(Dogs) at the same time and sends to 2 different php page calls, IF thats possible.
//index.php
<select name="category" onChange="showSub(this.value);showSize(this.value)" style="width:200px;">
<option value="">Select Category</option>
Send to php to get actual options.
</select>
//foo.js
function showSub(str)
{
if (str=="") {
document.getElementById("txtSub").innerHTML="";
return;
}
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("txtSub").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getSub.php?q="+str,true);
xmlhttp.send();
}
function showSize(str)
{
if (str=="") {
document.getElementById("txtSize").innerHTML="";
return;
}
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("txtSize").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getSize.php?q="+str,true);
xmlhttp.send();
}
//rest of index.php
<div id="txtSub"></div>
<div id="txtSize"></div>
Use var to declare all variables. Your showSub() and showSize() functions both use a variable xmlhttp that is not declared with var, which makes it global - so when you call showSize() it overwrites the xmlhttp object from showSub() (which is why you get the effect mentioned in a comment where "with the current code, the showsize only shows").
So add this line to the start of each function:
var xmlhttp;
And better yet, move the if/else out into a separate function that returns an xmlhttp object rather than repeating that code in both functions:
function getXMLHttp() {
return window.XMLHttpRequest ? new XMLHttpRequest() // newer browsers
: new ActiveXObject("Microsoft.XMLHTTP"); // old IE
}
// and then within your other functions:
var xmlhttp = getXMLHttp();

multiple ajax calls using only javascript

isn't it possible to execute multiple ajax calls using javascript only and without using Jquery. I tried the below javascript code with two ajax calls but the code is not working when I place the second ajax call
<script type="text/javascript">
var class1;
var class2;
var sec1;
var sec2;
function func()
{
class1 = document.getElementById('selcla');
class2 = class1.options[class1.selectedIndex].value;
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("secdiv").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getsec.php?q="+class2,true);
xmlhttp.send();
}
function funcsec()
{
sec1 = document.getElementById('selsec');
sec2 = sec1.options[sec1.selectedIndex].value;
alert("selecting class and section details " + class2 + " " + sec2 );
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)
{
alert("successfully received " );
document.getElementById("studiv").innerHTML=xmlhttp.responseText;
}
else
alert("unsuccessful ajax second call ");
}
xmlhttp.open("GET","getstu.php?x="+class2"&y="+sec2,true);
xmlhttp.send();
}
It is, but you need a different "xmlhttp" handler for each request you make.
Setup a new xmlhttp object and make a second request with the new object.
My suggestion is to break out the part with you initializing the xmlhttp object, into a standalone function, and use it to create a few instances of those objects.
However I must advise against such an approach. It is better to use a library for ajax requests.

Run php script every x mins using ajax request

got this file 'functions.php':
<?php
function test ($url){
$starttime = microtime(true);
$valid = #fsockopen($url, 80, $errno, $errstr, 30);
$stoptime = microtime(true);
echo (round(($stoptime-$starttime)*1000)).' ms.';
if (!$valid) {
echo "Status - Failure";
} else {
echo "Status - Success";
}
}
test('google.com');
?>
I want to run it every 10seconds or so, i was told to use ajax request but i dont completely understand how it works. I tried creating a new file 'index.php', and then had this written in it:
<script>
var milliSeconds = 10000;
setInterval( function() {
//Ajax request, i dont know how to write it
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
</script>
I put both files into ftp but nothing happens, can someone help me write a propper ajax request?
Edit: eddited typo, still doesnt work tho
var milliSeconds = 1000;
setInterval( function() {
var xmlhttp;
if (window.XMLHttpRequest) // code for IE7+, Firefox, Chrome, Opera, Safari
{
xmlhttp=new XMLHttpRequest();
}
else
{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); // code for IE6, IE5
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
console.log ( xmlhttp.responseText );
}
}
xmlhttp.open("POST","functions.php",true);
xmlhttp.send();
}, milliSeconds);
You have to load xmlhttp request object according to the browser ( xmlhttp=new XMLHttpRequest(); ), then set an event handler when the xmlhttp state changes ( xmlhttp.onreadystatechange=function() ). When it changes check if the status is 200 (success) then do whatever you want with the response. ( I printed it to console )
So, it sounds like your only problem is that you don't know how to write an XHR request. Take a look at Using XMLHttpRequest. Comment on this answer with your questions.
xmlhttp.open("POST","funkction.php",true);
should be:
xmlhttp.open("POST","functions.php",true);

How to parse json from a url

I have a url contain all the json format.
http://api.musixmatch.com/ws/1.1/track.lyrics.get?apikey=d34fb59a16877bd1c540aa472491825b&track_id=12414632
function load() {
dashcode.setupParts();
var link = 'http://api.musixmatch.com/ws/1.1/track.search?apikey=d34fb59a16877bd1c540aa472491825b&q_track=back%20to%20december&page_size=10';
req.open = ("GET", link, false);
req.onreadystatechange = readXML();
req.send(null);
}
function readXML(){
alert(req.responseText);
}
this code keep saying null all the time.
Are there any way that i can retrieved those json text
The problem is with req.onreadystatechange = readXML();. You're assigning the result of the function instead of the function itself (as a callback).
You want req.onreadystatechange = readXML;. Though I must say I'm not sure how this code is supposed to work. Not in terms of how the XHR is made, nor with regards to the external domain.
Correct usage is as follows.You can check this link http://jsfiddle.net/UH4KY/1/ The link will alert undefined since cross domain scripting is not allowed .You can set the Access-Control-Allow-Origin and test the code.
function readXML(req) {
alert(req);
}
function load() {
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 link = 'http://api.musixmatch.com/ws/1.1/track.search?apikey=d34fb59a16877bd1c540aa472491825b&q_track=back%20to%20december&page_size=10';
//req.open = ("GET", link, false);
xmlhttp.onreadystatechange = function(){ alert(xmlhttp.responseText); }
xmlhttp.open("GET", link, false);
xmlhttp.send(null);
}

Categories