Can't manage to make $_POST to work - php

I have three files in a server (000webhost.com):
"Test01.php" (main file),
"database.txt" (saved data, which will be changed by users),
"save_txt.php" (the file which gets data from the main file and writes it to the "database".
"Test01.php" is supposed to show a simple list, with a few names in a table (single column, multiple lines).
Those names will be retrieved from a file named "database.txt".
Everytime some user click on a name, that name will be sent to the bottom of the list, and the list will be saved to "database.txt", so the next user will see the changes made by the last one.
A function in "Test01.php" sends the changed list to a second file ("save_txt.php"), which is supposed to write it back to "database.txt".
I can manage to retrieve the data from the txt file, and the clicking events as well, but I still can't find a way to save the data into the txt file...
In fact, I don't understand why my variable isn't seen from inside the second php file ("save_txt.php").
To retrieve data I use:
<?php
$Data_from_File = file("database.txt",FILE_IGNORE_NEW_LINES);
?>
And the script:
var sSaved_Data = <?php echo json_encode($Data_from_File); ?>;
The listing stuff works fine.
I get many names from the txt file and store it into an array. Then I display it in the table. No problem from reading the file.
I send data to "save_txt.php" by doing this:
var sNew_Data = " is blue";
.
.
.
xmlhttp.send("php_Data_to_Save=" + sNew_Data);
But, could anyone tell me why the simple code below doesn't work?
https://rbonphp.000webhostapp.com/Test01.php
"save_txt.php" is just like this:
<?php
$var1 = $_POST["php_Data_to_Save"];
echo $var1;
?>
In time: in this example I just want to see " is blue" echoed in the screen (no matter where). I just want to understand how to get the data back to "save_txt.php".
Later I will try to write $var1 to "database.txt".
But first things first...
:-(
As I said, this "Test01.php" is just a test. The list and all the clicking events I wrote in another file. That part works just fine.
* Edited *
Let's try to put it all in a few lines.
The main file (Test01.php) does:
var sNew_Data = " is blue";
// there's more code for the XMLHttpRequest function
xmlhttp.send("php_Data_to_Save=" + sNew_Data);
The secondary file (save_txt.php) does:
<?php
$var1 = $_POST["php_Data_to_Save"];
echo $var1;
?> // and this is ALL its code, just these 4 lines.
That line echo $var1; should simply show " is blue" on the screen.
Right???
Extra info: Test01.php is a step prior to make the following page to work:
https://rbonphp.000webhostapp.com/DailyTasks1.php

Your code is working.
Calling Send_Data_to_Server() returns "The sky is blue" which is what you wanted, as the sent data is var sNew_Data = sSaved_Data + " is blue"; and it is correctly echoed by save_txt.php
Note: your commented jquery ajax call is wrong however, that's not how you define the sent data, check the first example at http://api.jquery.com/jquery.ajax/
You'd write this:
$.ajax({
url: 'save_txt.php',
data: { php_Data_to_Save : sNew_Data },
type: 'POST'
});

first, you didnt call Send_Data_to_Server() anywhere, you've just declared it.
secont, you just send the request to server, but don't store the answer anywhere.

Related

How can i call php Require from SQL string

i am seeking help with the following
So im using PHP 7.1 and MSSQL 2017, and IIS
i have some tables that are to large to hard-code or create a text out of them to input in a SQL table , so i created a separate file with a query to display the table.
but when i try to add to "<?php require'table1.php';?>"
as a Text or string in another Table, and is set in the browser it gets comment out by the browser
Is there any way to execute the require with out being comment it out?
for now i have just create a link for the tables to open in a new tab, but i really what then to open inside the original document.
So file 1 is the main query where it displays the information.
File 2 runs another query for the Table, i would like to set the <?php require'table1.php';?> on the main query so it displayed File 2 contents in File 1, rather than opening a new tab.
Main table would be like this
Title - ID - Message
Something - RK1 - Something Important
Something 2 - RK2 - <?php require'table1.php';?>
Something 3 - RK3 - Something Kinda Importan
i apologize if its confusing, let me know.
Any help is appreciated, tyvm.
It's never a good idea to store code in the database because if you're database gets compromised whoever managed to get access to your DB will also have access to running php code on your server and can cause even more damage.
I think what you're trying to achieve could be done within your php files alone.
Why don't you just require table1.php file in your main file?
Edit:
In your main php file you can can create a part that your ajax script can communicate with that allows you to retrieve the necessary table contents like so:
<?php
if(isset($_POST['tableChange'])) {
$tableToDisplay = $_POST['tableChange'];
switch($tableToDisplay) {
case 'A':
$realTableName = 'TableA';
$isValidTable = true;
break;
case 'B':
$realTableName = 'TableB';
$isValidTable = true;
break;
default:
$isValidTable = false;
break;
}
if($isValidTable) {
$tableContents = mysql_fetch_array(mysql_query("SELECT * FROM `".$realTableName."`"));
//Then you can retrieve what ever rows you want from the current table with the array you create with mysql_fetch_array
$row1 = $tableContents['name_of_row1'];
$row2 = $tableContents['name_of_row2'];
echo 'row1: '.$row1.' row2: '.$row2;
}
}
?>
Then you can make an ajax POST request to the main php file -- that passes a piece of data named "tableChange" that holds a string representing the table's identifier. In this case it would have to be set to either "A" or "B" in order for it to be accepted.
Here's an example with jQuery:
$.ajax({
url: 'main.php',
type: 'POST',
data: {tableChange: 'B'},
dataType: 'html',
complete: function(dataReturned) {
//Now print the contents of the dataReturned variable to the screen how ever you want
}
});

Showing progress bar while fetching data [duplicate]

I have this while loop, that basically loops through a lot of records in a database, and inserts the data in another:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
}
(The script has been shortened for easy reading - the correct one has a much longer array)
I would like to do this more graphical, and show a progress bar on how far it has went, instead of just seeing a page loading for a few minutes (there are ~20.000 rows in this one - I have tables with much more data)
I get that you could get the total number from the old database, and I could also easily put the current number into a variable like this:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
$i = 0;
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
$i++;
}
But now I need to actually fetch $i and display it - or something like it.
How is this "easily" done?
The code for the progress bar can either be in the same document as the while loop, or in another if easier.
You can do a "master" file that does an ajax to this first file to run a single query. You could get all the entry id's in this master file, and then pass it as a parameter to the second file that does a single query. Store these ids in a javascript array.
Create a function that does this, and when the first ajax is done, move to the second element of the id array, and do another ajax with a second parameter. That's how magento imports are done by the way :)
If you need further explanations, let me know, I tried my best to explain, but may have not been perfectly clear.
// you generate this javascript array using php.
// let's say you have all the ids that have to be processed in $Ids php array.
Ids = [<?php echo implode(',', $Ids); ?>];
function doAjax(i) {
$.ajax({ // using jquery for simplicity
'url': "ajax.php?id=" + Ids[i],
}).done(function(){
if ( i >= 0 ) {
// at the point you know you're at ((Ids.length-i)/(Ids.length) * 100) percent of the script
// so you can do something like this:
// $('.progressbar').css('width', ((Ids.length-i)/(Ids.length) * 100) + '%');
doAjax(i-1);
}
});
}
doAjax(Ids.length); // starting from the last entry
So, just to explain what this does. It starts by declaring a global javascript array that has all the ids that will need to be changed.
Then I declare a recursive ajax function, this way we can make sure that only one ajax runs at any single time (so the server doesn't blow up), and we can have a fairly accurate progress. This ajax function does the following:
Sends a request to ajax.php?id=xxx - where xxx is one of the ids in the javascript array.
In the file, we get the id ($_GET['id']), you take it from the old database, and insert it in the new one. This is only for one entry.
when the ajax is done, it goes to the done() function. Since we start the doAjax() function with the last element, we do the next iteration doAjax(i-1). Since we're going backwards in the array, we check if the key is positive. If it's not, the script will stop.
That's about it.
You can't. The php is first interpreted by the server and then send to the user as HTML-Code.
The only possibility would be creating a html-page and call the php-script with AJAX.

Look for in Mysql table and pass information from the javascript

My web-server has PHP and MySQL.
One table of database has information about user.
User that uses my site wants to receive some information.
So he or she presses mouse button and happen click event for this button and submit event for a form.
I use framework jQuery and in my javascript (method .submit())
I use AJAX for retrieving necessary information.
First, I want to know exist so user in the table or not.
I receive this information using ajax and php file – first.php.
If information about user hasn’t in the table I report about this in the script.
If information about user hasn’t in the table but like user(s) exist(s) in it I inform of this situation.
If information about user has in the table I call command: window.location.href = “second.php?param=2&user=userid” in my script and I have to look for necessary information again in the table and show it in the web-page.
So my next question is: How can I refrain from repeating a query on the same table?
I must show about 10 account’s records in my web page.
I want to know. How can I pass information (10 account’s records) from my script into second.php file?
I am afraid to do the second command $.ajax() in the script. I think there is no need for it.
What you are doing now is pretty much the standard. If you dont want to use this method then I suggest that you look into session.
On your first page you will need to include the line:
<?php
session_start();
then your normal code.
Once you have read the information from the database then place the values into session variables;
$_SESSSION['var1'] = $result['id']; //--- continue for all the values you want to save
On the second page you will need to do the reverse
<?php
session_start();
$id = $_SESSION['var1'];
You could write the query result into a semi-static1 JavaScript snippet:
<?php
// do your query
$result = ...;
echo '<script type="text/javascript">'
. 'var accountData = ' . parseForJavaScript($result) . ';'
. '</script>';
// do your other stuff
Then you can write code that depends on that (not necessarily global) variable accountData:
// JavaScript:
doStuff(accountData);
because it will essentially be expanded to (if parseForJavaScript returns a json representation):
<script type="text/javascript">
var accountData = {users: {
0 : { "name" : "John" },
1 : { "name" : "Jack" },
2 : { "name" : "James" }
}};
</script>
Of course the JSON object would look differently depending on your actual data structure.
Or you can skip that variable and inject the data directly as a function parameter:
<?php
// do your query
$result = ...;
echo '<script type="text/javascript">'
. 'doStuff(' . parseForJavaScript($result) . ');'
. '</script>';
// do your other stuff
1 semi-static because it is actually dynamically generated by php but looks static when looking at the final HTML.

Progress bar while running while loop

I have this while loop, that basically loops through a lot of records in a database, and inserts the data in another:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
}
(The script has been shortened for easy reading - the correct one has a much longer array)
I would like to do this more graphical, and show a progress bar on how far it has went, instead of just seeing a page loading for a few minutes (there are ~20.000 rows in this one - I have tables with much more data)
I get that you could get the total number from the old database, and I could also easily put the current number into a variable like this:
$q = $con1->query($users1) or die(print_r($con2->errorInfo(),1));
$i = 0;
while($row = $q->fetch(PDO::FETCH_ASSOC)){
$q = $con2->prepare($users2);
$q->execute(array($row['id'], $row['username'])) or die(print_r($con2-errorInfo(),1));
$i++;
}
But now I need to actually fetch $i and display it - or something like it.
How is this "easily" done?
The code for the progress bar can either be in the same document as the while loop, or in another if easier.
You can do a "master" file that does an ajax to this first file to run a single query. You could get all the entry id's in this master file, and then pass it as a parameter to the second file that does a single query. Store these ids in a javascript array.
Create a function that does this, and when the first ajax is done, move to the second element of the id array, and do another ajax with a second parameter. That's how magento imports are done by the way :)
If you need further explanations, let me know, I tried my best to explain, but may have not been perfectly clear.
// you generate this javascript array using php.
// let's say you have all the ids that have to be processed in $Ids php array.
Ids = [<?php echo implode(',', $Ids); ?>];
function doAjax(i) {
$.ajax({ // using jquery for simplicity
'url': "ajax.php?id=" + Ids[i],
}).done(function(){
if ( i >= 0 ) {
// at the point you know you're at ((Ids.length-i)/(Ids.length) * 100) percent of the script
// so you can do something like this:
// $('.progressbar').css('width', ((Ids.length-i)/(Ids.length) * 100) + '%');
doAjax(i-1);
}
});
}
doAjax(Ids.length); // starting from the last entry
So, just to explain what this does. It starts by declaring a global javascript array that has all the ids that will need to be changed.
Then I declare a recursive ajax function, this way we can make sure that only one ajax runs at any single time (so the server doesn't blow up), and we can have a fairly accurate progress. This ajax function does the following:
Sends a request to ajax.php?id=xxx - where xxx is one of the ids in the javascript array.
In the file, we get the id ($_GET['id']), you take it from the old database, and insert it in the new one. This is only for one entry.
when the ajax is done, it goes to the done() function. Since we start the doAjax() function with the last element, we do the next iteration doAjax(i-1). Since we're going backwards in the array, we check if the key is positive. If it's not, the script will stop.
That's about it.
You can't. The php is first interpreted by the server and then send to the user as HTML-Code.
The only possibility would be creating a html-page and call the php-script with AJAX.

PHP with JavaScript to call database

I made some javascript code to view the text inside input text. When I click on the submit with this code:
alert("The field contains the text: " + frm.find.value)
This works, so I want use this part from javascript in php "frm.find.value"
for example: I'll write the wrong code as i used it:
$j='<script>+ frm.find.value<script/>';
$code = mysql_query("SELECT * FROM s_output WHERE name='$j'");
while($rowc = mysql_fetch_array($code))
{
$code=$rowc['code'];
}
echo $code;
This code for view code number using the name from database. i can use it with only php, but in my example I cant because I have an error with charset UTF-8, SO i just need use the code or numbers.
Thanks
you have right idea... use an ajax call to your php page where the php page echoes the result. Here is a not-so-elegant example to demonstrate, http://www.w3schools.com/php/php_ajax_database.asp

Categories