Is there a way to send html id attribute to a function? - php

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;

Related

How can I merge 2 search forms together?

I am doing my website on Wordpress.
I have 2 search forms that appear separate on my website and I was wondering how could I merge them into one.
The first search form searches for products First search form
The second one searches for the location of the products Second search form
Sorry for asking this silly question and thank you for your help :D
Javascript is what you need to start learning. It is the essential other half of webpage design. With Javascript you can get the value from anything on the page. Here's the basic code for pulling the values from the inputs of two different forms and posting them to your PHP file.
<!--first form-->
<form>
<input type="text" id="product" name="product">
</form>
<!--second form-->
<form>
<input type="text" id="city" name="city">
</form>
<button onclick="continuePost()">Submit Both</button>
<div id="result"></div>
<script>
function continuePost() {
var product = encodeURIComponent(document.getElementById("product").value);
var city = encodeURIComponent(document.getElementById("city").value);
var params = "product="+product+"&city="+city;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myResponse = JSON.parse(this.responseText); //send a JSON response back from your PHP file
if(myResponse.hasOwnProperty('error')){
document.getElementById("result").innerHTML = myResponse.error;
}else{
var result1 = myResponse.myResult1;
var result2 = myResponse.myResult2[0]; //or whatever key and value pairs that you used in the JSON response that you sent back from you PHP file
document.getElementById("result").innerHTML = result1;
}
}else{
window.setTimeout(failed(), 3000);
}
};
xhttp.open("POST", "yourPHPfile.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send(params);
}
function failed(){
document.getElementById("result").innerHTML = 'Failed to connect to server.';
}
</script>
yourPHPfile.php
<?php
$obj = new stdClass();
$obj->dateread = date("D M j G:i:s T Y");
if(!isset($_POST["product"])){
$obj->error = 'No product.';
echo json_encode($obj);
exit;
}else {
$product=$_POST["product"];
}
if(!isset($_POST["city"])){
$obj->error = 'No city.';
echo json_encode($obj);
exit;
}else {
$city=$_POST["city"];
}
$obj->myResult1 = 'Info you want back from your PHP file.';
$obj->myResult2 = ['array', 'of', 'info', 'you', 'want'];
echo json_encode($obj);
?>

Creating a button that deletes data being displayed

Right now I have a program that uses AJAX to read in a XML file and a json file. The problem is once the user clicks one of these buttons the text stays on the page forever. I was wondering if there was a way to make a button that would delete the text and sort of start over. I tried making a reset button but it didn't work. Here is the code that I have. Thanks for the help in advance.
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml")
xmlHttp.send();
}
function getJSON() {
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>" + responseObject[i].name
+ " lived during the " + responseObject[i].pet
+ " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
</script>
</head>
<body>
<form>
<h3>Dinosaur Web Services</h3>
<div id="home"></div>
<button type="reset" value="Reset">Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();">JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();">XML Dinos</button>
</form>
</body>
</html>
You can empty the div before inserting the new value in it. Like below i have done for one of the div, and with same you can do to other.
Add this to your script
<script>
function reset() {
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = ""; // empty the div here
divObj.innerHTML = output;
}
</script>
and add this button in your HTML
RESET
Here you go:
<!DOCTYPE html>
<html>
<head>
<title>Assignment8</title>
<script src="ajax.js"></script>
<script>
function getXML() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get XML Document
var xmlDoc = xmlHttp.responseXML;
// Variable for our output
var output = '';
// Build output by parsing XML
dinos = xmlDoc.getElementsByTagName('title');
for (i = 0; i < dinos.length; i++) {
output += dinos[i].childNodes[0].nodeValue + "<br>";
}
// Get div object
var divObj = document.getElementById('dinoXML');
// Set the div's innerHTML
divObj.innerHTML = output;
}
}
xmlHttp.open("GET", "dino.xml", true);
xmlHttp.overrideMimeType("text/xml");
xmlHttp.send();
}
function getJSON() {
document.getElementById('msg').style.display = "none";
var xmlHttp = xmlHttpObjCreate();
if (!xmlHttp) {
alert("The browser doesn't support this action.");
return;
}
xmlHttp.onload = function() {
if (xmlHttp.status == 200) {
// Get Response Text
var response = xmlHttp.responseText;
// Prints the JSON string
console.dir(response);
// Get div object
var divObj = document.getElementById('dinoJSON');
// We used JSON.parse to turn the JSON string into an object
var responseObject = JSON.parse(response);
// This is our object
console.dir(responseObject)
// We can use that object like so:
for (i in responseObject) {
divObj.innerHTML += "<p>"+responseObject[i].name + " lived during the " + responseObject[i].pet + " period.</p>";
}
}
}
xmlHttp.open("GET", "json.php", true);
xmlHttp.send();
}
function resetDivs(){
document.getElementById('msg').style.display = "block";
document.getElementById('dinoJSON').innerHTML = "";
document.getElementById('dinoXML').innerHTML = "";
}
</script>
</head>
<body>
<form>
<h3> Dinosaur Web Services </h3>
<div id="home"></div>
<div id="msg">Select a button</div>
<button type="reset" value="Reset" onclick="resetDivs();"> Home</button>
<div id="dinoJSON"></div>
<button type="button" onclick="getJSON();"> JSON Dinos</button>
<div id="dinoXML"></div>
<button type="button" onclick="getXML();"> XML Dinos</button>
</form>
</body>
</html>

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;
}
}

jquery hide() executing wrongly

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.

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