javascript - handling server response AJAX -
javascript - handling server response AJAX -
in process of working on simple project (or @ to the lowest degree thought simple) user clicks button, , random saying generated php appears in above textbox. not have access php file can't see code , sense bit lost. problem i'm having believe, error in way im handling response server (the handleserverresponse function). advice appreciated.
in effort debug, i've seen message: (i've changed url)
xmlhttprequest cannot load http:somephp.php. no 'access-control-allow-origin' header nowadays on requested resource. origin 'null' hence not allowed access.
the code far:
var xmlhttp = createxmlhttprequestobject(); function createxmlhttprequestobject(){ var xmlhttp; if(window.activexobject){ try{ xmlhttp = new activexobject("microsoft.xmlhttp"); }catch(e){ xmlhttp = false; } }else{ try{ xmlhttp = new xmlhttprequest(); }catch(e){ xmlhttp = false; } } if(!xmlhttp) alert("error 1"); else homecoming xmlhttp; } $("#btnreset").click(function () { $("#tbsaying").val(""); }) $("#btngetsaying").click(function () { process(); }) function process(){ if(xmlhttp.readystate==0 || xmlhttp.readystate==4){ xmlhttp.open("get", "http://somephp.php", true); xmlhttp.onreadystatechange = handleserverresponse; xmlhttp.send(null); }else{ settimeout('process()', 1000); } } function handleserverresponse(){ if(xmlhttp.readystate==4){ if(xmlhttp.status==200){ xmlresponse = xmlhttp.responsexml; xmldocumentelement = xmlresponse.documentelement; message = xmldocumentelement.firstchild.data $("#tbsaying").val(message); }else{ alert('error 2'); } } } read through jquery documentation , started fresh, uploaded same server in php resides , works. here final code: advised!
$("#btnreset").click(function () { $("#tbsaying").val(""); }) $("#btngetsaying").click(function () { process(); }) function process(){ // ajax code submit form. $.get("http://somephp.php",function(data){ $("#tbsaying").val(data); }); }
your javascript seems horrible, alas, wrong "access-control-allow-origin" server-sided (php?) bug, sorry.
tell server guys add together like
header("access-control-allow-origin: *"); to see if javascript right ^^
on sidenote,
alert("error 1"); should utilize console.log or throw new error() instead.. why have xmlhttp global, can utilize process(e){ var xhr=e.target;...} instead don't settimeout('process()', 1000); , settimeout(process, 1000); javascript jquery ajax
Comments
Post a Comment