jQuery passing multiple values in Data and editing event - php

I am creating a php file to alter file systems and I want to make this php run in the background on a ubuntu server. The html creates a webpage but the php does not trigger at all.
I followed a youtube video to this point but I need to pass both new and old string to the php in the Data part of my query which I am unsure how to do.
HTML code
<html>
<head>
<meta charset ='utf-8'/>
<title> JQuery test </title>
<script src= "https://ajax.googleapis.cpm/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
</head>
<body>
<td>Please type in the old string</td>
<input id= 'Old_String' />
<td>Please type in the new string</td>
<input id= 'New_String' />
<script>
$(document).ready(function() {
$('#New_String').change(function(){
$.ajax({
type: 'GET',
url: 'replace.php',
data: 'Old_String='+$('#Old_String').val(),
success : function(msg){
$('#results').html(msg);
}
})
});
});
</script>
<table border="0">
<div id="results' ></div>
</body>
My php code
<?php
$valid = true;
if (!empty($_GET["Old_string"])) {
$Old_string = $_GET["Old_string"];
} else {
$valid = false;
echo "Old string is Empty . Please Enter value to proceed\n";
}
if (!empty($_GET["New_string"])) {
$New_string = $_GET["New_string"];
} else {
$valid = false;
echo "New string is Empty . Please Enter value to proceed\n";
}
if ($valid) {
echo "all input correct\n";
$myfile = fopen("word.txt", "r+") or die("Unable to open file!");
if (flock($myfile, LOCK_EX)) {
$text = fread($myfile, filesize("word.txt"));
$count = 0;
$newstring = str_ireplace($Old_string, $New_string, $text, $count);
file_put_contents("word.txt", $newstring);
echo "Number of changes made = " . $count;
flock($myfile, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print "Could not lock $filename!\n";
}
fclose($myfile);
}
?>
}
For some reason my PHP does not fire at all and no output is shown in the div results. Am I passing the values incorrectly or am I not quite doing this right? Please any suggestion would be appreciated. I am also trying to switch the event so that it triggers on a button click if you could show me how to do that I would very much appreciate it.

You had multiple errors.
These languages are case sensitive. You had different cases for the varables all over the place. So I made everything lowercase.
You can't mix the quotes. So when you start with a ' you need to end with a '.
You may need to create the word.txt file manually. The web server normally does not have permissions to create files in the web root dir.
The browser does not pay attention to new lines "\n" you need to use
Added some error reporting on the top.
index.php
<html>
<body
<head>
<meta charset ='utf-8'/>
<title> JQuery test </title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.0/jquery.min.js"></script>
</head>
<table border="0">
<tr>
<td>Old String</td>
<td align="center"><input type="text" name="old_string" size="30" id="old_string" /></td>
</tr>
<tr>
<td>New String</td>
<td align="center"><input type="text" name="new_string" size="30" id="new_string" /></td>
</tr>
<div id="results" ></div>
</table>
</form>
<script>
$(document).ready(function() {
$('#new_string').change(function(){
$.ajax({
type: 'GET',
url: 'replace.php',
data: 'old_string='+$('#old_string').val()+'&new_string='+$('#new_string').val(),
success : function(msg){
$('#results').html(msg);
}
})
});
});
</script>
</body>
</html>
replace.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
$valid = true;
if (!empty($_GET['old_string']) and isset($_GET['old_string'])) {
$old_string = $_GET['old_string'];
} else {
$valid = false;
echo 'Old string is Empty . Please Enter value to proceed<br>';
}
if (!empty($_GET['new_string']) and isset($_GET['new_string'])) {
$new_string = $_GET['new_string'];
} else {
$valid = false;
echo 'New string is Empty . Please Enter value to proceed<br>';
}
if ($valid) {
echo 'all input correct<br>';
$myfile = fopen('word.txt', 'r+') or die('Unable to open file!<br>');
if (flock($myfile, LOCK_EX)) {
if(filesize('word.txt')>0){
$text = fread($myfile, filesize('word.txt'));
} else {
$text = '';
}
$count = 0;
$newstring = str_ireplace($old_string, $new_string, $text, $count);
ftruncate($myfile,0);
fwrite($myfile,$newstring,strlen($newstring));
echo "Number of changes made = $count<br>";
flock($myfile, LOCK_UN); // unlock the file
} else {
// flock() returned false, no lock obtained
print 'Could not lock $filename!<br>';
}
fclose($myfile);
}

You're referencing $_GET["Old_string"] in your PHP code but passing it by query string parameter under the Old_String key in this line.
data: 'Old_String='+$('#Old_String').val(),
use case consistently, either Old_string or Old_String in both places.
To pass both values, I'd use a simple json object instead of building a query string manually.
data: { 'Old_String': $('Old_String').val(), 'New_String': $('New_String').val() }

Related

Problem with PHP paths: does not see the directory and files in it

I have forms.
On the forms should be adding files to the Files folder. (It works, but there is a problem) when I only add a file, it is not added, this error appears instead:
Warning:Cannot modify header information -headers already sent by (output started at Q:\home\rat\www\pr5\files.php:1) in Q:\home\rat\www\pr5\files.php on line 10
The file of the file in the Files folder (it does not work: constantly writes that the file exists, even if there is no such file)
The image of the added files (it works too)
Deleting files (it does not work completely, the files are not deleted), this error appears:
Warning: unlink(files/Удалить) [function.unlink]: No such file or directory in Q:\home\rat\www\pr5\files.php on line 61
What is the problem with the paths of me? I can not understand. I did everything on the textbook, but does not work ...
files.php
<?
class Files {
public $files;
function __construct() {
$this->files = scandir("files/");
}
function redirect($url) {
header('Location: '.$url);
}
function counter() {
$filename = "count.txt";
if(file_exists($filename)) {
$h = fopen($filename, "r+");
$Content = fread($h, filesize($filename));
fclose($h);
$text = $Content + 1;
} else {
$text = 1;
}
$h = fopen($filename, "w");
if(fwrite($h, $text)) {
echo "Вы $text-й посетитель сайта =)";
} else {
echo "Что-то не работает на сайте! =(";
echo "Надо напрячь прогера!";
}
fclose($h);
echo "<hr>";
}
function upload() {
if($_FILES['myfile']) {
$uploaddir = 'files/';
$destination = $uploaddir.$_FILES['myfile']['name'];
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $destination)) {
$this->redirect('/pr5');
} else {
return "error <br>";
}
}
}
function search() {
if($_POST['searchname']) {
$folder = "files/";
$file = $searchname;
$file = $folder.$file;
if(file_exists($file)) {
print "Файл существует";
} else {
print "Файл не существует";
}
}
}
function delete() {
if($_POST['delete']) {
unlink("files/".$_POST['delete']);
$this->redirect('/pr5');
}
}
}
?>
index.php
<?
include "files.php";
$f = new Files;
if($_FILES['myfile']) {
$f->upload();
}
if($_POST['delete']) {
$f->delete();
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>pr5</title>
</head>
<body>
<?
$f->counter();
?>
<form enctype = "multipart/form-data" method = "post">
<input type = "hidden" name = "MAX_FILE_SIZE" value = "30000" />
<input type = "file" name = "myfile" /><br>
<input type = "submit" value = "Отправить" />
</form>
<hr>
<form enctype = "multipart/form-data" method = "post">
<input type = "text" name = "searchname" /><br>
<input type = "submit" value = "Найти" />
</form>
<?
if($_POST['searchname']) {
$f->search();
}
?>
<hr>
<?
if(count($f->files) > 2) {
?>
<form method = "POST">
<table>
<tr>
<th>Имя</th>
<th>Удалить</th>
</tr>
<?
foreach($f->files as $s) {
?>
<?
if($s != '.' and $s != '..') {
?>
<tr>
<td> <?
echo $s;
?> </td>
<td>
<button type = "submit" name = "delete" value = "<? echo $s; ?>">Удалить</button>
</td>
</tr>
<?
}
?>
<?
}
?>
</table>
</form>
<?
}
?>
</body>
</html>
Okay, let's check this error more closely.
Warning: Cannot modify header information -headers already sent
PHP cannot modify headers - so the point where it realizes something's amiss is when it calls the header() function - because
output started at Q:\home\rat\www\pr5\files.php:1)
So, in that file, at row 1, there is something output. Something that's not PHP.
What appears to be line 1 is just
<?
which should have been perfectly copacetic (well, actually you'd better take the habit of using long tags, so, "<?php", since that's the established standard).
I am therefore betting something that in that line, unless there is an empty line before it of course, there is something you cannot see. My money is on a BOM: three invisible bytes that tell the operating system that file is coded in UTF8 with specific characteristics.
Usually, your editor should have an option to create files without a Byte Order Mark.

How I change this text from backend page?

I'm trying to make a scrolling text box in a page "front-end page" read from text file "msg.txt"
<div class="scroll-slow">
<?php echo file_get_contents('../msg.txt'); ?>
</div>
I added this code to add textbox and save button in my backend:
<html>
<head>
<title></title>
</head>
<body>
<form action="msg.txt" method="POST">
<input name="field1" type="text" />
<input type="submit" name="submit" value="Save">
</form>
</body>
</html>
<?php
if(isset($_POST['field1'])) {
$data = $_POST['field1'] . "\n";
$ret = file_put_contents('../msg.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file";
}
} else {
die('no post data to process');
}?>
Also I included txt file called "msg.txt" in my root, to make the save button save the text into the file then the scrolling msg box will read the file
My problem is:
The scrolling textbox doesn't read from the file
The save button doesn't save into the file it's just open the file!
What I'm doing wrong?
I'm sorry I know it's a mess, but I'm trying to learn.
You have to make action tag blank to execute the PHP code which is inside if statement
Change
action="msg.txt"
to
action=""
If you are doing coding on PH, you should use php file in action tag, you can not perform any action on txt file.
To append the text every time to existing file use
$txt = "This is text";
$myfile = file_put_contents('text_file.txt', $txt.PHP_EOL , FILE_APPEND | LOCK_EX);
Here you can use jquery and ajax for get activ value of text
$.ajax({
url: "backendFile.php",
type: "post",
data: {
text: $("input[name='field1']").val()
},
success: (e) => {
$(".scroll-slow").html(e)
}
}
Your backendFile.php
<?php
if(isset($_POST['field1'])) {
$data = $_POST['field1'] . "\n";
$ret = file_put_contents('../msg.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
die('There was an error writing this file');
} else {
echo "$ret bytes written to file\n".file_get_contents("../msg.txt");
}
} else {
die('no post data to process');
}
?>
You are submitting the form data to a text file, text files won't be able to handle form data.
You need to send data to php file, in your case just removing the action from form tag would work.

HTML using a PHP script

im new in php programming and ive a problem recently. I have 1 html page with a Search Box and a php script using for grep in a specific file on local host. This is what i want, when a user type string of char and click on enter that send a POST to modify my php var $contents_list, and grep all filename where the string is found.
<?php
$contents_list = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir = new RecursiveDirectoryIterator($path);
$compteur = 0;
foreach(new RecursiveIteratorIterator($dir) as $filename => $file) {
$fd = fopen($file,'r');
if($fd) {
while(!feof($fd)) {
$line = fgets($fd);
foreach($contents_list as $content) {
if(strpos($line, $content) != false) {
$compteur+=1;
echo "\n".$compteur. " : " . $filename. " : \n"."\n=========================================================================\n";
}
}
}
}
fclose($fd);
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
</head>
<body>
<form action="page2.php" method="post">
<INPUT TYPE = "TEXT" VALUE ="search" name="search">
</form>
</body>
And when i go to my html page and type text in searchbar, that redirect me to my php script "localhost/test.php" and i have 500 internal error.
So I want:
To see result of the php script on the same html page, but i dont know how to do that :/
And if the previous filename return was same like previous result, dont print it, to avoid double result.
I hope its clear and youve understand what i want to do, so thanks for the people who want to help me <3
My recommendations:
Combine the code into the single index.php file for simplicity
Separate logic for search and output to achieve clean separation of duties
Add helper text such as nothing found or enter text
index.php content:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<form action="index.php" method="post">
<input type="text" placeholder="search" name="search">
</form>
<?php
// Check if the form was submitted.
if (isset($_POST['search']) && (strlen($_POST['search'])) > 0) {
$search_line = $_POST['search'];
$path = "/my/directory/used/for/grep";
$dir_content = new RecursiveDirectoryIterator($path);
// Array to store results.
$results = [];
// Iterate through directories and files.
foreach (new RecursiveIteratorIterator($dir_content) as $filename => $file) {
$fd = fopen($file, 'r');
if ($fd) {
while (!feof($fd)) {
$file_line = fgets($fd);
if (strpos($file_line, $search_line) !== FALSE) {
$results[] = $filename;
}
}
fclose($fd);
}
}
// Output result.
echo "<pre>";
if ($results) {
foreach ($results as $index => $result) {
echo ($index + 1) . " :: $result\n";
}
}
else {
echo "Nothing found!";
}
echo "</pre>";
}
else {
// When nothing to search.
echo "<pre>Enter something to search.</pre>";
}
?>
</body>
</html>

Ajax call not being returned

The issue is that either the PHP file isn't sending the data back or the JS file isn't catching the data.
The exact issue is that the data isn't display on the index.php page inside the <div>.
I included code in the getDetails.php file to record what it was doing. It allows me to see that the query is running and data is being returned.
I have used similar code to this in the past without any problems. The only difference is that the previous code was working with MySQL. This code is dealing with an Access database. I don't know if I need to do anything special with the json_encode to deal with Access data.
I used an alert() at the beginning of java.js to make sure that the java code is being called. It is. An alert right after the details = result command never gets called.
INDEX.PHP:
<!doctype html>
<html>
<head>
<meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script src="java.js" type="text/javascript"></script>
</head>
<body>
<div id="reportDetails" class="reportDetails" align=center></div>
</body>
<html>
JAVA.JS:
jQuery(document).ready(function () {
var ra='7100913063';
$.ajax({
type: 'POST',
url: 'getDetails.php',
data: 'value=' + ra,
dataType: 'json',
cache: false,
success: function(result) {
details = result;
$("#reportDetails").text("");
for (var i = 0; i < details.length; i++) {
$("#reportDetails").append("<tr class='bottom'><td width=200 align=center class='bottom'>" + details[i][0] + "</td><td width=200 align=center class='bottom'>" + details[i][1] + "</td><td width=200 align=center class='bottom'> " + details[i][2] +"</td></td><td width=200 align=center class='bottom'> " + details[i][3] +"</td></td></tr>");
}
$("#reportDetails").append("</table>");
},
});
});
getDetails.php
<?php
include("../../scripts/adodb/adodb.inc.php");
$myFile = "testFile.txt";
$fh = fopen($myFile, 'w') or die("can't open file");
$ra = $_POST['value'];
set_time_limit(0);
date_default_timezone_set('America/Chicago');
$counter = 0;
$connect = odbc_connect("Driver={Microsoft Access Driver (*.mdb)};Dbq=//server/directory/database.mdb", '', '');
$query = "SELECT distinct ra, MIN(received) as startDate, MAX(completion) AS stopDate, MAX(status) as stat FROM cont WHERE ra = '" . $ra . "' GROUP BY ra";
$result = odbc_exec($connect,$query);
while(odbc_fetch_row($result)){
$radetails[0] = odbc_result($result,"ra");
fwrite($fh, $radetails[0]);
$radetails[1] = odbc_result($result,"startDate");
fwrite($fh, $radetails[1]);
$radetails[2] = odbc_result($result,"stopDate");
fwrite($fh, $radetails[2]);
$radetails[3] = odbc_result($result,"stat");
fwrite($fh, $radetails[3]);
}
fclose($fh);
echo json_encode($radetails);
?>
I had the line "echo <br/>" in my getDetails.php. Removed that line and it works now.

reading Json from PHP with javaScript

My PHP code is:
<?php
class Sample{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) ){
echo "Starting to read ";
$req = $_GET[ 'request' ];
$result = json_decode($req);
if( $result->request == "Sample" ){
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}else{
echo "Not Supported";
}
}
?>
Is there anything wrong
I want to send a JSON to this php and read the JSON that it returns using java script , I can't figure out how to use JavaScript in this , because php creates an html file how Can I use $_getJson and functions like that to make this happen ?!
I tried using
$.getJSON('server.php',request={'request': 'Sample'}) )
but php can't read this input or it's wrong somehow
thank you
try this out. It uses jQuery to load contents output from a server URL
<!DOCTYPE html>
<html>
<head>
<title>AJAX Load Test</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(event) {
$('#responce').load('php_code.php?request={"request":"Sample"}');
});
});
</script>
</head>
<body>
<p>Click on the button to load results from php_code.php:</p>
<div id="responce" style="background-color:yellow;padding:5px 15px">
Waiting...
</div>
<input type="button" id="button" value="Load Data" />
</body>
</html>
Code below is an amended version of your code. Store in a file called php_code.php, store in the same directory as the above and test away.
<?php
class Sample
{
public $name = "N3mo";
public $answer = "";
}
if( isset( $_GET['request'] ) )
{
echo "Starting to read ";
$req = $_GET['request'];
$result = json_decode($req);
if( isset($result->request) && $result->request == "Sample" )
{
$ans = new Sample();
$ans->answer = " It Is Working !!! ";
echo json_encode($ans);
}
else
{
echo "Not Supported";
}
}
Let me know how you get on
It would be as simple as:
$.getJSON('/path/to/php/server.php',
{request: JSON.stringify({request: 'Sample'})}).done(function (data) {
console.log(data);
});
You can either include this in <script> tags or in an included JavaScript file to use whenever you need it.
You're on the right path; PHP outputs a result and you use AJAX to get that result. When you view it in a browser, it'll naturally show you an HTML result due to your browser's interpretation of the JSON data.
To get that data into JavaScript, use jQuery.get():
$.get('output.html', function(data) {
var importedData = data;
console.log('Shiny daya: ' + importedData);
});

Categories