Tomer Touitou Tomer Touitou - 1 month ago 6
Ajax Question

how to getelementbyid using ajax.response

I use php to sent back div name to ajax call using post
I want to use the js variable that I get using ajax and than use this to dom a div

idisis=ajax.responseText;
document.getElementById(idisis).innerHTML= some text;
// ('idisis') || (''+idisis+'')|| ("'+idisis+'")


But it dont work it is possible ?

Answer

Here is a raw XMLHttpRequest post function I made, and a few other goodies. It's backward compatible.

function phpEncode(obj){
  var r = [];
  if(obj instanceof Array){
    for(var i=0,l=obj.length; i<l; i++){
      r.push(phpEncode(obj[i]));
    }
    return '%5B'+r.join(',')+'%5D';
  }
  else if(typeof obj === 'object' && obj){
    for(var i in obj){
      if(obj.hasOwnProperty(i)){
        var v = obj[i], s;
        if(typeof v === 'object' && v){
          s = encodeURIComponent('"'+i.replace('"', '\\"')+'":')+phpEncode(v);
        }
        else{
          v = typeof v === 'string' ? '"'+v.replace('"', '\"')+'"' : v;
          s = encodeURIComponent('"'+i.replace('"', '\\"')+'":'+v);
        }
        r.push(s);
      }
    }
    return '%7B'+r.join(',')+'%7D';
  }
  else{
    r = typeof obj === 'string' ? '"'+obj.replace('"', '\\"')+'"' : obj;
    return ''+r;
  }
}
function phpAccept(respText){
  return eval('('+decodeURIComponent(respText)+')');
}
function clone(obj){
  return phpAccept(phpEncode(obj));
}
function post(send, where, success, context){
  var x = new XMLHttpRequest || new ActiveXObject('Microsoft.XMLHTTP');
  var c = context || this;
  x.open('POST', where); x.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
  x.onreadystatechange = function(){
    if(x.readyState === 4 && x.status === 200){
      if(success)success.call(c, phpAccept(x.responseText));
    }
  }
  if(send && typeof send === 'object' && !(send instanceof Array)){
    var r = [];
    for(var p in send){
      r.push(encodeURIComponent(p)+'='+phpEncode(send[p]));
    }
    if(r.length)x.send(r.join('&'));
  }
  return x;
}
post({testProperty:'testValue'}, 'yourPage.php', function(response){
  // evaluate response and run all your other code here
});