ajax/php not able to edit files - php

I'm developing a web page that should read and change the contents of specific files on the server.
These files will only have two values: 1 or 0. Reading/changing the contents will be made via combo boxes with OnChange. Basically the idea is to control appliances via General Purpose Input/Outputs (GPIO's). The electronics part is all done, I just need to finish the web programing part and got stuck on it.
I'm not experienced in programing at all, but with some snippets found here and there, I was able to implement part of it with AJAX/PHP.
So far, I'm able to read the values, but unable to change it even though I'm building the correct command with "escapeshellarg".
Also, I was expecting to have two interactive areas in the page but only the original is working.
Could anyone point me into the right direction? Any help/suggestion/comment will be welcomed.
pqp6.php
<html>
<head>
<script>
function showUser(str)
{
if (str=="")
{
document.getElementById("txtHint").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 (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","getinfo.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>
<?php
$file1="/var/www/file1";
$file2="/var/www/file2";
$output = shell_exec('cat '.escapeshellarg($file1));
if($output == 0)
{
echo "zero ; ";
$file1status = "off";
$file1oposite = "on";
$file1exec= "file1on";
}
else
{
echo "one ; ";
$file1status= "on";
$file1oposite= "off";
$file1exec= "file1off";
}
echo "output:$output ; file1status:$file1status ; file1oposite:$file1oposite ; file1exec:$file1exec <br><br>";
$output = shell_exec('cat '.escapeshellarg($file2));
if($output == 0)
{
echo "zero ; ";
$file2status = "off";
$file2oposite = "on";
$file2exec= "file2on";
}
else
{
echo "one ; ";
$file2status= "on";
$file2oposite= "off";
$file2exec= "file2off";
}
echo "output:$output ; file2status:$file2status ; file2oposite:$file2oposite ; file2exec:$file2exec <br><br>";
?>
<br>
<br>
FILE 1:
<form>
<select name="file1" onchange="showUser(this.value)">
<option value="1,<?=$file1status?>"><?=$file1status?></option>
<option value="1,<?=$file1oposite?>"><?=$file1oposite?></option>
</select>
</form>
<br>
<div id="txtHint"><b>File 1 information will be listed here.</b> </div>
<br>
<br>
FILE 2:
<form>
<select name="file2" onchange="showUser(this.value)">
<option value="2,<?=$file2status?>"><?=$file2status?></option>
<option value="2,<?=$file2oposite?>"><?=$file2oposite?></option>
</select>
</form>
<br>
<div id="txtHint"><b>File 2 information will be listed here.</b></div>
</body>
</html>
getinfo.php:
<?php
$q=$_GET["q"];
$q_stripped = explode(",", $q);
$file_n = $q_stripped[0];
$file_command = $q_stripped[1];
$path="/var/www/file";
if($file_command == "on")
{
$file_command = "1 > ";
}
else
{
$file_command = "0 > ";
}
$command= "/bin/echo $file_command$path$file_n";
$escaped_command = escapeshellarg($command);
echo "COMMAND: $escaped_command";
shell_exec($escaped_command);
echo "file_n=$file_n ; file_command=$file_command ; ";
?><?php

By applying the escapeshellcmd your > 0 or > 1 is turned into \\> 0 and \\> 1 I guess that is why it doesnt work. You are not using escapeshellcmd, you are using escapeshellarg.
You might want to check the file permissions also.
However, instead of using system calls, have you ever thought about using
file_exists, file_get_contents or file_put_contents .
With those functions and writable dirs/files, you can achieve exactly what you are doing, without making system calls. Plus, it would be more portable.

Related

jQuery data sent from PHP is not the correct format?

I am using jQuery to send a part number from one php file to another.
The part number is received correctly in the destination php file, but when when I try to use it, it does not work.
Here is the strange thing: To test,when I use $mpn=STA-12 (or any other value that exists in table2), in destination php file, the connection is established and the relevant data is extracted, BUT when THE SAME DATA is fetched, it does not work
Here is the destination PHP file:
<?php
$row['mpn'] = $_GET['q'];
include("order/connection.php");
echo "mpn is here : ".$row['mpn']; // It displays STA-12 but doesn't data get fetched!
$mpn=$row['mpn'];
//$mpn="STA-12"; // *** When I actually put this line in, it all works ***
$stmt = $pd->prepare("SELECT * FROM table2 WHERE part_number = :part_number " );
//$stmt->execute(array());
$stmt->execute(array(':part_number' => $mpn));
$row = $stmt->fetch(PDO::FETCH_BOTH);
//... rest of the code
?>
This jQuery script copied from W3:
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
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("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET","serv.reply3.3.php?q="+str,true);
xmlhttp.send();
}
}
And this is where it is called from:
<form>
<select name="users" onchange="showUser(this.value)">
<option value="">Choose</option>
<option value=" <?php echo $row["mpn"]; ?> ">items</option>
</select>
</form>
The problem is finally solved.
Since the code was copied from another example, the jQuery variable sent over, contained some EXTRA information that when ECHO'ed didn't show.
echo "mpn is here : ".$row['mpn']; that displayed STA-12, actually contained ' string(6) " STA-12" ', which was discovered by doing:
var_dump( $row['mpn']).
This had my head scratching for days.

Auto complete multiple results in textfield from mysql database [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I am new in php and ajax. I have search a lot from internet for this problem but in vain. I want to make an auto complete system just like this website: (http://www.zameen.com/). My problem is more simple than this website. My requirement is: "When I will enter something in text field, it will show the match results from database. When i will select one of those results then it will show in the same text field. I want to select multiple results and all results will show in the same text field."
Now my next question is: "how i will handle all these results in php variables and post them to my required file."
I am so much confused. Please give a simple solution because I am new in php and ajax.
You can see an image to understand my problem on this link: (http://mutaliapakistan.com/problem.png).
I'll try to give you a simple, working example of what you want:
this will be your livesearch.js file:
function showResult(str)
{
if (str.length==0)
{
document.getElementById("livesearch").innerHTML="";
document.getElementById("livesearch").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("livesearch").innerHTML=xmlhttp.responseText;
document.getElementById("livesearch").style.border="1px solid #A5ACB2";
}
}
xmlhttp.open("GET","livesearch.php?q="+str,true);
xmlhttp.send();
}
And this will be your livesearch.php file:
<?php
$hint="";
//get the q parameter from URL
if (!isset($key))$key = $_GET['q'];
//include the mysql conn script
require_once ('mysql_connect.php');
//just change the selects here to what you want/ need.
$query = "SELECT DISTINCT * FROM table_name WHERE display='1' AND (name LIKE '%$key%' OR description LIKE '%$key%') LIMIT 5";
$result = mysql_query($query);
while($result_row = mysql_fetch_array($result))
{
$found = $result_row[12];
if (strlen($found)>25)
{
$found = substr($found, 0, 25) . '...';
}
$hint = $hint."<div id='search_result'>".$found."</div>";
}
// Set output to "no suggestion" if no hint were found
// or to the correct values
if ($hint == "")
{
$response = "No results";
}
else
{
$response = $hint;
}
//output the response
echo $response;
?>
And now finally to the page that you want to have the seach in it add the following:
<script type="text/javascript" src="livesearch.js"></script>
<div class="search">
<form name="frm_search" id="frm_search" method="get" action="advanced_search.php">
<input type="text" name="search" id="search" value="" placeholder=" Search" onkeyup="showResult(this.value)"/>
<input type="submit" name="search_go" id="search_go" value="↵"/>
</form>
<div id="livesearch" style="margin-left:3px;background-color:#fff;text-align:left;">
</div>
</div>
I hope it's clear.

JAVASCRIPT: OK button proceed to another .php form

I have a basic javascript code for my saving entry.
Scenario:
I have two forms, the first form,[view_netbldg.php], is for my data entry then when the user click the "ADD" button it will proceed to the next form [save_netbldg.php]. So in my save_netbldg.php form there is a if else condition where the code will know first if the variable of $bldgName or $netName are empty. Everything is okay, but my concern is this when the code detect either of the two variables are empty the code below I'm using will be executed.
Here's my code:
if($bldgName == "" || $netName == "")
{
echo "<script type='text/javascript'>\n";
echo "alert('Please complete the fields for Building Name or Network Name');\n";
echo "</script>";
header("location:view_netbdlg.php");
}
*The result of the program is, its not displaying the alert instead it will jump to the header
The correct way is, if the $bldgName == "" || $netName == "" == true** an alert will display and when the user click the ok button it will proceed to the next form which is "view_netbdlg.php". I don't need a confirmation message here because its only an error message something like that.
Advance thank you.
You are confusing php with javascript, You can solve this by
if($bldgName == "" || $netName == "")
{
echo "<script type='text/javascript'>\n";
echo "alert('Please complete the fields for Building Name or Network Name');\n";
echo "window.location='view_netbdlg.php';\n";
echo "</script>";
}
That happens because when the document loads, it stops when it finds a script tag.
In your case, you're trying to echo data in an undetermined part of the document, when it is already loaded.
Here's my solution:
PHP File (test.php):
<?php
if(!isset($_POST['bldgName']) || !isset($_POST['netName']) {
die("false"); //returns false if the values are NOT set
} else {
die("true"); //returns true if the values are set
}
?>
In your file (file.html):
<form method="post" action="test.php" id="formtest">
<input type="text" name="bldgName" />
<input type="text" name="netName" />
</form>
<script type="text/javascript">
if(getAjaxResponse(document.getElementById("formtest") == "true") {
alert("Please complete the fields for Building Name or Network Name");
window.navigate("view_netbdlg.php");
}
function getAjaxResponse(frm){
var elem = frm.elements;
var params = "";
url = form.action;
for(var i = 0; i < elem.length; i++){
if (elem[i].tagName == "SELECT"){
params += elem[i].name + "=" + encodeURIComponent(elem[i].options[elem[i].selectedIndex].value) + "&";
} else {
params += elem[i].name + "=" + encodeURIComponent(elem[i].value) + "&";
}
}
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("POST",url,false);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.setRequestHeader("Connection", "close");
xmlhttp.send(params);
return xmlhttp.responseText;
}
</script>
you have written the the code under script and never invoked that script
for that you have to use functions and call the function manually...
For more about function call refer
https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Function/Call
You could try:
if($bldgName == "" || $netName == ""){
header('Refresh: 10; URL=your url');#10 second delay
echo "Please complete the fields for Building Name or Network Name";
exit;#make sure rest of page doesn't render!
}

AJAX, PHP, MYSQL - innerHTML not working & Neither any Alternatives

I am a noob and i am trying to get this script working. It works perfectly in all browsers except IE. I have tried most of the solutions here on stackoverflow but none of them works for me. I am doing some kiddish mistake somewhere which I am unable to spot. Would request your help.
Also just to let you know the DOM Objects format of using appendchild might not work 100% correctly for me since this script basically passes values from a drop down which shows say numbers from 1 to 10 and based on those numbers it pulls up corresponding charts. So if I am viewing chart 1 then i can go ahead and select the drop down to view chart 3 as well. But if we use the appendchild property, it only allows me to see one of the charts by selecting 1 to 10 and it doesn't work unless I refresh the page. So unless deletechild is used I think it would not work, just my guess. Hence, I have commented that section out and I am using the good old method of innerhtml.
This is my JS function.
function showUser(str) {
debugger;
var xmlhttp = GetXmlHttpObject("Browser does not support HTTP Request");
if (str=="") {
document.getElementById("pairname").innerHTML="";
return;
}
/* <-- I HAVE ALREADY COMMENTED THIS OUT & am using a more robust function for this.
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("pairname").innerHTML=xmlhttp.responseText;
//AS YOU CAN SEE THE ALTERNATIVE SOLUTION OF USING DOM OBJECTS HAS BEEN COMMENTED OUT.. SINCE THIS IS ALSO NOT WORKING IN IE FOR ME.
//var wrappingElement = document.createElement("div");
//wrappingElement.innerHTML = xmlhttp.responseText;
//document.getElementById('pairname').appendChild(wrappingElement);
}
}
xmlhttp.open("GET","getimgdetails.php?q="+str,true);
xmlhttp.send();
}
function GetXmlHttpObject(errorMessage) {
var r = false;
try { r = new XMLHttpRequest(); }// Opera 8.0+, Firefox, Safari
catch(e) {
// Internet Explorer Browsers
try { r = new ActiveXObject("Msxml2.XMLHTTP"); }// older IE
catch(e) {
try { r = new ActiveXObject("Microsoft.XMLHTTP"); }// IE 5+
catch(e) {// AJAX not possible
if(errorMessage) { alert(errorMessage); }
}
}
}
return r;
}
AND THIS IS WHERE I AM SHOWING IT
<div id="pairname"><b>Charts will be shown here.</b></div>*
AND this is the Script which receives and sends back the info. SO basically it shows 5 charts for each number 1 to 10.
$q=$_GET["q"];
Echo "<img src=mqluploads/".$q."15.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."60.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."240.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."1440.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."10080.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
Echo "<img src=mqluploads/".$q."43200.gif?".time()."></img>";
Echo "<br>";
Echo "---------------------------------------------------------";
Echo "<br>";
?>
Many many thanks in advance for your help and for reading this far. I have been struggling with this for the past one week and now finally decided to seek some help. Looking forward to your advice.
Have you checked that your php script is returning some data. Try to access getimgdetails.php?q=str (replace str with correct paremeter) directly in browser.
Also place an alert(xmlhttp.responseText) before this line:
document.getElementById("pairname").innerHTML=xmlhttp.responseText;
This will help you to debug.

How to prevent the page from scrolling after an ajax request (return false not working or maybe in the wrong palce)

I want to display a tree with information about the Catalogue of Life which includes the Kingdom, phylum, order, etc information. I'm using ajax/php to interact with a mySQL database, while using javascript to display and output the information. I have finally completed the things I wanted it to do: expand and collapse on clicking, load only once, etc. But everytime something is clicked below the scroll limit, it bounces back to the top of the page. I researched this and saw something about including 'return false' in the function or the tag, but this did not solve the problem. Am I just putting it in the wrong place? Thanks for your help...
Here is the code: in its php/javascript goodness...
<?php
include ('includes/functions.php');
$connection=connectdb();
$result=runquery('
SELECT scientific_name_element.name_element as shortname ,taxon_name_element.taxon_id as taxonid
FROM taxon_name_element
LEFT JOIN scientific_name_element ON taxon_name_element.scientific_name_element_id = scientific_name_element.id
LEFT JOIN taxon ON taxon_name_element.taxon_id = taxon.id
LEFT JOIN taxonomic_rank ON taxonomic_rank.id = taxon.taxonomic_rank_id
LEFT JOIN taxon_name_element AS tne ON taxon_name_element.parent_id = tne.taxon_id
LEFT JOIN scientific_name_element AS sne ON sne.id = tne.scientific_name_element_id
LEFT JOIN taxon AS tax ON tax.id = tne.taxon_id
LEFT JOIN taxonomic_rank AS tr ON tr.id = tax.taxonomic_rank_id
WHERE taxon_name_element.parent_id is NULL');
set_time_limit(0);
ini_set('max_execution_time',0);
?>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.js"></script>
<script type="text/javascript">
function load_children(id){
if(document.getElementById(id).active != 'true'){
if(document.getElementById(id).loaded != 'true'){
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()
{//actual stuff
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{//change the text
this.active='true'
//document.getElementById(id).innerHTML = xmlhttp.responseText;
var oNewNode = document.createElement("ul");
document.getElementById(id).appendChild(oNewNode);
document.getElementById(id).active = 'true';
document.getElementById(id).loaded = 'true';
oNewNode.innerHTML="<i>"+xmlhttp.responseText+document.getElementById(id).active+"</i>";
}
}
xmlhttp.open("GET","new.php?id="+id,true);
xmlhttp.send(false);
}else{
$("#"+id).children().children().show(); document.getElementById(id).active = 'true'}}else{ $("#"+id).children().children().hide();
document.getElementById(id).active = 'false';
}return false;}
</script>
</head>
<body>
<?php
echo "<ul>";
while($taxon_name_element = mysql_fetch_array($result)){
echo "
<li id=\"{$taxon_name_element['taxonid']}\" style=\"display:block;\">{$taxon_name_element['shortname']}</li>
";}
echo "</ul></body></html>";
?>
You were missing a closing parenthesis - if popped it in with a comment where I think you were wanting it. If JS has an error it generally won't execute, and instead it'll fall back to the non JS (ie, the return false wont fire because of the error). Were you getting an actual error when running this? The console is a good friend when you're debugging JS.
Formatting your code like I have below will also help to identify any missing elements more easily.
function load_children(id)
{
if(document.getElementById(id).active != 'true')
{
if(document.getElementById(id).loaded != 'true')
{
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()
{
//actual stuff
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//change the text
this.active='true'
//document.getElementById(id).innerHTML = xmlhttp.responseText;
var oNewNode = document.createElement("ul");
document.getElementById(id).appendChild(oNewNode);
document.getElementById(id).active = 'true';
document.getElementById(id).loaded = 'true';
oNewNode.innerHTML="<i>"+xmlhttp.responseText+document.getElementById(id).active+"</i>";
}
}
xmlhttp.open("GET","new.php?id="+id,true);
xmlhttp.send(false);
} // This was missing - were you getting an error?
}
else
{
$("#"+id).children().children().show(); document.getElementById(id).active = 'true'}
}
else
{
$("#"+id).children().children().hide();
document.getElementById(id).active = 'false';
}
return false;
}
When you're done checking and if everything is ok, take a look at: http://api.jquery.com/jQuery.get/ - the example's are at the bottom.

Categories