javascript - readyState is not changing to 4 -
this question has answer here:
i making chat application.in chat application, there "send" button, on clicking call javascript function.
function sendmessage() { var message = document.getelementbyid('messagebox'); var currentuser = document.getelementbyid('username').value; if(trim(message.value) != '' && trim(currentuser) != '') { params = "mode=sendandretrievenew"+ "&name="+encodeuricomponent(currentuser)+ "&message="+encodeuricomponent(message.value); message.value=""; xmlhttpgetmessages.open("post",chaturl,true); xmlhttpgetmessages.setrequestheader("content-type","application/x-www-form-urlencoded"); xmlhttpgetmessages.onreadystatechange = sendmessages(); xmlhttpgetmessages.send(params); } } here variable xmlhttpgetmessages object of xmlhttprequest. chaturl variable contains name of php file. following snippet runs in php file.
if($mode == 'sendandretrievenew') { $name = $_post['name']; $message = $_post['message']; //$id = $_post['id']; if($name != '' && $message != '') { $chat->postmessages($name,$message); } } the postmessages($name,$message); follows:
public function postmessages($name, $message) { $name = $this->mysqli->real_escape_string($name); $message = $this->mysqli->real_escape_string($message); $query = 'insert chat(posted_on, user_name, message) values ( now(), " ' . $name . ' " , " '. $message .' " )'; $result = $this->mysqli->query($query); } the sendmessages() function as:
function sendmessages() { if(xmlhttpgetmessages.readystate == 4) { if(xmlhttpgetmessages.status = 200 || xmlhttpgetmessages.status == 304) alert("send message.check database"); else alert("in else of inner if"); } else alert("in else of outer if "+xmlhttpgetmessages.readystate); } the readystate value changes 0 1, evident last alert();. how make it's value change 4.
after reading first answer changed xmlhttpgetmessages.onreadystatechange = sendmessages(); xmlhttpgetmessages.onreadystatechange = sendmessages , worked. last alert() sendmessages() executed , shows value of readystate changing 2,3 , inner if executed. how function called 3 times? know there answer in comment, didn't understand. pls help. newbie in ajax.
this incorrect:
xmlhttpgetmessages.onreadystatechange = sendmessages(); ^^ the () means javascript executing sendmessages function right , there. function returns nothing, you're setting onreadystatechange callback null.
it should just
xmlhttpgetmessages.onreadystatechange = sendmessages; ^---note which assigns function itself, not results.
Comments
Post a Comment