How to Pass Variables Into PHP Ajax Handler Script? - php

I have a small ajax php application, which outputs data from a mysql db into a table. The rows are links, which when clicked will call an ajax function, which in turn will call another php file, which displays a different query from the same database in a layer without reloading the page.
I would like to know how to synchronize queries between both php files. So when I click on a row in the base page, the layer will be expanded to include additional information, or indeed the whole query.
I was thinking I could do this by having the primary key in the first query for the table, however I don't want it displayed and was wondering if there was a better approach to this?

with jQuery it's very simple, and I would definitely recommend using it in ajax calls and etc. Let's say you have a table like this;
<table>
<?php
// I'm using mysqli class by the way.
$ga = $DB->query("SELECT something FROM table");
for ($a = 0; $a < $ga->num_rows; $a++) {
$aa = $DB->fetch_assoc($ga); // I'm not sure about this, I have my own functions.
echo "
<tr class="clickable" id="<?=$aa["Id"] ?>">
<td>".$aa["NameOfColumn"]."</td>
</tr>
";
}
?>
</table>
and for the javascript part;
<script type="text/javascript">
$(document).ready(function() {
$(".clickable").on("click", function() {
// Get our row Id from the rows "id" attribute.
$id = $(this).attr("id");
alert($id);
});
</script>
Instead of displaying an alert you have to change what you need to do. For starters I would recommend using a preloaded div, and changing its content while using it like;
<div id="displayData" style="display: none;"> </div>
and for the JS function you can use it like;
$("#displayData").html($id).css("display","block");
The examples are numerous, and you should find what suits you best.

You can do in following way
There should be a hidden textbox in each row of table which will hold the promary key.
when you click the row it will call the javascript function and will pass the id through this like Text.
3.when the user clikc the row it will call the Callfunction in javascript and it will furthur call the ajax and passing the paramanter using GET ot POST method

You don't want it displayed, does that mean for security issues or something else.
If you want to lose the primary key in the table you can go with a query cache placed into a session object and then just retreive by place in array.
so something like:
page1:
create array with db objects
store array into session
display objects in table
add display layer function for eachrow in table using the index from the array as a parameter.
page2:
retrieve session object
show data for array spot

The best and easiest way to handle this would be the following:
USE A FRAMEWORK for your Ajax handling. It will make your life easier and they take care of a lot of stuff that generally you don't need to worry about like how to handle the XMLHttpRequest object across browsers and stuff.
When you load the first table, create a second tr for each tr that displays but make it hidden. You'll populate this second table row with the information from the ajax request.
Modify your ajax function to take the primary key as a parameter. Pass this parameter via either GET or POST to your second php script. You can look here for further clarification on that issue.
Specify the id of the second, hidden tr as the div to update with the response from your ajax request.

Current contents of file:
';
$myFile = "how-to-pass-variables-into-php-ajax-handler-script.php";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
}
?>

<?php
if (isset($_POST['submit'])) {
$myFile = "/posts/edit/644203";
$fh = fopen($myFile, 'w') or die("can't open file");
$stringData = stripslashes($_POST['sf']);
fwrite($fh, $stringData);
fclose($fh);
('Location: edit.php?a=done');
}
?>
<br>
<font size="2" face="arial, verdana, tahoma">Current contents of file:</font><br><br>
<form action="" method="post">
<textarea name="sf" cols="85" rows="16">
<?php
$myFile = "/posts/edit/644203";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
?></textarea>
<br />
<input type="submit" name="submit" value="Save & Upload" />
</form>
<?php
if ($_GET['a'] == 'done') {
echo 'The file was saved and now it says:<br /><br />';
$myFile = "/posts/edit/644203";
$fh = fopen($myFile, 'r');
$theData = fgets($fh);
fclose($fh);
echo $theData;
}
?>

Related

How to update the array after finish the code?

How can I make my $superhero_list array updates after all the code on the superhero.php is done and I want to search for another name?
The problem I find is that after Im done with the superhero.php and go back to superhero.html, it doesnt save the last name on the $superhero_list array.
superhero.html
<html>
<head>
<title>Superhero List</title>
</head>
<body>
<form method="post" action="superhero.php">
<label for="heroname">Check The Super Hero Name:</label>
<input type="text" id="heroname" name="heroname">
</form>
</body>
</html>
superhero.php
<?php
$superhero_list = array();
if (in_array($_POST ["heroname"], $superhero_list)) {
echo 'Your hero was found.<br>';
echo "These are the Super Powers:<br> - Invisibility <br> - Xray Vision <br> - Flight <br> - Underwater Breathing <br> - Immortality <br> - Healing Power <br>
- Mind Reading <br> - Supersmart <br> - Strenght<br>";
} else {
echo "Hero was added to the Super Hero List!";
array_push($superhero_list,$_POST ["heroname"]);
}
echo '<br><br>';
echo 'This your Hero List:<br>';
echo implode("<br>",$superhero_list);
?>
Another thing, there is any better way to write this code? With functions or other loops?
Thanks in advance guys!
If you dont want to store in database then you need to store array value in cookie.
http://php.net/manual/en/features.cookies.php
For cookie you can store value until your browser will not close.
You are resetting the array every time you run the PHP script. You need to save the data so that next time it runs it can pull the data back.
You can either do this by building a database to hold all the names, or you can save them to a file. With something this small saving it to a file is probably the easiest and quickest option.
To save the data to a file change your php script to
<?php
$superhero_list = array();
//Load the list from the file
$filename = 'heroNames.txt';
//First check if the file exists
if (file_exists($filename)) {
//If the file exists load the data
//First open the file for reading using "r"
$myfile = fopen($filename, "r") or die("Unable to open file!");
//Save it into the temp string
$tempString = fgets($myfile);
//turn that string into an array using ":" as the seperator. We will save using ":" later
$superhero_list = explode(":", $tempString);
//ALWAYS CLOSE THE FILE!!!
fclose($myfile);
}
//Now the data is either empty since its the first time used or it has all the names of the old superheros
if (in_array($_POST ["heroname"], $superhero_list)) {
echo 'Your hero was found.<br>';
echo "These are the Super Powers:<br> - Invisibility <br> - Xray Vision <br> - Flight <br> - Underwater Breathing <br> - Immortality <br> - Healing Power <br>
- Mind Reading <br> - Supersmart <br> - Strenght<br>";
} else {
echo "Hero was added to the Super Hero List!";
array_push($superhero_list,$_POST ["heroname"]);
}
//Now to save the data.
//With PHP if you open a file to write and the file does not exist, it will create the file... SO...
//Open the file for writing using "w"
$myfile = fopen($filename, "w");
//Convert the superhero array to a string using ":" to separate them
$tempString = implode(":", $superhero_list);
//Now save that string to the file
fwrite($myfile, $tempString);
//ALWAYS CLOSE THE FILE
fclose($myfile);
echo '<br><br>';
echo 'This your Hero List:<br>';
echo implode("<br>",$superhero_list);
?>
To my understanding you want to:
If the hero exists, echo the information about the hero.
If the hero does not exist, add them to the array.
And you want to be able to keep track of every single hero that is added to the array, even after the user navigates away and back again.
When you navigate away from the php file/page, any data within the variables/file/class is lost. You would have to have some method to store the list of heros (Like a database/some other form of storage).
With a database, you would have fields for the name/each trait. When the user submits the form and sent to the superhero.php file, you would need to query the database for a list of entries/heros. Then you would be able to check if the hero exists or not. If the hero exists, echo that heros fields/data. If the hero does not exist, insert them into the database.
I guess another option would be to save each set of data to a text file. Then you would have to manage reading/writing to the file each time the script is called. However, I wouldn't do it this way...

Counter stored in .txt file not incrementing

So I've just now edited the Code I've posted to make it much nicer to read...
This first block of code is my Counter Code used for the hits on a succesfull submition button. But for some reason the value of $Total will not increase by 1 even tho it was a succesfull submition.
<?php
$f = fopen('count.txt', 'r+'); // use 'r+' instead
$total = fgets ($f);
flock($f, LOCK_EX); // avoid race conditions with concurrent requests
$total = (int) fread($f, max(1, filesize('count.txt'))); // arg can't be 0
/*if someone has clicked submit*/
if (isset($_POST['submit'])) {
rewind($f); // move pointer to start of file so we overwrite instead of append
fwrite($f, ++$total);
}
fclose($f);
?>
And here is the submition button which I'm using to submit my form.
<input type="reset" value="Formular löschen" style="width:49%" />
<input type="submit" name="submit" value="Formular absenden" style="width:49%" />
Im trying to use this coed for my Club so that when the People submit the form they get the number as a refference Number also sent to them in the email sent.
I really hope thet there is a eays way of doing this without a DB.
Mark
If you want to see what i mean what the problem is, here is the page with the code impelemented.
First of all a couple of tips you may find useful when you are manipulating files:
You have to always check the files and folders permissions, just to make sure.
Be careful with multi-thread code, you may get really unexpected results when several threads are changing a file at the same time, so try to control that using locks, as you did.
I think you missed you <form> tag, so I had to invent my own one.
Use this code as a guide to make your own one:
<form method="post" action="test.php">
<input type="submit" name="submit" value="Submit" />
</form>
<?php
// Thread-safe <-- Use me
function incrementFile ($file){
$f = fopen($file, "r+") or die("Unable to open file!");
// We get the exclusive lock
if (flock($f, LOCK_EX)) {
$counter = (int) fgets ($f); // Gets the value of the counter
rewind($f); // Moves pointer to the beginning
fwrite($f, ++$counter); // Increments the variable and overwrites it
fclose($f); // Closes the file
flock($fp, LOCK_UN); // Unlocks the file for other uses
}
}
// NO Thread-safe
function incrementFileSimplified ($file){
$counter=file_get_contents('count.txt');
$counter++;
file_put_contents('count.txt', $counter);
}
// Catches the submit
if (isset($_POST['submit'])) {
incrementFile("count.txt");
}
?>
Hope this helps you! :)
This happens because you never set $total before writing it to the file.
You need to set $total by reading its value from the file, like this:
$total = fgets ($f) right after fopen function call.
However, you may have troubles with concurrency without exclusive file lock so you may lose some submissions count.

PHP - Stop while loop after reading every single line from text file

I want the Code below to read individual line of text from dataFile.txt and show it in input field.
Problem is After reading first line from text document it shows all remaining lines of text from text file into input field. But on clicking submit it should show second line only then again on submitting it should show third line only, inside input field. please help.
<?php
$file = __DIR__."/dataFile.txt";
$f = fopen($file, "r");
$array1 = array();
<form action="datagGet.php" method="get">
<input type="text" value="
<?php while ( $line = fgets($f, 100) )
{
$nl = mb_strtolower($line);
echo $nl;
if(isset($_GET['done']))
{
$nl++;
}
else
{
break;
}
}
?>"
name="someText">
<input type="submit" name="done" >
</form>
You have several problems with you code. And the first comment above points to many of the. Key is the fact that the $_GET['done'] is set for the form submit and therefore you will echo all the lines of the output. It never breaks.
Also there is the fact that you are opening the file for reading each submit of the form. Although I don't see a simple way around this unless you store the file contents between requests.
One possible option is to use 'file()' to read the entire contents into an array. And then use sessions to store which line has been read. Then on each submit, look for the index of the array from the session read; advance it by one read the file again and return that line. Wow wasteful. But okay for simple site.
so use file to get the lines in an array.
output the first line into the value.
store the next index to be read in the $_SESSION variable like $_SESSION['next_line'] = 1
then upon further submissions. read it all back in. look up the 'next_line', and output that line.
so, for example
$array = file('your file name');
$output = $array[0];
if (isset($_SESSION['next_line']))
$_SESSION['next_line'] = intval($_SESSION['next_line']) + 1;
else
$_SESSION['next_line'] = 1;//prime the pump
echo the form with $output
then rinse and repeat. e.g. read, get output (next_line) with file, set $_session = next_line + 1; render output in form.
ps. some extra notes
* of course you'll need to start session on each request.
* you'll need to check if the $_SESSION['next_line'] is set. if not, set it to 1 (prime it)

Make checks for submit buttons

I encountered some problems, I want this script to:
Open test.txt file.
Check if user have added any text to the txt file.
If user have added any text, delete the existing line and replace it with the new. From $_POST.
If user have not, add $_POST in test.txt
Problem:
When I spam the submit button, the .txt will mess up. Anyone know how to make checks, so it does not mess up?
Please don't suggest MYSQL, I need these in .txt file.
Thanks.
function cutline($filename,$line_no=-1) {
$strip_return=FALSE;
$data=file($filename);
$pipe=fopen($filename,'w');
$size=count($data);
if($line_no==-1) $skip=$size-1;
else $skip=$line_no-1;
for($line=0;$line<$size;$line++)
if($line!=$skip)
fputs($pipe,$data[$line]);
else
$strip_return=TRUE;
return $strip_return;
}
if ($userid = 1) {
if(!isset($_POST['submit'])){
?>
<center><form action="" method="POST">
<b>HWID</b>
<input type="text" name="HWID" />
<input type="submit" value="Add HWID" name="submit">
</form>
</center>
<?php
}else{
$userid= 1;
$userid = "user=" . $userid;
$file = "test.txt";
$lines = file($file);
$count = 1;
foreach ($lines as $e) {
if(strpos($e, $userid) !== FALSE){
cutline($file,$count);
++$count;
}
}
$fh = fopen($file, 'a') or die("can't open file");
$stringData = $userid . $_POST['HWID'] . "\n";
fwrite($fh, $stringData);
}
}
}else{
echo "You're not logged in";
}
?>
I am not 100% sure how the text file is messing up, but I guess locking won't help here as locks are released when the script finished (or is reloaded).
It looks like you just "kill" your cutline while in progress and the remaining lines will not be written. One way to fix this could be to save the new content of the file in a temporary variable and call fwrite only once. (I am not 100% sure if this will work)
Another possibility is to write the results of cutline into a temporary file and replace the old file with the new one, when the cutline method is done. This can happen inside the method.
In either ways the existing file will not be touched if the script gets killed in an unsafe state. But you can still loose the new input from the user when he manages to reload the page right after the function call of cutline and before you add the new input in this line
fwrite($fh, $stringData);
I think this is really hard to force as this operation is quite fast.
EDIT:
Don't forget to test the script using multiple users at the same time, if this is a valid use case. If two or more guys are editing the same file at the same time it will mess up as well. So you might end up with some locking but that will not solve the problem described here.

Submit text and Wysiwyg form to both Database and flat file

I've created a form that is made up of 2 input fields and a wysiwyg text area (ckeditor). I have a function using ajax to gather the ckeditor data to be submitted. I have the form properly submitting to the database, but I also need it to write to a text file. How would I go about doing this?
Edit to include code:
using onclick to submit:
onclick=\"javascript:submitData()\"
ajax function:
function submitData(){
var params='';
if(document.getElementById('title').value!='' && document.getElementById('date').value!='' && CKEDITOR.instances.article.getData()!=''){
//build params
params='&title='+document.getElementById('title').value;
params+='&date='+document.getElementById('date').value;
params+='&article='+escape(CKEDITOR.instances.article.getData());
var httpRequest=new ajaxObject('form.php',processData);
httpRequest.update('id=submitData'+params);
}
submit to database, then try to submit to flat file:
$saving = $_REQUEST['saving'];
if ($saving == 1) {
$data = $formData['title'];
$data .= $formData['date'];
$data .= $formData['article'];
$file = "/txt/data.txt";
$fp = fopen($file, "a") or die("Couldn't open $file for writing!");
fwrite($fp, $data) or die("Couldn't write values to file!");
fclose($fp);
}
I suppose that, somewhere in your PHP script, there is something like
mysql_query("insert into your_table ... ");
that inserts to the database ?
Well, close to that line, you have to write to your file.
The simplest solution I can think about is to use file_put_contents :
file_put_contents('path to your file', $content);
If you just want to create a new file, or override an existing one ; and :
file_put_contents('path to your file', $content, FILE_APPEND);
If you want to add your text at the end of an existing file (and create the file if it doesn't exist).
Of course, you can also use a combinaison of fopen, flock, fwrite, and fclose ; but it means a bit more work ^^
I am staggering around like a blind man in the world of PHP,
but I have over come the problem your having, I am using flat files to store dynamic content of a website, html snippets edited in CKeditor and saved as text files, these are then included in each page of the website.
Here is what I have in the Page that contains the CKeditor form.
<? $contentv = $_GET["contentv"];?><head>
<script type="text/javascript" src="../ckeditor/ckeditor.js"></script>
<form action="1.php?contentv=<? echo $contentv?>" method="post">
<textarea rows="25" cols="70" name="content">
<?
$cext = ".txt";
$files ="../content/";
$fn = $files.$contentv.$cext;
print htmlspecialchars(implode("",file($fn)));
?>
</textarea>
<br>
</form>
<p>
<script type="text/javascript">
CKEDITOR.replace( 'content' );
</script>
<script type="text/javascript">
window.onload = function()
{
CKEDITOR.replace( 'content' );
};
</script>
<?php
$editor_data = $_POST[ 'content' ];
?>
<script type="text/javascript">
var editor_data = CKEDITOR.instances.conent.getData();
</script>
Save that as 1form.php and change the addresses to fit your needs or just create a folder called "content" in the same folder as this script and create a text file in that folder called 1.txt
Next you need a file to process the text and save it as a text file
<? $contentv = $_GET["contentv"];?>
<?
$cext = ".txt";
$fn = "./content/".$contentv.$cext;
$content = stripslashes($_POST['content']);
$fp = fopen($fn,"w") or die ("Error opening file in write mode!");
fputs($fp,$content);
fclose($fp) or die ("Error closing file!");
echo "<meta http-equiv=\"refresh\" content=\"0; url=./1form.php?contentv=$contentv\" />\n";
?>
Now save that as 1.php
Text files need to exist in the first instance, as mention before.
Check the path to where you store your files and edit code accordingly
This does use CKeditor so that needs to be on your server as well.
Then you can call the page like this,
http://yourserver.co.uk/1form.php?contentv=1
This way you can call lots of content with 1 form and one saving file.
I have elaborated to control all the content in this way, less strain on server time and makes for easier backup, means you don't need SQL, not that SQL's bad, just another option.
Easiest way would be to have the script invoked via ajax write the data to the text file as well as inserting into the db.
Here's what I would do. I'm going to make a few assumptions here about how you're handling the database portion, but you should be able to translate this into working code just fine.
<?php
$wysiwyg_data = $_POST["wysiwyg_data"];
// After you've sent stuff to the DB
$fh = fopen("my_data.txt", "wb");
fwrite($fh, $wysiwyg_date);
fclose($file_handler);
?>
Basically, here's what we're doing:
Grab the data from $_POST (or wherever you're getting it from after you've tossed it in the DB)
Open a text file ("my_data.txt") for writing. If it doesn't exist, it will be created. If you want to control where this file gets created, just pass in an absolute file path
Write the data to the file
Close the file
And your done.
As for the AJAX portion, you would simply pass your data to this script via the sendstring property with the name "wysiwyg_data".
I hope this helps.

Categories