I have built an AJAX driven form wherein when i press the submit button,it displays data via AJAX.All that is working fine.Now i want to hide a specific too as a part of the AJAX function.But instead of just hiding that the whole page goes blank!Heres the code
The AJAX function:
function ajax_post(){
$("#form1").hide();
var hr = new XMLHttpRequest();
var url = "my_parse_filefe.php";
var fn = document.getElementById("description").value;
var nm = document.getElementById("name").value;
var sel = $('#list option:selected').text()
var vars = "todo="+fn+"&name="+nm+"&sel="+sel;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
}
The PHP in the same file:
<?php
include_once "connect_to_mysql.php";
$sql = mysql_query("SELECT * FROM timetracking");
while($row = mysql_fetch_array($sql))
{$name = $row['name'];
$description = $row['description'];
$hours = $row['hours_invested'];
$finaltable1 .= '<table class="ftable" width="650">
<tr>
<td align="center">'.$name.'</td>
<td align="center">'.$description.'</td>
<td align="center"> '.$hours.'</td>
</tr>
';}
?>
<div id="form1"><?php print $finaltable1; ?> </div>
<div id="status"></div>
Note:When I put normal text inside the "form1" div it works!when i put php tags it stops working.
Related
php code :
while($row = mysql_fetch_assoc($arr))
{
$id = $row['id'];
$user_from = $row['user_from'];
$user_to = $row['user_to'];
$date = $row['date'];
$msg_body = $row['msg_body'];
$opened = $row['opened'];
if(strlen($msg_body)>150)
{
$msg_body = substr($msg_body,0,150)."....";
}
echo "<div id='toggletext$id' style='background-color:#ADD8E6;padding:6px;' onclick='toggle()'>";
echo "<form method='post'>";
echo "<input type='hidden' id='id1' value=$id>";
echo "<a href='$username'>$username</a> ";
echo " : $msg_body ";
echo "</form>";
echo "</div> <hr/>";
}
** it will echo the value present in $arr in forms of div so each $arr row will get displayed with unique div id **
js code :
function toggle()
{
var hr = new XMLHttpRequest();
var id = document.getElementById("id1").value;
var tx = "toggletext"+id;
var fn = document.getElementById(tx);
var url = "in.php";
fn.style.backgroundColor = "#fff";
var v = '<?php echo #$username;?>';
var vars = "post="+v+"&id="+id;
hr.open("POST", url, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
hr.onreadystatechange = function()
{
if(hr.readyState == 4 && hr.status == 200)
{
var return_data = hr.responseText;
document.getElementById("status").innerHTML = return_data;
}
}
hr.send(vars);
document.getElementById("status").innerHTML = "processing...";
}
// The problem is ...when there are 2 div(if $arr has 2 rows)..if i click the second div first div will get selected ..
Change your id in your input type hidden
echo "<input type='hidden' id='id".$id."' value=$id>";
and get like this in your javascript...
var incval = '<?php echo $id ?>';
var id = document.getElementById("id"+incval).value;
I am giving php echo because you already call username....
Finally, try to use My_Sqli function instead my_sql
I would need some advice/assistance here. I'm trying to pass 2 variable to other page from a link using ajax but when i click the link, there is no response. Seem like my ajax is not working, would appreciate if anyone can assist here. Thanks.
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script type="text/javascript" src="js/jquery-1.8.2.min.js"></script>
<script type="text/javascript" src="productshow.js"></script>
</head>
<body>
<?php
$sql = mysql_query ("SELECT * FROM espaceproduct WHERE email = 'jaychou#hotmail.com' ");
?>
<?php
$result1 = array();
$result2 = array();
$loopCount1 = 0;
$loopCount2 = 0;
while($row = mysql_fetch_array($sql))
{
$result1[] = $row['thumbnail'];
$result2[] = $row['id'];
$_SESSION['thumbnail'] = $result1;
//$url = "profileview.php?email=".$result1[$loopCount1].'&'. "id=".$result2[$loopCount2];
$loopproduct = $result1[$loopCount1];
$loopid = $result2[$loopCount2];
echo"<br/>"."<br/>";
echo '<a href="#" onClick="ajax_post($loopproduct,$loopid)" >'. $_SESSION['thumbnail'][$loopCount1] .'</a>'."<br/>" ;
$loopCount1++;
$loopCount2++;
}
?>
</body>
</html>
This my ajax page
function list_chats(){
var hr = new XMLHttpRequest();
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
document.getElementById("showbox").innerHTML = hr.responseText;
}
}
hr.open("GET", "productshow.php?t=" + Math.random(),true);
hr.send();
}
setInterval(list_chats, 500);
function ajax_post(la,ka){
// Create our XMLHttpRequest object
var hr = new XMLHttpRequest();
// Create some variables we need to send to our PHP file
var url = "espaceproductinsert.php";
var kn = "add="+la+"&csg="+ka;
hr.open("POST", url, true);
// Set content type header information for sending url encoded variables in the request
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
// Access the onreadystatechange event for the XMLHttpRequest object
hr.onreadystatechange = function() {
if(hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("status1").innerHTML = return_data;
}
}
// Send the data to PHP now... and wait for response to update the status div
hr.send(kn); // Actually execute the request
document.getElementById("csg").value = "";
}
This is the page where the variables should be insert
<?php
$add = $_POST['add'];
$csg = $_POST['csg'];
$sql2 = mysql_query ("INSERT INTO espaceproduct ( storename,productname ) VALUES ('$add','$csg') ");
?>
Smiply Try this
function ajax_post(la,ka){
$.post("espaceproductinsert.php", { add:la, csg:ka},
function(data) {
alert(data);
});
}
In page 1 add this script appropriately
<script language="javascript" type="text/javascript">
var httpObject=false;
if(window.XMLHttpRequest){
httpObject = new XMLHttpRequest();
}else if(window.ActiveXObject){
httpObject = new ActiveXObject("Microsoft.XMLHttp");
}
function tranferData(){
var data1= document.getElementById('div1').value;
var data2= document.getElementById('div2').value;
var queryString = "?data1=" + data1;
queryString += "&data2=" + data2;
httpObject.onreadystatechange = function(){
if(httpObject.readyState == 4 && httpObject.status == 200){
var error = document.getElementById('error');
var response = httpObject.responseText;
alert(response);
}
}
httpObject.open("GET", "page2.php"+queryString ,true);
httpObject.send(null);
}
</script>
You send the data using above script and recieve from another page
page 2
<?php
echo $_GET['data1'];
echo $_GET['data2'];
?>
and on the serverside do this
<?php
header('Content-Type: application/json');
echo json_encode($_GET); //for testing replace with array('key'=>$value);
?>
My code is below.I want to send id=content to the function mr. And then write result to the passed id=result.Although it is only for this html file,I want to make this function available for another html pages, and want to add this function in another util.js file.
Add Item:
<input type="text" name="name" id="content">
<br>
<button onclick="javascript:mr('POST',content,result,'post.php');"
type="button"
id="btn1">
Submit
</button>
<br>
<button onclick="javascript:mr('GET',content,result,'get.php');" type="button"
id="btn2" >
List Jobs
</button>
<div id="result"></div>
The function mr is like this.It is for ajax post and get operations:
function mr(type,content,result,URL) {
var hr = new XMLHttpRequest();
//var content = document.getElementById("content").value;
var vars = "content=" +content;
if (type == 'GET')
URL = URL + '?' + vars;
hr.onreadystatechange = function() {
if (hr.readyState == 4 && hr.status == 200) {
var return_data = hr.responseText;
document.getElementById("result").innerHTML = return_data;
}
}
hr.open(type, URL, true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
switch(type) {
case 'GET':
hr.send();
break;
case 'POST':
hr.send(vars);
break;
}
document.getElementById("result").innerHTML = "Processing...";
}
</script>
post.php
<?php echo "POST\n"; if(isset($_POST)) print_r($_POST); ?>
get.php
<?php echo "GET\n"; if(isset($_GET)) print_r($_GET); ?>
When I click submit ,I got the following output.
POST Array ( [content] => [object HTMLInputElement] )
And clicking list button the output:
GET Array ( [content] => [object HTMLInputElement] )
It's because of this line:
var vars = "content=" +content;
You're sending the actual <input> element instead of it's value or id. You were on the right track with the commented out line above it.
To send the value, not the input object:
var content = document.getElementById("content");
var vars = "content=" + content.value;
To send the id:
var content = document.getElementById("content");
var vars = "content=" + content.id;
I'm trying to do an AJAX call to pull back data to popluate a drop down box based off the select of another drop down box. My code is working fine in FF 9.0.1 (used for firebug), but failing in IE 7 (which is my company standard). I've tried several ways to show the data, and I don't have the time right now to learn how to do this in jQuery. I'm sure this will be a head smacker, but what about IE is causing this issue?
Here are my code pages. First is the trimmed down version of the form calling the JavaScript.
<html>
<head>
<script language="JavaScript" src="/includes/Transaction_Update.js"></script>
<form id="submit" name="submit" action="Transaction_Process.php" method="post">
<table align='left'>
<tr>
<td class='reporttd'>Vendor</td>
<td>
<select name='selVendorCode' id='selVendorCode' onChange="getServiceCode()">
<option value='' selected='selected'></option>
<?php echo $vendorOptionList; ?>
</select>
</td>
</tr>
<tr>
<td class='reporttd'>Service Code</td>
<td class='reporttd'>
<select name='selServiceCode' id='selServiceCode'>
<option value='' selected='selected'></option>
</select>
</td>
</tr>
</table>
</div>
</div>
</form>
JavaScript page
//setup xmlHttp request for Ajax call
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequestObject(){
var xmlhttp;
try{
xmlHttp = new XMLHttpRequest();
}
catch(e)
{
var xmlHttpVersions = new Array("MSXML2.XMLHTTP.6.0",
"MSXML2.XMLHTTP.5.0",
"MSXML2.XMLHTTP.4.0",
"MSXML2.XMLHTTP.3.0",
"MSXML2.XMLHTTP",
"Microsoft.XMLHTTP");
for (var i=0; i<xmlHttpVersions.length && !xmlHttp; i++){
try{
xmlHttp = new Activexobject(xmlHttpVersions[i]);
}
catch(e) {}
}
}
if (!xmlHttp){
alert("Error creating the XMLHttpRequest object.");
}
else{
return xmlHttp;
}
}
//Call page to get all service codes for a vendor.
function getServiceCode(){
if (xmlHttp){
try{
var vCode = document.getElementById("selVendorCode").value;
var parms = "vCode=" + vCode;
//Call Transaction_AJAX.php to pass back an XML.
xmlHttp.open("GET", "Transaction_AJAX.php?" + parms, true);
xmlHttp.onreadystatechange = handleRequestStateChange;
xmlHttp.send(null);
}
catch(e){
alert("Can't connect to server:\n" + e.toString());
}
}
}
//Checks state of the HTTP request call, and proceed if status is ready
function handleRequestStateChange(){
if (xmlHttp.readyState == 4){
if(xmlHttp.status == 200){
try{
handleServerResponse();
}
catch(e){
alert("Error reading the response: " + e.toString());
}
}
else{
alert("There was a problem retrieving the data:\n" + xmlHttp.StatusText);
}
}
}
//Handles response from the server
function handleServerResponse(){
var xmlResponse = xmlHttp.responseXML;
if (!xmlResponse || !xmlResponse.documentElement){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
var rootNodeName = xmlResponse.documentElement.nodeName;
if(rootNodeName == "parsererror"){
throw("Invalid XML Structure:\n" + xmlHttp.responseText);
}
xmlRoot = xmlResponse.documentElement;
if(rootNodeName != "root" || !xmlRoot.firstChild){
throw("Invalid XML structure:\n" + xmlHttp.responseText);
}
//Get response and load it into drop down
responseText = xmlRoot;
var sel = document.getElementById("selServiceCode");
sel.options.length = 0;
var opt = document.createElement("option");
document.getElementById("selServiceCode").options.add(opt);
for(var i=0; i < responseText.childElementCount; i++){
var newOpt = new Option(responseText.childNodes[i].childNodes[1].textContent,responseText.childNodes[i].childNodes[0].textContent);
sel.options[sel.options.length] = newOpt;
}
}
The PHP page creating the XML file
<?php
header('content-type:text/xml; charset=utf-8');
include("../includes/DBConn.php");
$vCode = $_GET['vCode'];
///Setup cursers and proc command
$curs = OCI_New_Cursor($c);
$stmt = OCI_Parse($c,"begin schema.package.procedure(:var_code, :expected_cv); end;");
OCI_Bind_By_Name($stmt, ":var_code", $vCode);
OCI_Bind_By_Name($stmt,":expected_cv",&$curs,-1,OCI_B_CURSOR);
//execute statment and cursors
oci_execute($stmt);
oci_execute($curs);
//Create xml document
$dom = new DOMDocument('1.0', 'UTF-8');
$root = $dom->createElement('root');
$root = $dom->appendChild($root);
//loop through results of Proc
while (ocifetchinto($curs,&$vendor_cv )) {
//Add node for each row
$occ = $dom->createElement("cell");
$occ = $root->appendChild($occ);
//Id Value
$id = "value";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
//Id text
$id = "text";
$child = $dom->createElement($id);
$child = $occ->appendChild($child);
//Here is the actual value
$id = $vendor_cv[1];
$value = $dom->createTextNode($id);
$value = $child->appendChild($value);
}
//Close xml tags and save.
$xmlString = $dom->saveXML();
//Echo XML back to Transaction_Update.js
echo $xmlString;
?>
Here is how you do it in jQuery
1) Include jQuery library in your head section of the page. (here i am refering it from the google cdn)
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>
</head>
In your javascript
$("#stateDropDown").change(function(){
var stateId=$("#stateDropDown").val();
$.ajax({
url: 'getcities.php?stateid='+stateId,
success: function(data) {
$("cityDropDown").html(data);
}
});
});
Assuming you have a HTML select element with id "stateDropDown" for states and another one with id "cityDropDown" for cities.
The above code will do the follolwing
1) When the value of state dropdown changes, it executes the inside code.
2 ) Reade the selected item value and store it in a variable called stateId.
3) Using the jQuery ajax method , it makes a call to getcities.php page with a query string key called stateid
4) when we get a response from the ajax call, the control flow will be in the part called "success" handler. there we are receiving the response in a variable called data.
5) setting the received response (data) as the inner html of the city dropdown.
Assuming the getcities.php page will return some output like this
<option value='1'>Ann Arbor</option>
<option value='2'>Dexter</option>
<option value='3'>Novi</option>
jQuery will take care of your cross browser issues. Yes its is well tested and everybody is using it.
http://www.jquery.com
You can change your for loop in handleServerResponse to the following to fix this issue:
for(var i=0; i < responseText.childNodes.length; i++){
var node = responseText.childNodes[i];
var text = node.childNodes[1].text ? node.childNodes[1].text : node.childNodes[1].textContent;
var value = node.childNodes[0].text ? node.childNodes[0].text : node.childNodes[0].textContent;
var newOpt = new Option(text,value);
sel.options[sel.options.length] = newOpt;
}
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.