PHP with JavaScript to call database - php

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

Related

Output Buffering: Easy way to make string out of HTML-Code

I'm currently using Chatfuel to open the index.php-file of my website which sends the user the html code into his browser. There he can register and set up his account.
An example URL might look like this:
https://my.domain.com?key_value='123456789'
Depending on if that user is a new or a existing one, I wanna present him with a different form. In order to check so, I do a simple query to the MySQL db and see if the passed on key_value is already in the db and safe true or false to a boolean. Stating the obvious: If hes not an existing user, the 'empty' form with no values should show up. If he is registered he should see the information he filled in from last time.
My idea:
At the top of my index.php I do the check whether he's an existing customer or not (Note: This is working already). Then I want to use outputbuffering to alter the html-code depending on the boolean, before it is sent to the client.
My problem:
I developed the blueprint of the website in plain html (see code below). And OB only catches it as output if its within a string. Since I use " as well as ' in the document the string gets interrupted every few lines. Is there a simple workaround to this? Because the OB function is unable to access anything within the <html>...</html> tags.
Or do i need to use redirecting after the check (in my index.php) and create a separate form + script for both edit customer data and add new customer data?
<?php
//Connection stuff
// Prepare statment: !TODO: string needs to be escaped properly first
$query_string = "SELECT * FROM tbl_customer WHERE unique_url = '$uniqueurl'";
$query_rslt = mysqli_query($conn, $query_string);
if($query_rslt == FALSE)
{
// Failure
echo "<br> Oops! Something went wrong with the querying of the db. " . $conn->connect_error;
//Handle error
}
else
{
if ($query_rslt->num_rows > 0)
{
// Set boolean
$existing_customer = TRUE;
// Create an array called row to store all tuples that match the query string
while($row = mysqli_fetch_assoc($query_rslt)) {
//...
}
}
}
// Custom post processing function
function ob_postprocess($buffer)
{
// do a fun quick change to our HTML before it is sent to the browser
$buffer = str_replace('Testing', 'Working', $buffer);
// Send $buffer to the browser
return $buffer;
}
// start output buffering at the top of our script with this simple command
// we've added "ob_postprocess" (our custom post processing function) as a parameter of ob_start
if (!ob_start('ob_postprocess'))
{
// Failure
echo "<br> Oops! Something went wrong with output buffering. Check that no HTML-Code is sent to client before calling this start function.";
// Handle error
}
else
{
// Success
// This is where the string should get accessed before sending to the client browser
echo "Testing OB.";
}
?>
<!--DOCTYPE html-->
<html lang="en">
<head>
<meta charset="utf-8">
//...
</body>
</html>
<?php
// end output buffering and send our HTML to the browser as a whole
ob_end_flush();
?>
Output: "Working OB."
EDIT: I added source code example. This code won't compile.
Since, i can't comment, so i'll put some of my question here.
I dont really get the point, but give me a try, are you mean escaping string? you can use backslashes \ to escape string.
Like this "select from ".$dbname." where id = \"".$id."\"".
You can easily using addslashes($var) before adding the variable to the sql. like this
$id = addslashes($_POST['id']);
$sql = "select form db where id = '$id'";
If you mean checking the existent of the user to select which form to show in the page, why dont you do this?
if(userCheck()) {
?>
// here write the html code if user passed
<?php
} else {
?>
// here write the html code if user not passed
<?php
}
You can put userCheck() as global function or whereever you place it, as long as you can use it when you want to check the user before showing the form.
tl;dr: The thing I was looking for was a combination of file_get_contents() and object buffering.
file_get_contents() returns a string of a plain html-file of your choice. I could post a ton of explanation here or simply link you to phppot.com. The article offers you a directly executable demo with source (Download here). In case you wanna try it with a html file of yours, simply change the file path.
So once the whole html was converted into a string, I used the postprocessing function of OB to alter the string (= basically my html) if it's an existing user that came to alter his data. Then all the html-code (in a string still at this point) is sent to the client using ob_end_flush(). I will put up the actual code asap :)

Can't manage to make $_POST to work

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.

how to check if bookmarks exist in html document

I've just designed my first form in HTML and a PHP page to display the results. In the form the user inputs some codes in response to some questions, a bit like a multiple choice, so for example, these are "ABC". The PHP page displays the code to the user as a link, which when clicked will go to a bookmark (a link within the same page) with the ID #ABC. This was achieved with simple manipulation of the PHP variable as follows:
<?php
$code = "ABC"
$part1 = '<a href="mywebpage.php#';
$part2 = '">Go to this code</a>';
$string = $part1.$code.$part2;
echo $string;
?>
(i.e. Link in the page says "go to this code" and when clicked will go to section with bookmark ABC)
This all works fine, but I simply need to know if there is a way of error trapping so that if a bookmark does not exist for the code entered, a message can be displayed to the user instead? Can this be done using the PHP variable, or do I need to use JavaScript? One work around may be to search the web page for the ID "#ABC'. Is it possible to do this? Another option would be to store an array of valid codes on the server then query this before setting the bookmark, but I want to keep it as simple as possible. Any help appreciated, thanks.
What you call a "bookmark" we call a hash. And when you say "go to a bookmark" you mean a hash change. Hash changes do not make an additional request to the server, it is all handled on the client-side, therefore this must be done with JavaScript and not PHP.
So let's just do some simple JavaScript on hash change window.onhashchange that will search for an element with that ID and if it's not found alert something.
window.onhashchange = function(){
if(!document.getElementById(location.hash){
alert("not found");
}
}

Can't combine two strings properly

I'm trying to assign the return value of a php script to a js variable. I have this:
var email = jQuery("input[name=email]").val();
var emailRegex = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,})?$/;
var exists='<?php
$query = "SELECT * FROM rss_members WHERE email_id=\"something#email\"";
$results = mysql_query($query);
$results = mysql_num_rows($results);
echo $results;
?>';
console.log(exists)
The query works and I get the correct results back, but I want to replace "something#email.com" with the email variable, but if I write something like email_id=\"'+email+'\"..., the query result comes back incorrect. What am I doing wrong?
You aren't taking in consideration execution time.
When you make a request to a server (enter www.google.com for example) the server gets a request, and replies with a HTML page. The server in your case is in PHP and it sends a HTML page with some javascript included in it. After the browser receives the HTML page, it then interprets it, and run javascript code.
So basically, your php code ran without access to the email variable. If you wanted to have access to server-side information after the page loaded, you would need to make an ajax request

echo inside dynamic created div-tag php javascript

Im trying to echo an xml value to an dynamic created div tag, but i cant seem to find any information about it.
The DOM tree is created with JavaScript
textArea = document.createElement('textarea');
The output become <textarea></textarea>No problem here...
Then Im getting the value from an xml file with simple php.
<?php
foreach($xml->sticker as $sticker ){
$post = $sticker->text . "</br>";
$post;
echo $post;
}
?>
and the echo returns " Hello World "
Now to the issue, how do I echo inside the dynamically created textarea
the output should be
<textarea>Hello world</textarea>
Any ideas ? or a link maybe ?
Thanks
If you successfully load the xml with XHR then you can put your response inside your textarea with:
textArea.innerHTML = responseFromXHR;
It's not quite clear on how your application is supposed to work. If you want to fetch the data using ajax or not. Some people here seems to think so although you haven't stated that. I will assume that is not the case. If it is the solution would most likely be to have you PHP script return JSON encoded data, decode that using Javascript and insert it into the textarea.
Since you dynamically create the textarea you also have to dynamicly fill it with text using Javascript. Just add the text to the .innerHTML of the textarea.
Some if check in PHP to make sure the text should be printed and that the textarea exists and then using PHP add this to a Javascript.
echo 'textArea.innerHTML = "' . $post;
If you are supposed to print all posts in the same textareayou could do something like
<?php
echo '<script>';
echo 'textArea = document.createElement(\'textarea\');';
foreach($xml->sticker as $sticker ){
$posts .= $sticker->text . "\n\r";
echo $post;
}
echo 'textArea.innerHTML = "' . $posts;
echo '</script>';
?>
You could also have the check for the textarea's existence in Javascript if you'd like that. You probably wan't to do some filtering on the text you put into the textarea though.
How are you getting the value from the XML file?
In the PHP, return a string or JSON object, then in the AJAX callback, insert the data into the desired location.
Your php script that returns "Hello World" must be called via AJAX and on successful answer just like 'apelsinapa' said:
textArea.innerHTML = responseFromAjaxCall;
Otherwise - the PHP code gets parsed by the server before JavaScript creates the textarea node.

Categories