I am trying to get a live chat working using PHP and mysql and AJAX. It is almost completely functioning, except I cant seem to figure out how to submit the chat message without reloading a page. I have a page, sendchat.php, that takes input from the previous page and enters the data into a database. I am trying to use a text input field and when the user clicks the enter key, it would execute the PHP page with the details needed to send to sendchat.php without actually loading or refreshing the page. This is what I have so far:
<form id="send-message-area">
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeydown="onChatEnter(this);"></textarea>
</form>
</div>
</td></tr></table>
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js">
function onChatEnter(str) {
if(event.key === 'Enter') {
$.ajax({
type: "GET",
url: "sendchat.php?msg=" + str ,
success : function() {
// here is the code that will run on client side after running clear.php on server
}
});
}
</script>
All it does is try to load the url, but its not trying to find sendchat.php or send the data. Instead it just tries to load a blank page. Where am I going wrong here? Everything seems spelled correctly and case sensitive. I check if the user pressed enter when they press a key. If they did, I am loading an AJAX function to execute a PHP page. Yet, it is not doing that. Just for FYI, I do not want a button there to be clicked.
EDIT:
I tried the suggestions below and still nothing. I decided to try a different approach now. Still doesn't work.
<script>
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","sendchat.php?msg="+str,true);
xmlhttp.send();
}
}
</script>
<p>Your message: </p>
<input type="text" id="sendie" maxlength = '100' onkeypress="updatechat(this.value);"></input>
Try this:
$("#send-message-area").submit(function(e) {
e.preventDefault();
e.stopPropagation();
});
I am not sure how.. But I fixed it.. I think it had to do with giving the input a name along with the ID. See below:
<script language="javascript" type="text/javascript">
function updatechat(str) {
if(event.key === 'Enter') {
if (str=="") {
document.getElementById("sendie").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (this.readyState==4 && this.status==200) {
document.getElementById("sendie").innerHTML=this.responseText;
}
}
var planetloc = document.getElementById("loc").value;
chaturl = "sendchat.php?msg="+str+"&loc="+planetloc;
sendie.value="";
xmlhttp.open("GET",chaturl,true);
xmlhttp.send();
}
}
//-->
</script>
This was the code I used for the html:
<p>Your message: </p>
<input type='text' id='sendie' name='sendie' maxlength = '100' onkeypress='updatechat(this.value);'></input>
<input type='hidden' id='loc' name='loc' value='$chatroom'></input>";
I also added chaturl to combine the ajax page I needed along with the parameters passed to it. It seemed by creating a variable for that it solved other issues too.
Related
So I'm trying to build a pretty simple website, to learn basic webdesign. It's just a random quote generator - you click on a button and it prints some famous quote. Anyway, I try to use ajax to get the quote, so I use this function:
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
but no matter what I type into RandomQuote.php, even if it's something like :
<?php
echo 'Hello, world';
?>
nothing shows up in the quote "div', it just becomes blank. I really have no idea what's the problem here. Thanks for the help!
Well, I'm not sure about much, but are you calling your function? You put your ajax inside loadXMLDoc() , so you probably have to call it. Another way is to put your ajax into an addEventListener so when a user clicks on something, it'll execute. If that's not the problem, try making sure your element in your html page with the id of "quote" is spelled correctly. Sometimes the latter scenario is always the problem for me.
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
console.log( "Load was performed." );
});
Don't forget to include jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This is my ajax function, try to use it:
/**
* #function ajax Send ajax-request with post
* #param {string} xmlpage Target url
* #param {string} data Post parameters (like param1=val1¶m2=val2...)
* #param {Function} callback
* #return {null}
*/
function ajax(xmlpage, data, callback)
{
var xmlh = null;
if(window.XMLHttpRequest)
xmlh = new XMLHttpRequest();
else
try
{
xmlh = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex)
{
xmlh = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlh)
{
xmlh.open("post", xmlpage, true);
xmlh.onreadystatechange = function(x)
{
if(xmlh.readyState==4 && typeof callback !== 'undefined')
callback(xmlh.responseText);
}
xmlh.setRequestHeader("Accept-Language","ru, en");
xmlh.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlh.send(data);
}
}
Following test files using your code from the question. It is working perfectly. Either you are missing something or its a browser issue. I tested on Mozilla. To be sure of browser independent code use jQuery for Ajax call
test.html
<html>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
RandomQuote.php
<?php
echo 'hi';
Update: jQuery version
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function loadXMLDoc()
{
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
});
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
I am using below code on my main page ,where other pages are loaded using ajax with the help of TWO RADIO BUTTONS
<script>
function loadXMLDoc(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
if(str=="Candidate")
{
xmlhttp.open("GET","creg.php",true);
}
else if(str=="Employer")
{
xmlhttp.open("GET","Empyr.php",true);
}
xmlhttp.send();
}
</script>
below script is written for FORM VALIDATION (written at end of main page),this script works only when main page loaded first time ,but when forms are getting loaded second time using ajax than this script is not working
<script>
$.validate({
form : '#cand, #employerRegister'
})
;
</script>
As i know script is getting read at the time of page load ,but now Where should I write this script so that it works when I load forms using ajax,where i am going wrong?
Are you using validation engine? I will not prefere doing ajax call with pure javascript it looks messy.
jQuery(document).ready(function($) {
$('#registration').validate({
rules:{
email: {
email: true
},
password : {
minlength : 6
},
repassword : {
minlength : 6,
equalTo : "#password"
}
},
submitHandler: function(form) {
// do other things for a valid form
var post = {};
form_data = $(form).serialize();
//console.log(form_data);
//console.log(book_form);
if(post)
{
$.post(site_url+'/members/register',form_data,
function(response){
var res1 = $.parseJSON(response);
console.log(res1);
if(res1.success == true )
{
$('.success_message').html('You are successfully registered ').show();
window.location.href = site_url+'/pages/registerstep';
clear_form(form);
}
else
{
$('.error_message').html(res1.success).show();
//clear_form(form);
}
}
);
}
}
});
});
Use something like this. This will work. Reason why your code is not working after first load is because your validation is not triggering while form submit
You need to run the code again to bind the event handler, after the new element is inserted into the DOM. It is better to use cross platform javascript framework like jQuery, Prototypejs etc
You need to call the bellow javascript again from ajax response
<script>
$.validate({
form : '#cand, #employerRegister'
})
;
</script>
Check here
The code 1: When I click on the "click here" it's supposed to hide the div with "id=adiv", and when I click again its show it again.
The code 2 and 3: the ajax code (code 2) belongs to code 3. but there not belong to code 1! this codes just refresh php page every 1 second.
Why after the ajax code (code 2&3) loads in the page, the 'code 1' stops working? When I click on "click here", its doing nothing.
But before the ajax load, the code 1 works good.
the codes 2 and 3 works good, i have no problem with them. the only problem is with code 1.
edit: when i debug this page its show me for the line: "hideshow(document.getElementById('adiv'))" (in code 1), this eror: "Uncaught ReferenceError: hideshow is not defined (anonymous function)".
but i dont really understand why i have this problem? and what i need to do to solve this?
1) The script:
Click here
<script type="text/javascript">
function hideshow(which){
if (!document.getElementById) { return; }
if (which.style.display=="block") { which.style.display="none"; }
else { which.style.display="block"; }
}
</script>
<div id="adiv" style="font:24px bold; display: block">Now you see me</div>
2) The ajax code:
<script type="text/javascript">
function refresh(name, url, info, info_1, info_2, type)
{
if (type == "send") {
document.getElementById("send_"+name).innerHTML = info; // just show the txt that send
Input(name);
if (info == "") {
document.getElementById(name).innerHTML="";
return;
}
}
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
var xhr = new XMLHttpRequest();
var params = "c=<?php echo $_GET["c"]; ?>&info="+info+"&info_1="+info_1+"&info_2="+info_2;
xhr.open("POST",url,true);
xhr.onreadystatechange = function() {
if( this.readyState == 4 && this.status == 200) {
document.getElementById(name).innerHTML = this.responseText;
}
};
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.setRequestHeader("Content-length", params.length);
xhr.setRequestHeader("Connection", "close");
xhr.send(params);
return false;
}
</script>
3) The code that play the ajax code:
<script type="text/javascript">
setInterval("refresh('aaa', 'refresh.php', '', '', '', 'refresh')", "1000");
</script>
There's a form users fill out and click the submit button. The data gets sent back to the server and based on the servers server's response the form is submitted or not (and the page is redirected or not). The problem is the form always submits and the page redirects before the server's response is received.
function SubmitForm(name, data1)
{
var result;
var checkResult = function(result)
{
alert("final value is: "+result)
return result
}
var xmlhttp
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if(xmlhttp.readyState == 4 && xmlhttp.status == 200)
{
if(xmlhttp.responseText)
{
result = true
}
else
{
document.getElementById("report").innerHTML = "blah blah blah"
result = false
}
checkResult(result)
}
}
xmlhttp.open("POST", "Checkdata1.php", true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded")
xmlhttp.send("name="+encodeURIComponent(name.value)+"&data1="+encodeURIComponent(data1.value))
//return false
}
Here's the HTML for the form that calls the above JavaScript function.
<form onsubmit="return isPasswordCorrect(document.getElementById('name'), document.getElementById('txtField1'))" action="nextpage.php" method="GET">
I know the idea is for the function to return false to prevent the form from being submitted, but how do I get it to wait long enough for the server to reply through Ajax? By the way, I haven't needed JQuery and if it's not necessary I'd prefer not to start using it now.
I would use a <button> that doesn't submit the form (the type isn't "submit"):
<form ...>
...
<button onclick="SubmitForm(...)">Submit</button>
</form>
Then at the end of SubmitForm, you can put:
document.querySelector("form").submit();
When you want to submit the form.
I am trying to load an XML file that asks for a username and password.
The code I'm using is as follows that I am trying to send the username and password in the URL:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
The full code of my page looks like this:
<html>
<body>
<textarea id="test1" name="test1" cols="90" rows="30">
XML file will be displayed here
</textarea><br>
<script type="text/javascript">
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("test1").value=xmlhttp.responseText;
} else
{
alert('Panel not communicating.Reason: '+xmlhttp.status);
}
}
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
xmlhttp.send();
</script>
</body>
</html>
Anyone know what I am doing wrong?
First, add this function to create the authorization header contents:
function make_base_auth(user, password)
{
var tok = user + ':' + pass;
var hash = Base64.encode(tok);
return "Basic " + hash;
}
Then, call the function and store the return value in a separate variable:
var auth = make_basic_auth('admin', 'admin');
Lastly, pass the value of auth to the XMLHttpRequest object:
xmlhttp.setRequestHeader('Authorization', auth);
xmlhttp.send();
Attribution: http://coderseye.com/2007/how-to-do-http-basic-auth-in-ajax.html
I ended up getting it working by doing the following:
Change:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false);
To:
xmlhttp.open("POST","http://admin:admin#192.168.0.5/myfile.xml",false,"username","password");
See this question for a similar scenario. How to use Basic Auth with jQuery and AJAX? Note one answer states that IE does not support credentials in a URL (as you are attempting to do).