readyState does not get past 1 - javascript

Trying to put data into an XML through javascripts open() function.
but The website does not get past readyState 1,
Below is the the Javascript code
function addItem()
{
var name = document.getElementById('Iname').value;
var price = document.getElementById('Iprice').value;
var quantity = document.getElementById('Iquantity').value;
var description = document.getElementById('Idescription').value;
xHRObject.open("GET", "listing.php", true);
xHRObject.onreadystatechange = function() {
if (xHRObject.readyState == 4 && xHRObject.status == 200)
{
document.getElementById('Information').innerHTML = xHRObject.responseText;
xHRObject.send(null);
}
}
}
I do not know if it is an error with the PHP, but its quite large so i will only post it in if required.

This was an error with the browser functionality, worked fine in firefox.

Related

execute code after typing indication over

i have problem figuring out a solution . i am developing a chatbot .
this is my html where i print all the discussion , its just one :
<div id="divChat"> </div>
i want to add typing indicator to it .here is how it works on each message:
1)User types his message (exemple : Hello), and click on a button
<button onclick="sendMessage()" id="btn1" > Send </button>
2) i read his message and i sent it to mybackend application to receive the response and print it in the chat element.
function sendMessage(){
var url = "http://localhost:3000/api/v1/bots/renault/converse/user1";
xhr.open("POST", url, true);
xhr.setRequestHeader("Content-Type", "application/json");
xhr.onreadystatechange = function () {
if (xhr.readyState === 4 && xhr.status === 200) {
var reponseBot= JSON.parse(xhr.responseText);
if(reponseBot!='undefined'){
$("#divChat").append(reponseBot+"</br>");
}
}
}
};
var values = {
type: "text"
}
values.text=$("#userMessage").val();
var data= JSON.stringify(values);
xhr.send(data);
}
the chat works fine , now i want to add typing indicator which is this element (u dont need see css of it):
<div class="typing-indicator"></div>
i want When the user send his message i Append the typing indicator to the chat , show it for 2sec then hide it and append then response bot : like this
if (xhr.readyState === 4 && xhr.status === 200) {
var reponseBot= JSON.parse(xhr.responseText);
if(reponseBot!='undefined'){
$("#divChat").append("<div class='typing-indicator' ></div>");
/// I WANT TO HIDE IT AFTER 2SEC THEN APPEND THE USER RESPONSE
$("#divChat").append(reponseBot+"</br>");
}
}
Please any idea how to achieve this and thanks
You can use setTimeout to delay an action.
Also note that if you've already included jQuery in the page you may as well use its AJAX methods to simplify the code. Try this:
let $divChat = $('#divChat');
function sendMessage() {
$.post('http://localhost:3000/api/v1/bots/renault/converse/user1', {
type: 'text',
text: $('#userMessage').val()
}, function(response) {
$('#userMessage').val(''); // empty the typed message
let $indicator = $('<div class="typing-indicator"></div>').appendTo($divChat);
setTimeout(() => {
$indicator.remove();
$divChat.append(response + "</br>");
}, 2000);
});
};
Also note that from the response to your AJAX request it looks like you're returning a plain text response which is not ideal, as it can be affected by whitespace. I'd suggest you amend your server side logic to return a serialised format, such as JSON or XML.

XMLHttpRequest - get value from URL and write it in a div

I have a div called totalvalue.
<div id="totalvalue"></div>
I wrote a function to get value from my PHP script (on the same server).
function totalvalue() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
totalvalue = (ajax5.responseText);
console.log(totalvalue);
document.getElementById("totalvalue").innerHTML = ajax5.responseText;
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
The php script does output a value.
Neither my console nor the div display the output.
This worked for me.
function test5() {
var ajax5 = new XMLHttpRequest();
ajax5.onreadystatechange = function() {
if (ajax5.readyState == 4) {
xxx5 = (ajax5.responseText);
console.log("this is the total value: "+xxx5);
if (xxx5 == 0) {
document.getElementById("totalvalue").innerHTML="Loading...";
} else {
document.getElementById("totalvalue").innerHTML="Total: "+xxx5;
}
}
};
ajax5.open("GET", "totalvalue.php", true);
ajax5.send(null);
}
I presume that where I write the div matter + there could have been an issue with the cache. I cannot tell for sure why the above just started working.
For simpler code, and better cross browser support, i would use jQuery.ajax like so:
$.ajax({
url: 'totalvalue.php',
success: function(data){
$('#totalvalue').html(data);
}
});
Read more about it in the documentation

Address ID of dynamically generated Input to send value via AJAX

First of all, Hello Everyone, I'm new in here.
I have searched all over the site and I can't seem to find an answer to my problem...
I have an input, being generated via AJAX-PHP dynamically, and I want the user to enter some Value there, then send the data via Ajax for processing it into Mysql.
Thing is, javascript is reading the input value of the as Null:
"Uncaught TypeError: Cannot read property 'value' of null"
Here's the code:
function addBandMember() {
var Btn = _("addBandMem");
var errorMsg = _("UpWinMsg");
var url = window.location.href;
var mmbr = _("#newBandMember").value; // <-THIS IS RETURNING NULL
if (mmbr == "") {
errorMsg.innerHTML = "Please enter a USERNAME";
} else {
errormsg.innerHTML = "please wait...";
var ajax = ajaxObj("POST", url);
ajax.onreadystatechange = function() {
if (ajaxReturn(ajax) == true) {
//SETTINGS RECEIVED
if (ajax.responseText != "member_added") {
errorMsg.innerHTML = ajax.responseText;
} else {
toggleUpWin();
receiveUserData();
}
}
};
ajax.send("mmbr=" + mmbr);
}
}
I believe this is happening because the Input field is being generated AFTER the document loads, via Ajax and PHP... Am I wrong? How can I address this newly-generated ID?
Thanks!
Try this one to get the value of input box.
var mmbr =$("#newBandMember").val();
OR
var mmbr =_("#newBandMember").val();
Found the answer... It was just a stupid mistake...
I have a function set for "getElementById" which requires a string, without "#".
so it'd be:
var mmbr = _("newBandMember").value; // <-THIS IS NOT RETURNING NULL
instead of:
var mmbr = _("#newBandMember").value; // <-THIS IS RETURNING NULL
Thanks to everyone who answered!

Not able to call a jquery function in a ajax returned code

I am not much of a javascript programmer, I am learning so please forgive the stupid mistakes.
I am trying to save customer details using ajax (its not the jquery ajax), which returns another form for advanced details. I am using a jquery plugin for validation of input boxes. But the validation doesn't work on the form returned by ajax.
Ajax code:
function createcustomer() {
var firstname = _("firstname").value;
var lastname = _("lastname").value;
var email = _("email").value;
var phone = _("phone").value;
var status = _("status");
if (firstname == "" || lastname == "" || email == "" || phone == "") {
status.innerHTML = "Fill out all of the form data";
} else {
_("signupbtn").style.display = "none";
status.innerHTML = 'please wait ...';
var ajax = ajaxObj("POST", "save-customer.php");
ajax.onreadystatechange = function () {
if (ajaxReturn(ajax) == true) {
if (ajax.responseText != "failure") {
_("signupform").innerHTML = "";
_("advancedform").innerHTML = ajax.responseText;
} else {
window.scrollTo(0, 0);
_("signupform").innerHTML = "Error Occured";
}
}
}
ajax.send("firstname=" + firstname + "&lastname=" + lastname + "&email=" + email + "&phone=" + phone);
}
}
function ajaxObj(meth, url) {
var x = new XMLHttpRequest();
x.open(meth, url, true);
x.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
return x;
}
function ajaxReturn(x) {
if (x.readyState == 4 && x.status == 200) {
return true;
}
}
I have tested the ajax return code thouroughly and the jquery works independently on that form.
This is how I initiate the jquery validation plugin :
$(document).ready(function() {
$('form').validationEngine();
});
I tried putting the exact code in the createcustomer() function to reload the jquery function but it doesnt work. Is there any way I can call that jquery validation function in the ajax function?
Any help will be appreciated.
Regards
Priyanshu
I'm suspecting that your validation is trying to find a form that doesnt exists at the execution time, try putting the validation binding when you have sure that the form exists in your DOM. To achieve this you should put the validation binder:
$('form').validationEngine();
...inside the callback after the ajax loads some HTML data in the document. Like this:
ajax.onreadystatechange = function() {
if(ajaxReturn(ajax) == true) {
if(ajax.responseText != "failure"){
_("signupform").innerHTML = "";
_("advancedform").innerHTML = ajax.responseText;
$('#ajaxreturnform').validationEngine('attach'); //Here
} else {
window.scrollTo(0,0);
_("signupform").innerHTML = "Error Occured";
}
}
}
I've looked around here and found this post Attach Validation the accepted answer may inlight your problem also. Try to put the 'attach' command as a parameter to your binder as well as the #id of your form.

fetching xml data into a div via ajax and javascript

Building a chat app and I am trying to fetch all logged in user into a div with ID name "chat_members". But nothing shows up in the div and I have verified that the xml file structure is correct but the javascript i'm using alongside ajax isn't just working.
I think the problem is around the area of the code where I'm trying to spool out the xml data in the for loop.
XML data sample:
<member>
<user id="1">Ken Sam</user>
<user id="2">Andy James</user>
</member>
Javascript
<script language="javascript">
// JavaScript Document
var getMember = XmlHttpRequestObject();
var lastMsg = 0;
var mTimer;
function startChat() {
getOnlineMembers();
}
// Checking if XMLHttpRequest object exist in user browser
function XmlHttpRequestObject(){
if(window.XMLHttpRequest){
return new XMLHttpRequest();
}
else if(window.ActiveXObject){
return new ActiveXObject("Microsoft.XMLHTTP");
} else{
//alert("Status: Unable to launch Chat Object. Consider upgrading your browser.");
document.getElementById("ajax_status").innerHTML = "Status: Unable to launch Chat Object. Consider upgrading your browser.";
}
}
function getOnlineMembers(){
if(getMember.readyState == 4 || getMember.readyState == 0){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.send(null);
}else{
// if the connection is busy, try again after one second
setTimeout('getOnlineMembers()', 1000);
}
}
function memberReceivedHandler(){
if(getMember.readyState == 4){
if(getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
}
</script>
HTML page
<body onLoad="javascript:startChat();">
<!--- START: Div displaying all online members --->
<div id="chat_members">
</div>
<!---END: Div displaying all online members --->
</body>
I'm new to ajax and would really appreciate getting help with this.
Thanks!
To troubleshoot this:
-- Use an HTTP analyzer like HTTP Fiddler. Take a look at the communication -- is your page calling the server and getting the code that you want back, correctly, and not some type of HTTP error?
-- Check your IF statements, and make sure they're bracketed correctly. When I see:
if(getMember.readyState == 4 || getMember.readyState == 0){
I see confusion. It should be:
if( (getMember.readyState == 4) || (getMember.readyState == 0)){
It might not make a difference, but it's good to be absolutely sure.
-- Put some kind of check in your javascript clauses after the IF to make sure program flow is executing properly. If you don't have a debugger, just stick an alert box in there.
You must send the xmlhttp request before checking the response status:
function getOnlineMembers(){
getMember.open("GET", "get_chat.php?get_member", true);
getMember.onreadystatechange = memberReceivedHandler;
getMember.timeout = 1000; //set timeout for xmlhttp request
getMember.ontimeout = memberTimeoutHandler;
getMember.send(null);
}
function memberTimeoutHandler(){
getMember.abort(); //abort the timedout xmlhttprequest
setTimeout(function(){getOnlineMembers()}, 2000);
}
function memberReceivedHandler(){
if(getMember.readyState == 4 && getMember.status == 200){
var chat_members_div = document.getElementById('chat_members');
var xmldoc = getMember.responseXML;
var members_nodes = xmldoc.documentElement.getElementsByTagName("member");
var n_members = members_nodes.length;
for (i = 0; i < n_members; i++) {
chat_members_div.innerHTML += '<p>' + members_nodes[i].childNodes.nodeValue + '</p>';
chat_members_div.scrollTop = chat_members_div.scrollHeight;
}
mTimer = setTimeout('getOnlineMembers();',2000); //Refresh our chat members in 2 seconds
}
}
To prevent caching response you can try:
getMember.open("GET", "get_chat.php?get_member&t=" + Math.random(), true);
Check the responseXML is not empty by:
console.log(responseXML);
Also you might need to select the root node of the xml response before selecting childNodes:
var members_nodes = xmldoc.documentElement.getElementsByTagName("member"); //documentElement selects the root node of the xml document
hope this helps

Categories

Resources