keypressed() and onCLick() implementation problem in IE - php

I've the following input text box and a button.
<div id="sender" onKeyUp="keypressed(event);">
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>
The keypressed(event) function actually detects if the key being pressed is "Enter" and calls the doWork() function.
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
This code seems to work fine in Chrome & Firefox. But in IE, the function seems to called twice.
Can anyone help me tweak the code so that it works properly in IE also.
Thanks
EDITED:
Whole ajax codes
<!--
var httpObject = null;
var link = "";
var timerID = 0;
var nickName = "Unname"; //"<?php echo $nickname; ?>";
// Get the HTTP Object
function getHTTPObject(){
if (window.ActiveXObject) return new ActiveXObject("Microsoft.XMLHTTP");
else if (window.XMLHttpRequest) return new XMLHttpRequest();
else {
alert("Your browser does not support AJAX.");
return null;
}
}
// Change the value of the outputText field
function setOutput(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML += response;
objDiv.scrollTop = objDiv.scrollHeight;
var inpObj = document.getElementById("msg");
inpObj.value = "";
inpObj.focus();
}
}
// Change the value of the outputText field
function setAll(){
if(httpObject.readyState == 4){
var response = httpObject.responseText;
var objDiv = document.getElementById("result");
objDiv.innerHTML = response;
objDiv.scrollTop = objDiv.scrollHeight;
}
}
// Implement business logic
function doWork(){
httpObject = getHTTPObject();
if (httpObject != null) {
link = "message.php?nick="+nickName+"&msg="+encodeURIComponent(document.getElementById('msg').value);
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setOutput;
httpObject.send(null);
}
}
// Implement business logic
function doReload(){
httpObject = getHTTPObject();
var randomnumber=Math.floor(Math.random()*10000);
if (httpObject != null) {
link = "message.php?all=1&rnd="+randomnumber;
httpObject.open("GET", link , true);
httpObject.onreadystatechange = setAll;
httpObject.send(null);
}
}
function UpdateTimer() {
doReload();
timerID = setTimeout("UpdateTimer()", 5000);
}
function keypressed(e){
if(e.keyCode=='13'){
doWork();
}
}
//-->

If someone is facing a similar problem, this could be useful.
I solved the problem by detecting IE browser using PHP script and discarding the onKeyUp() function while rendering HTML for IE.
IE Detection PHP script
//Detect IE function
function detectIE() {
if (isset($_SERVER['HTTP_USER_AGENT']) && (strpos($_SERVER['HTTP_USER_AGENT'], 'MSIE') !== false))
return true;
else
return false;
}
And this is how i changed the event handling.
<div id="sender" <?php if (detectIE()) { /*do nothing */ } else { echo "onKeyUp=\"keypressed(event);\""; } ?> >
Your message: <input type="text" name="msg" size="70" id="msg" />
<button onClick="doWork();">Send</button>
</div>

Related

Ajax reply javascript not functioning for validation

am trying to generate report through dynamically generated form. Through XMLHttpRequest the form loads well but the validation against the form fields wont work. I have tried eval() it works only during load time ( like eval(alert("hi")) but not on dom objects , think some scope problem. The form fields are dynamically generated and so its validation based on selection and availability role in database.
The code of two files is attached below
<script>
function showUser(str)
{
if (window.XMLHttpRequest)
{
xmlhttp=new XMLHttpRequest();
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var s= xmlhttp.responseText;
parseScript1(s);
parseScript(s);
}
}
xmlhttp.open("GET","test2.php",true);
xmlhttp.send();
}
function parseScript1(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
var k = "<script> "+ scripts +"<\/script>";
document.getElementById("txtHint1").innerHTML=k ;
// Return the cleaned source
return source;
}
function parseScript(_source) {
var source = _source;
var scripts = new Array();
// Strip out tags
while(source.indexOf("<script") > -1 || source.indexOf("</script") > -1) {
var s = source.indexOf("<script");
var s_e = source.indexOf(">", s);
var e = source.indexOf("</script", s);
var e_e = source.indexOf(">", e);
// Add to scripts array
scripts.push(source.substring(s_e+1, e));
// Strip from source
source = source.substring(0, s) + source.substring(e_e+1);
}
document.getElementById("txtHint").innerHTML=source;
// Return the cleaned source
return source;
}
function valid()
{
eval(validate());
}
</script>
<div id="txtHint1"><b>javascript will appear here</b></div>
<form>
<div id="nons1" >
<select id="nope1" name="users" onchange="showUser(this)">
<option value="">Select a option:</option>
<option value="1">not working here</option>
</select>
</div>
</form>
<div id="txtHint"><b>Select the value .</b></div>
test2.php
echo "<p>This form works fine singly not with xmlhttprequest";
echo'<form name="frm" method="post" action="test2.php" onsubmit="return(eval(validate()));">';
echo '<input value="" name="kfrm19" type="text">';
echo '<input name="save" value="submit" type="submit"></form>';
echo '<script>
function validate(){
if( document.frm.kfrm19.value.trim()=="")
{
alert( "If you can see this message .its working..." );
document.frm.kfrm19.focus() ;
return false;
}
}
</script>';
?>
try this:
function validate(){
if(document.frm.kfrm19.value.length == 0)
{
alert("If you can see this message .its working...");
document.frm.kfrm19.focus();
return false;
}
}

PHP and AJAX onclick redirection

I am using Ajax to populate a drop down menu from the database, my question is how do I onclick redirect it to a page along with the CARD_ID i got back from the database?
right now when I click on it it's displaying the card name in the search bar which is part of what I want but now I need the other half the redirection. How can I achieve this?
<?php
$mysqli = mysqli_connect('localhost', 'root', '', 'draftdb');
if(mysqli_connect_errno())
{
echo "Connection Failed: " . mysqli_connect_errno();
exit();
}
$str = $_GET['content'];
if(strlen($str))
{
$sel = mysqli_query($mysqli, "select CARD_NAME, CARD_ID,CARD_TYPE from cards where CARD_NAME like '".trim($str)."%'");
if(mysqli_num_rows($sel))
{
echo "<table border =\"0\" width=\"100%\">\n";
if(mysqli_num_rows($sel))
{
echo "<script language=\"javascript\">box('1');</script>";
while($row = mysqli_fetch_array($sel))
{
$card_info = str_ireplace($str,"<b>".$str."</b>",($row['CARD_NAME']));
$card_type = str_ireplace($str,"<b>".$str."</b>",($row['CARD_TYPE']));
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\" onClick=\"display('".$row['CARD_NAME']."');\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
}
}
echo "</table>";
}
}
else
{
echo "<script language=\"javascript\">box('0');</script>";
}
?>
the javascript.
subject_id = '';
function handleHttpResponse() {
if (http.readyState == 4) {
if (subject_id != '') {
document.getElementById(subject_id).innerHTML = http.responseText;
}
}
}
function getHTTPObject() {
var xmlhttp;
/*#cc_on
#if (#_jscript_version >= 5)
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
#else
xmlhttp = false;
#end #*/
if (!xmlhttp && typeof XMLHttpRequest != 'undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp = false;
}
}
return xmlhttp;
}
var http = getHTTPObject(); // We create the HTTP Object
function getScriptPage(div_id,content_id)
{
subject_id = div_id;
content = document.getElementById(content_id).value;
http.open("GET", "script_page.php?content=" + escape(content), true);
http.onreadystatechange = handleHttpResponse;
http.send(null);
if(content.length>0)
box('1');
else
box('0');
}
function highlight(action,id)
{
if(action)
document.getElementById('word'+id).bgColor = "#C2B8F5";
else
document.getElementById('word'+id).bgColor = "#F8F8F8";
}
function display(word)
{
document.getElementById('text_content').value = word;
document.getElementById('box').style.display = 'none';
document.getElementById('text_content').focus();
}
function box(act)
{
if(act=='0')
{
document.getElementById('box').style.display = 'none';
}
else
document.getElementById('box').style.display = 'block';
}
the html
<div class="ajax-div">
<div class="searchbar">
<input type="text" onKeyUp="getScriptPage('box','text_content')" id="text_content">
</div>
<div id="box"></div>
</div>
I'm not sure what you are trying to do, but it seems you want something like this:
1- Change the way you display your rows so that the ID gets sent to your function as well:
echo "<tr id=\"word".$row['CARD_ID']."\" onmouseover=\"highlight(1,'".$row['CARD_ID']."');\" onmouseout=\"highlight(0,'".$row['CARD_ID']."');\"
onClick=\"display('".$row['CARD_NAME']."', " . $row['CARD_ID'] . ");\" >\n<td>".$card_info." ".$card_type."</td>\n</tr>\n";
^^^^^^^^^^^^^^^^^^^^^^^^^
2- Change your display function to redirect
function display(word, id)
{
// document.getElementById('text_content').value = word;
// document.getElementById('box').style.display = 'none';
// document.getElementById('text_content').focus();
window.location.href = "some_page.php?card_id=" + id;
}
I have commented out the original lines because there doesn't seem much point in doing stuff on a page you are leaving anyway. You could also completely remove the word parameter if this is the solution you are looking for.

Onclick Event Not Working, Onmouse Working Though

I have build an instant search with AJAX, It is like when you start typing result appears, then if you click anywhere on the body result disappear, onmouse over at input field result re appear. when clicked inside input field result disappers.
I want this result to stays open after onmouse event when clicked in input field. for that i have added a click event, but it is not working.
Please see the codes and suggest any possible way to do this.
<script type="text/javascript">
function showResult(str) {
if (str.length == 0) {
document.getElementById("search-result").innerHTML = "";
document.getElementById("search-result").style.border = "0px";
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 (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("search-result").innerHTML = xmlhttp.responseText;
document.getElementById("search-result").style.border = "1px solid #A5ACB2";
document.getElementById("search-result").style.display = "block";
document.getElementById("search-input").onmouseover = function() {
show_box()
};
document.getElementById("search-input").onclick = function() {
show_box()
};
}
}
xmlhttp.open("GET", "instant-search.php?keyword=" + str, true);
xmlhttp.send();
}
function close_box() {
fadeOut();
document.getElementById("search-result").style.display = "none";
}
function show_box() {
setOpacity(0);
document.getElementById("search-result").style.display = "block";
fadeIn();
}
document.onclick = function() {
close_box()
};
function setOpacity(value) {
document.getElementById("search-result").style.opacity = value / 10;
document.getElementById("search-result").style.filter = 'alpha(opacity=' + value * 10 + ')';
}
function fadeIn() {
for (var i = 20; i <= 100; i++)
setTimeout('setOpacity(' + (i / 5) + ')', 5 * i);
}
function fadeOut() {
for (var i = 20; i <= 100; i++)
setTimeout('setOpacity(' + (5 - i / 5) + ')', 5 * i);
}
</script>
HTML Code
<input name="keyword" type="text" size="50" id="search-input" onkeydown="showResult(this.value)" autocomplete="off" />
<div id="search-result"></div>
I'm so into jQuery that I forgot there is a difference on IE.
if(!e) {
e = window.event;
}
if(e.stopPropagation && e.preventDefault) {
e.stopPropagation();
e.preventDefault();
} else {
e.cancelBubble = true;
e.returnValue = false;
}
try this?
<input name="keyword" type="text" size="50" id="search-input" onclick="showResult(this.value)" autocomplete="off" />
or to test if onclick works
<input name="keyword" type="text" size="50" id="search-input" onclick="alert('replace this with your function you want to call');" autocomplete="off" />

Correct way to submit a mail form using ajax? - no JQuery

I'm trying to handle a php mailform with ajax. It's a simple form that sends a message to my e-mail with the users phonenumber etc.
I'm not experienced with php at all but I got it to send me mail using a regular submit and then returning to the index page.
As this does not provide any feedback to the user this isn't working for me. I've found some examples using JQuery. I've also seen people using both GET and POST. I'm confused now how I should proceed.
The JQuery version of what I'm trying to achieve would look similar to this I guess.
var dataString = 'name='+ name + '&email=' + email + '&message=' + message;
$.ajax({
type: "POST",
url: "mail.php",
data: dataString,
success: function() {
$('#myForm').html("<div id='response'></div>");
$('#response').html("<h2>Contact Form Submitted!</h2>");
}
});
<?php
$mail = $_POST['email '];
$name = $_POST['name'];
$subject = 'new submit';
$text = $_POST['message'];
$to = “yourmail#domain.com”;
$message =” You received a mail from “.$mail;
$message .=” Text of the message : “.$text;
mail($to, $subject,$message)
?>
As the others said, jQuery is better than the natural way of using AJAX. But for the answer, firstly you should create a XmlHttp object in JavaScript. Then you can send your value to your page with the proper GET or POST method. After that, you can track the process by getting the state of posted request which it's implemented in stateChanged function. That's All!
var xmlhttp
function retrive(url, str){
xmlhttp = GetXMLHTTPObject();
if(xmlhttp==null){
alert("Your browser doesn't support the ajax.");
return;
}
var script=url;
script=script+"?value="+str;
xmlhttp.onreadystatechange = stateChanged;
xmlhttp.open("GET",script,true);
xmlhttp.send(null);
}
function stateChanged(){
if(xmlhttp.readyState == 0){
document.getElementById("result").innerHTML = "not initialized";
}
if(xmlhttp.readyState == 1){
document.getElementById("result").innerHTML = "has been set up";
}
if(xmlhttp.readyState == 2){
document.getElementById("result").innerHTML = "has been sent";
}
if(xmlhttp.readyState == 3){
document.getElementById("result").innerHTML = "in process";
}
if(xmlhttp.readyState == 4){
document.getElementById("result").innerHTML = xmlhttp.responseText;
}
}
function GetXMLHTTPObject(){
if(window.XMLHttpRequest){
//code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if(window.ActiveXObject){
//code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
I think it's better to see the definition of XmlHttpObject.
Solved it like this:
<form id="form" method="post" name="mailform" action="mail.php" onsubmit="mail(); return false;">
<p>
<label for='name'>Stuff</label><br>
<input type="text" name="stuff">
</p>
<input type="submit" name="submit" value="Send">
</form>
<p id="result" style="display: none">
<img src="images/succes.png"><br>
Thank you
</p>
/*----------------------------*/
function mail() {
var form = document.getElementById("form");
var name = form.name.value;
var email = form.email.value;
var phone = form.phone.value;
var message = form.message.value;
var valid = true;
if (!name) {form.name.style.backgroundColor = '#FF9481'; valid = false; }
else {form.name.style.backgroundColor = '';}
if (!email && !phone) {form.email.style.backgroundColor = '#FF9481'; form.phone.style.backgroundColor = '#FF9481'; valid = false;}
else {form.email.style.backgroundColor = ''; form.phone.style.backgroundColor = '';}
if (!message) {form.message.style.backgroundColor = '#FF9481'; valid = false;}
else {form.message.style.backgroundColor = '';}
if (email) {
var patt=/\b[A-Z0-9._%+-]+#[A-Z0-9.-]+\.[A-Z]{2,4}\b/gi;
var result=patt.test(email);
if (!result) {form.email.style.backgroundColor = '#FF9481'; valid = false;}
else form.email.style.backgroundColor = '';
}
if (phone) {
var patt=/[^0-9|\-| ]/g;
var result=patt.test(phone);
if (result) {form.phone.style.backgroundColor = '#FF9481'; valid = false;}
else form.phone.style.backgroundColor = '';
}
if (!valid) return false;
var datastr = 'name='+ name + '&email=' + email + '&phone=' + phone + '&message=' + message;
var xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
if (xmlhttp.responseText == "ok") {
form.style.display = 'none';
document.getElementById("result").style.display = '';
}
else {
form.message.value= "That doesn't seem right";
}
}
}
xmlhttp.open("GET","mail.php?" + datastr,true);
xmlhttp.send();
}
/*----------------------------*/
<?php
$name = $_GET['name'];
$etc...
if(IsInjected($name)||IsInjected($visitor_email)||IsInjected($phone)||IsInjected($message))
{
echo "Something fishy going on?";
exit;
}
[...]
mail($to,$email_subject,$email_body,$headers);
echo "ok";
function IsInjected($str)
{
$injections = array('(\n+)',
'(\r+)',
'(\t+)',
'(%0A+)',
'(%0D+)',
'(%08+)',
'(%09+)'
);
$inject = join('|', $injections);
$inject = "/$inject/i";
if(preg_match($inject,$str))
{
return true;
}
else
{
return false;
}
}
?>

Problem in php ajax post value

I want to make a php ajax post.(post value without refresh the page) here is my code. It can return the value and show in <div id="msg"></div>, But I also want to use this value.
In #benhowdle89 's help, I made $name= "<div id='msg'></div>". but when I use echo $name, in the source code, I can see <div id='msg'></div>(html tag), this is not a pure value, so I tried to use strip_tags, but the value lost. it seems the left the ajax pointed div tag, the value also gone. Still waiting for help...
index.php
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript">
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
</script>
</head>
<body>
<?php
echo $name="<div id='msg'></div>";
$name1=strip_tags($name);
$name2 = explode("|",$name1);
$namea=$name2[0];
$nameb=$name2[1];
?>
<form name="user_info" id="user_info" method="post">
<input name="user_name" type="hidden" value="abc|def" /><br />
<input type="button" value="abc|def" onClick="saveUserInfo()">
</form>
</body>
value.php
<?php
echo $_POST["user_name"];
?>
This is what I want. post value from index.php, then get the value by self without refresh the page. one botton with two values, I want explode them and finally get $namea and $nameb. I want use them in other php part.
You can put the ajax response into a javascript variable, then you can manipulate it from there:
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
alert( myPhpVariable );
Here is a working javascript example (full code):
function saveUserInfo() {
var msg = document.getElementById("msg");
var f = document.user_info;
var userName = f.user_name.value;
var url = "value.php";
var postStr = "user_name="+ userName;
var ajax = false;
if(window.XMLHttpRequest) {
ajax = new XMLHttpRequest();
if (ajax.overrideMimeType) {
ajax.overrideMimeType("text/xml");
}
} else if (window.ActiveXObject) {
try {
ajax = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajax = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
}
}
}
if (!ajax) {
window.alert("wrong");
return false;
}
ajax.open("POST", url, true);
ajax.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
ajax.send(postStr);
ajax.onreadystatechange = function() {
if (ajax.readyState == 4 && ajax.status == 200) {
var myPhpVariable = ajax.responseText;
msg.innerHTML = myPhpVariable;
// myPhpVariable is now a variable which you can use
alert( myPhpVariable );
}
}
}
The PHP file would look like:
$postVar = $_POST["user_name"];
$postVarArr = explode('|', $postVar);
// will show abc
//echo $postVarArr['0'];
// will show def
echo $postVarArr['1'];
by including $name= "<div id='msg'></div>" and calling echo $name, you're just telling the program to store "" in the $name variable and then print what is stored in that variable. That's why you're getting the unwanted output.
not sure if you're having problems posting the value or showing it in the value, but you need to echo the variable where the userName is stored, may need to send that from the ajax to the php and set it to $name.

Categories