php - Request ready state always returns 0? -
i new javascript , trying play ajax dynamically load html <div> element. have php page spits out json html needed insert <div>. have been testing , cannot call work. started alerts on readystate, , 0 , nothing else. understanding, function senddata() should called every time readystate changes, appears once, or readystate never changes, gets called once...?
this php
<?php $array['html'] = '<p>hello, menu here</p>'; header('content-type: application/json'); echo json_encode($array); ?> this html
<!doctype html> <html> <head> <title>veolia water - solutions , technologies dashboard</title> <meta http-equiv="content-type" content="text/html;charset=utf-8" /> <meta name="description" content="veolia water - dashboard"/> <meta http-equiv="imagetoolbar" content="no" /> <meta author="nathan sizemore"/> <link rel="stylesheet" href="./css/stylo.css" media="screen"/> </head> <body> <div id="menu"> </div> <div id="content"> </div> </body> <script src="./js/dashboard.js"></script> </html> this javascript
var request; window.onload = function() { load_menu(); } //load menu function function load_menu() { request = gethttpobject(); alert(request.readystate); request.onreadystatechange = senddata(); request.open("get", "./php/menu.php", true); request.send(null); } function gethttpobject() { var xhr = false; if (window.xmlhttprequest) { xhr = new xmlhttprequest(); } else if (window.activexobject) { try { xhr = new activexobject("msxml2.xmlhttp"); } catch(e) { try { xhr = new activexobject("microsoft.xmlhttp"); } catch(e) { xhr = false; } } } return xhr; } function senddata() { alert(request.readystate); // if request object received response if (request.readystate == 4) { var json = json.parse(request.responsetext); document.getelementbyid('menu').innerhtml = json.html; alert(json.html); } } thanks in advance help!
nathan
use this:
request.onreadystatechange = senddata; note () removed senddata()
what had before executing senddata , returning result onreadystatechange. since nothing returned, value undefined. wasn't setting onreadystatechange , therefore not executing when state changes. onreadystatechange property expects reference function...which senddata is.
in code, since senddata executed once (accidentally), state reported 0 (the xhr's initial state).
Comments
Post a Comment