How to use AJAX in IE - php

i'm using IE and I need to do a simple AJAX that will display a table with values from the database once a dropdown has been changed.
Here is my script:
<script type="text/javascript">
function getXML()
{
var req;
try {
req = new XMLHttpRequest();
} catch (trymicrosoft) {
try {
req = new ActiveXObject("Msxml2.XMLHTTP");
} catch (othermicrosoft) {
try {
req = new ActiveXObject("Microsoft.XMLHTTP");
} catch (failed) {
req = null;
}
}
}
if (!req){
return null;
} else {
return req;
}
}
function filter(month, year)
{
if(getXML()){
var xmlhttp = getXML();
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("mandayTable").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","ajax/filterMandays.php?m="+month+"&y="+year,true);
xmlhttp.send();
} else {
alert("Error initializing XMLHttpRequest!");
}
}
</script>
and here is my ajax php
<?php
$q = "SELECT md.mandays_id,md.employeenum,md.month,md.year,md.required_man_days,d.firstname,d.lastname
FROM tbl_mandays md,tbl_employee_details d
WHERE md.active = '1'
AND md.employeenum = d.employeenum
AND md.month = '10';"; //employee_details WHERE approver = 0"
$res = $db->Execute($q);
echo "<table border = 1>";
echo "<tr><th>Employee Number</th><th>First Name</th><th>Last Name</th><th>Month-Year</th><th>Required Man Days</th><th>Edit/Delete</th></tr>";
/while($rows = $res->FetchRow())
for($i=0;$i<5;$i++)
{
$mandays_id = $rows[0];
$empnum = $rows[1];
$month_year = $rows[2] ."-" .$rows[3];
$required_man_days = $rows[4];
$firstname = $rows[5];
$lastname = $rows[6];
echo "<tr><td>".$empnum . "</td><td>".$firstname ."</td><td>".$lastname ."</td><td>" . $month_year ."</td><td>" .$required_man_days . "</td><td width = \"200\" align = \"center\"><a href = 'edit_mandays.php?mandays_id=$mandays_id');'>Edit/Delete</a></td></tr>";
}
echo "</table>";
?>
THe problem is that on the first "ONCHANGE" it does not do anything.
on the 2nd "ONCHANGE" the headers of the table in the php code is the only one that's being echoed.
I alsoi tried doing it without the query and changing the loop into for($i=0;$i<5;$i++) and changed the qvalues to be displayed into "1" but still it does noty go into the loo[ and display it.
what seems to be the problem? :(

Start here : https://developer.mozilla.org/en/AJAX/Getting_Started , Mozilla explains the correct way to do this across browsers. Later, you may consider jQuery for cross-browser compatibility once you've learned the basics

Download and use jQuery for your website: http://docs.jquery.com/Downloading_jQuery#Download_jQuery
And then your code will be something like this:
$('.mydropdown').change(function(){
//get values for month, year
$.ajax({
url: "ajax/filterMandays.php?m="+month+"&y="+year,
type: "GET",
success: function(data){
//data is returned back
$('#mandayTable').html(data);
}
});
});

Related

Get data from 3 dropdown menus and populate a 4 one from db based on that 3 parameters

I need to know what is wrong. The PHP doesn't return anything. I think the variables don't get on the PHP file. Please help me to find out what goes wrong.
<?php
defined('_JEXEC') or die;
$db = JFactory::getDbo();
$an=$_POST['an'];
$fac=$_POST['fac'];
$uni=$_POST['uni'];
$result1 = mysql_query("SELECT * FROM drv_uni_$uni WHERE an='$an'");
while($row = mysql_fetch_array($result1)){
$display_string = "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>";
}
echo $display_string;
?>
Javascript
function getValFromDb() {
var valoare_selectata_uni = document.getElementById('category').value;
var valoare_selectata_fac = document.getElementById('subcategory').value;
var valoare_selectata_an = document.getElementById('an').value;
var url = "modules/mod_data/tmpl/script.php";
var params = 'uni=' + valoare_selectata_uni +
'&fac=' + valoare_selectata_fac +
'&an=' + valoare_selectata_an;
if (window.XMLHttpRequest) {
AJAX=new XMLHttpRequest();
} else {
AJAX=new ActiveXObject("Microsoft.XMLHTTP");
}
if (AJAX) {
AJAX.open("POST", url, false);
AJAX.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
AJAX.onreadystatechange = function() {
if(AJAX.readyState == 4 && AJAX.status == 200) {
var answer = AJAX.responseText;
document.getElementById('materie').innerHTML = answer;
}
};
AJAX.send(params);
}
}
You can debug the code using below few methods.
You can 1st print_r($result1) and see whether your SQL returns the results you want. If not try working on the query.
$display_string = "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>"; is wrong you should have a it like below. $display_string .= "<option value=\"".$row['materie']."\">". $row['materie'] ."</option>";. You are missing .=
if had static variables and included on the main it shows good. Rather than using $_POST use Joomla's way of retrieving POST data JRequest::getVar('an');. Read more
let me know the results I might be able to help you.

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.

ajax json decode mysql fetch array

$result = mysql_query ("SELECT * FROM order_list");
$test = array();
$i=0;
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
echo $myjsons[] = json_encode(array($row));
}
and a AJAX javascript
function ajaxFunction() {
var ajaxRequest; // The variable that makes Ajax possible!
try {
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e) {
// Internet Explorer Browsers
try {
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) {
// Something went wrong
alert("Your browser is too old to run me!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function() {
if (ajaxRequest.readyState == 4) {
document.getElementById("resultTXT").value = eval(" (" + ajaxRequest.responseText + ")");
}
}
ajaxRequest.open("POST", "userfind.php", true);
ajaxRequest.send(null);
}​
the javascript function wont store the array into the textbox
can anyone tell me whats the problem here?
Thanks
try:
while($row = mysql_fetch_assoc($result)){
$myjsons[] = json_encode(array($row));
}
echo json_encode($myjsons);
instead of
while($row = mysql_fetch_assoc($result)){
echo $myjsons[] = json_encode(array($row));
}
you can use jquery library for tha ajax call http://api.jquery.com/jQuery.post/
$.post('userfind.php', function(data) {
$("#resultTXT").val(data);// ==document.getElementById("resultTXT").value =data;
},'json'
);
JSON output would be invalid in your example, build the array and out put a single json encoded array like so:
$myjsons = array();
while($row = mysql_fetch_assoc($result)){
$myjsons[] = $row;
}
echo json_encode($myjsons);

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.

AJAX Div Retrieval every 60 seconds

What I would like to do is retrieve the contents of a PHP file and insert it into a div every 60 seconds, basically refreshing the dynamic div. I've come up with the following code so far, however it doesn't seem to be working. The code is just like this, nothing extra, apart from the MYSQL login.
PHP to grab:
<?php
$time = date("m/d/Y h:i:s a", time());
mysql_query("UPDATE djs SET requesttime='{$time}' WHERE username='{$djs['username']}'")
or die(mysql_error());
$request_db = mysql_query("SELECT * FROM requests
WHERE haveplayed='0'") or die(mysql_error());
echo "<table style=\"border:1px solid;width:99%;margin-left:auto;margin-right:auto;\" border=\"1\">";
echo "<tr><th>Title</th><th>Artist</th><th>Dedicated To...</th></tr>";
while($request = mysql_fetch_array( $request_db )) {
echo "<tr><td style=\"width:33%;padding:1px;\">";
echo $request['SongName'];
echo "</td><td style=\"width:33%;\">";
echo $request['Artist'];
echo "</td><td style=\"width:33%;\">";
echo $request['DedicatedTo'];
echo "</td></tr>";
}
echo "</table>";
?>
The original PHP code is just the same, enclosed in a div with an id attribute of 'ajax_table'.
The JavaScript is:
// JavaScript Document
var xmlHttp_moniter
function moniter()
{
xmlHttp_moniter = GetXmlHttpObject_parcel()
if(xmlHttp_moniter == null)
{
alert("browser does not support HTTP Request")
return
}
var url="ajax_table.php?random=" + Math.random()
xmlHttp_moniter.onreadystatechange = stateChanged
xmlHttp_moniter.open("GET",url,true)
xmlHttp_moniter.send(null)
}
function stateChanged()
{
if(xmlHttp_moniter.readyState==4 || xmlHttp_moniter.readyState == "complete")
{
document.getElementById("ajax_table").innerHTML = xmlHttp_moniter.responseText
setTimeout('ajax_table()',60000);
}
}
function GetXmlHttpObject_parcel()
{
var xmlHttp_moniter=null;
try
{
xmlHttp_moniter=new XMLHttpRequest();
}
catch (e)
{
//Internet Explorer
try
{
xmlHttp_moniter=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
xmlHttp_moniter=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp_moniter;
}
and that is on the page that is requesting the other php page.
How about using a framework like jQuery to simplify your javascript:
$(function() {
setInterval(function() {
$.get('ajax_table.php', function(data) {
$('#ajax_table').html(data);
});
}, 60 * 1000);
});
At first, there's no js function ajax_table() called in
setTimeout('ajax_table()',60000);
in your code.
At second point, are you sure you are calling moniter() function somewhere for the first time?
Try this, You can retrieve the contents of a PHP file and insert it into a div for every 60 seconds http://www.webtrickss.com/ajax/how-to-refresh-a-div-using-ajax/

Categories