Php fread() function not returning anything - javascript

I have a simple AJAX function being called when a user clicks a button that sends the text of a HTML textarea and alerts the response from the backend:
send_button.onclick = function ()
{
var ajax = new XMLHttpRequest();
var text = text_input.value;
ajax.onreadystatechange = function ()
{
if (ajax.readyState == 4 && ajax.status == 200) alert(ajax.responseText);
};
ajax.open("POST", "write.php", true);
ajax.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
ajax.send("text=" + text);
};
as well as a PHP script on the backend which is supposed to write the received text to a file and echo the file's content:
<?php
$filename = "preview/preview.html";
$text = (isset($_POST["text"]) ? $_POST["text"] : "");
try
{
$fh = fopen($filename, "w+");
if (!$fh) throw new Exception("File open error");
fwrite($fh, $text);
$filetext = (filesize($filename) > 0 ? fread($fh, filesize($filename)) : "");
echo $filetext;
fclose($fh);
}
catch (Exception $e)
{
header("Location: error.php");
}
?>
But every time the response is empty. I tried echoing a hardcoded string instead of fread()and it worked, I also tried echoing filesize($filename)which worked perfectly fine as well.
The POST data sent by the AJAX function gets through as well, and the fwrite($fh, $text) function does exactly what it is supposed to.
What am I doing wrong?

You didn't rewind your file:
you open your file for writing
you write out some text - file pointer is at the END of the file
you try to read some text from the file, but the pointer is at the END of the file
no data is read, so you output an empty string
Why not use something more like this:
file_put_contents('preview/preview.html', $_POST['text'], FILE_APPEND);
readfile('preview/preview.html');
The "can't read file" is all fine and dandy, but all of the open/write/read business is redundant and can be reduced to the above two lines of code.

You could use $filetext = file_get_contents($filename); instead. I think you moved the file pointer to the end after writing in it, so you only see the end-of-file character.

You can use file_get_contents($file_name)

Related

php file's code not executing through ajax call

I have a button in my PHP file, and when I click on that button, I want another PHP file to run and save some data in a MySQL table. For that I am using AJAX call as suggested at this link (How to call a PHP function on the click of a button) which is an answer from StackOverflow itself.
Here is my show_schedule file from which I am trying to execute code of another PHP file:
$('.edit').click(function() {
var place_type = $(this).attr("id");
console.log(place_type);
$.ajax({
type: "POST",
url: "foursquare_api_call.php",
data: { place_type: place_type }
}).done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
});
});
here 'edit' is the class of the button and that button's id is being printed in the console correctly.
here is my foursquare_api_call.php file (which should be run when the button is clicked):
<?php
session_start();
include('connection.php');
if(isset($_POST['place_type'])){
$city = $_SESSION['city'];
$s_id = $_SESSION['sid'];
$query = $_POST['place_type'];
echo "<script>console.log('inside if, before url')</script>";
$url = "https://api.foursquare.com/v2/venues/search?client_id=MY_CLIENT_ID&client_secret=MY_CLIENT_SECRET&v=20180323&limit=10&near=$city&query=$query";
$json = file_get_contents($url);
echo "<script>console.log('inside if, after url')</script>";
$obj = json_decode($json,true);
for($i=0;$i<sizeof($obj['response']['venues']);$i++){
$name = $obj['response']['venues'][$i]['name'];
$latitude = $obj['response']['venues'][$i]['location']['lat'];
$longitude = $obj['response']['venues'][$i]['location']['lng'];
$address = $obj['response']['venues'][$i]['location']['address'];
if(isset($address)){
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude, address) VALUES ($name, $latitude, $longitude, $address)");
$result = $statement->execute();
}
else{
$statement = $connection->prepare("INSERT INTO temp (name, latitude, longitude) VALUES ($name, $latitude, $longitude)");
$result = $statement->execute();
}
}
}
?>
none of the console.log is logged in the console and also the 'temp' table is not updated. Can anyone tell me where I am making mistake? Or is it even possible to execute the code of a PHP file like this?
Your JavaScript is making an HTTP request to the URL that executes you PHP program.
When it gets a response, you do this:
.done(function( data ) {
alert("foursquare api called");
$('#userModal_2').modal('show');
}
So you:
Alert something
Show a model
At no point do you do anything with data, which is where the response has been put.
Just sending some HTML containing a script element to the browser doesn't cause it to turn that HTML into a DOM and execute all the script elements.
You'd need to do that explicitly.
That said, sending chunks of HTML with embedded JS back through Ajax is messy at best.
This is why most web services return data formatted as JSON and leave it up to the client-side JS to process that data.
to return the contents of php code you can do something like this
you can use any call to this function
function check_foursquare_api_call(place_type) {
var place_type= encodeURIComponent(place_type);
var xhttp;
//last moment to check if the value exists and is of the correct type
if (place_type== "") {
document.getElementById("example_box").innerHTML = "missing or wrong place_type";
return;
}
xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("example_box").innerHTML = xhttp.responseText;
$('#userModal_2').modal('show');
}
};
xhttp.open("GET", "foursquare_api_call.php?place_type="+place_type, true);
xhttp.send();
}
this will allow you to send and execute the code of the foursquare_api_call file and return any elements to example_box, you can return the entire modal if you want,
you can use any POST / GET method, monitor the progress, see more here
XMLHttpRequest

Get data php with ajax without display it

Is it possible to get data php with Ajax without display them ? Simply stock data in JS variable?
I need this data to manipulate dates but no show it.
When I tried to simply return data without echo, etc. Data ajax in JS is empty
Ps : sorry my English is bad
try it this way
File *.php
<?php
$var_1 = null;
$var_2 = null;
/** ... */
$response = new stdClass;
$response->var_1 = $var_1;
$response->var_2 = $var_2;
echo json_encode($response);
?>
File *.html or *.js
<script>
var state = {};
$.ajax({
url: 'getData.php',
type: 'post',
dataType: 'json',
success: function (response) {
console.warn(response);
state = response;
}
});
</script>
Assuming you are trying to pass data from a PHP file to HTML/JS where it happens that your PHP file is also included in the HTML that's why it's displaying the echo (if I understood correctly!)
Using AJAX PHP example from w3school.
HTML sample file:
<?php include "PHP_SAMPLE_FILE.php" ?>
<header>
<meta name="temp_files" content="<?= htmlspecialchars($jsonData) ?>">
<!-- The rest of HTML content -->
JS sample file:
if (str.length == 0) {
// do something if there was nothing entered
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
if (this.responseText.includes('{')){
result = JSON.parse(this.responseText);
// do something if response is JSON
} else {
// do something if response is null
}
}
}
xmlhttp.open("GET", "PHP_SAMPLE_FILE.php?q="+str, true);
xmlhttp.send();
}
PHP sample file:
$q = $_REQUEST["q"] ?? $_POST["q"] ?? "";
$sql = "GET SOMETHING FROM DATABASE";
$result = mysqli_query($con, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[] = $row;
}
}
$jsonData = json_encode($json ?? null);
if($q != ""){
echo $jsonData;
}
What happens exactly is that once the page loads initially it won't display the output of the PHP query as we have surrounded the echo with an if statement that requires to have query value (q) to search and it shouldn't be empty (""). Of course, assuming that once the page is loaded the data is shared with the client-side through defined PHP variables using various approaches, using a meta tag in the header for instance.
Once the data is received from the PHP file through echo, we use the JSON.parse function to parse it as in this scenario JS receives it as a string.
Hope that helped :)!

appending a text file in php using JSON, not working and no error message being displayed

I have a JavaScript function which is called with a parameter when someone clicks a div. The JavaScript function makes a JSON string out of the parameter and then makes a XMLHttpRequest (AJAX) to the php file that takes this JSON string, finds the number within the JSON string and then stores the number in a text file on the server.
However when i run this on my server, no number is appended to the text file and nothing seems to happen. No error message is displayed. The "Thank You!" message does get displayed in the div, which means the readystate does become 4 and the status does become 200.
The html code that calls the JavaScript function with a parameter:
<li id="star1" onclick="saveRating(1)"><i class="fa fa-star" aria-hidden="true"></i></li>
The javaScript function that creates a JSON string and calls the php file:
function saveRating(num){
obj = { "score":num };
dbParam = JSON.stringify(obj);
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
//a "Thank You!" message is displayed in the div
}
};
xmlhttp.open("GET", "php/storeRating.php?x=" + dbParam, true);
xmlhttp.send();
}
The PHP file that opens a text file, searches the JSON string for a number and appends the number to the text file:
<?php
header("Content-Type: application/json; charset=UTF-8");
$obj = json_decode($_GET["x"], false); //gets the param that was sent and stores it in $obj
//opens text file and sets to appending the file.
$myfile = fopen("ratingNumbers.txt", "a");
//goes through string and if it finds a number it adds it to the text file.
while(false !== ($char = fgetc($obj))){
if($char == 1){
fwrite($myfile, $char);
}if($char == 2){
fwrite($myfile, $char);
}if($char == 3){
fwrite($myfile, $char);
}if($char == 4){
fwrite($myfile, $char);
}if($char == 5){
fwrite($myfile, $char);
}
}
//closes the file
fclose($myfile);
?>
[edit] The text file and PHP file both have write permissions.
I found 2 mistakes on your script.
Place the file handle in given line
while(false !== ($char = fgetc($myfile))){
$myfile = fopen("ratingNumbers.txt", "a+"); // Open for reading and writing;

Passing php variable to javascript in a different file

I'm having problems with passing php variables to javascript.
It does pass through the variable that is declared at the top, but I don't know how to call the function to get the new version of variable after the IF statement is done.
$info = "A message";
if (true){
$info = 'Message to be passed';
}
The script that is used to pass the php variable to javascript file:
<script type='text/javascript'>
var info = "<?php echo $info; ?>";
</script>
I was wondering what could I do to fix this problem?
The simple way (this requires both files to be PHP files):
<?php
require_once "your_php_file_here.php"; // Change to your PHP file here
?>
<script type='text/javascript'>
var info = "<?php echo $info; ?>";
alert(info);
</script>
This will only allow you to get the value on page load. You need to reload the page if you want it to get a new value.
The (in my opinion) better way (the file can be HTML) using Ajax:
<script type='text/javascript'>
var info;
var xhr = new XMLHttpRequest();
xhr.open('GET', 'your_php_file_here.php'); // Change to your PHP file here
xhr.onload = function() {
if (xhr.status === 200) {
info = xhr.responseText;
alert(info);
} else {
alert('Request failed: ' + xhr.status);
}
};
xhr.send();
</script>
This can be put in a function and called as many times as you want. It can get the new value without the need to reload the page.
For this to work, you need to change your PHP code to:
$info = "A message";
if (true){
$info = 'Message to be passed';
}
echo $info;
I did not add support for IE6 and below because I think it's about time we stop supporting browsers that lost support by their developers many years ago.

Simple HTML DOM get dynamic content loaded with JS

I'm trying to get a dynamically loaded content from a web page. Specifically the options loaded to a select. So if I do:
$options = $html->find('select[class=theSelectClass]')[0]->find('option');
foreach($options as $option){
echo $option->text().'<br>';
}
This works as expected and my output is:
Select an option
Why? Because the other options are loaded with JS after the page loads. So my question is how can I get this dynamically loaded options inside the select?
This is my attempt using JS Ajax and another PHP page:
in my php that includes the simple_html_dom:
$html->load_file($base);
$var = '<script>
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
this.responseText;
}
};
xhttp.open("GET", "http://localhost/crawler/ajax.php?param=HelloWorld", true);
xhttp.send();
</script>';
$e = $html->find("body", 0);
$e->outertext = $e->makeup() . $e->innertext . $var . '</body>';
and my ajax.php file:
file_put_contents ( 'ajax.txt' , $_GET['param']);
I was trying to see if I could send an Ajax call from the html loaded file, but I feel far from being able to do it. So how can I make this happen?
Thank you
It might be easier for you to first use a headless browser to render the page then pass that to simple html dom. You could do this with CasperJS/PhantomJS or another tool that renders the page with javascript.
`
require("vendor/autoload.php");
use Sunra\PhpSimple\HtmlDomParser;
use Browser\Casper;
$casper = new Casper();
// forward options to phantomJS
// for example to ignore ssl errors
$casper->setOptions(array(
'ignore-ssl-errors' => 'yes'
));
$casper->start('https://www.reddit.com');
$casper->wait(5000);
$output = $casper->getOutput();
$casper->run();
$html = $casper->getHtml();
$dom = HtmlDomParser::str_get_html( $html );
$elems = $dom->find("a");
foreach($elems as $e){
print_r($e->href);
}
?>`

Categories