I need to change the html in a div without page refreshing while php runs a foreach statement, i think this is possible with jquery, but i'm not sure i'm doing the correct way to achieve this. This is the code i have at the moment.
$filename = "entries.csv";
$topic = $_GET['q'];
$file = new SplFileObject($filename, 'w');
$sentences = explode(".", getResultsPage(getBingLink($topic)));
$file->fputcsv(array("Topic", "Sentence", "Word", "Tag"));
foreach($sentences as $sentence){
?>
<script>
$("#view").html('<?php echo $sentence; ?>');
</script>
<?php
if(preg_match("/^[A-Za-z0-9òàùèìé\s\?\!\,\-]*$/",$sentence)){
$words = $pos->tag(explode(" ", $sentence));
foreach($words as $word){
$file->fputcsv(array($topic, $sentence, $word[0], $word[1]));
}
}
}
because it only prints the script when the page is loaded. Any useful hints or advices are greatly appreciated. Thanx.
Related
With scandinavian letters and when encoding them, I have a problem. With code below, javascript add some extra encoding to variable
<script>
function doit(params) {
var url = "/linkto/code.php" + params;
window.open(url,"Doit","width=750, height=600");
}
</script>
<?php
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
echo 'Do it!'; // link to page
?>
When changing code above to php, changed does not happened and problem go away.
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
// link to page
echo '<a href="/linkto/code.php"'.$param.'>Do it!</a>';
Hi all again,
I cannot make it work, no difference between utf-8 or iso-8859-1.
Result is something else, when using javascript-function or direct link.
You can try it here:
http://www.ajl.fi/tmp/test.php
Here is codes:
test.php:
<script type="text/javascript">
function doIt(params) {
var url = "doit.php" + params;
window.open(url,"doit");
}
</script>
<?php
$var1 = 'pähkinä';
$var1 = urlencode($var1);
echo sprintf("Do it - call",$var1)."<br>";
echo sprintf("Do it - link",$var1);
?>
and here is doit.php:
<?php
var_dump($_GET);
?>
In ist code, you have two issues in this code
1) Short tag will not work inside the <?php ?> here:
echo 'Do it!'; // link to page
2) You forgot to add quotes here:
window.open(url,"Doit",width=750, height=600"); //missing quote here
Modified Code:
<?php
$var1 = 'p%E4hkin%E4';
$values = urlencode($var1); // encoding skandinavian letters
$param = '?test='.$values; // add them to variable
?>
Do it!
<script type="text/javascript">
function doit(params) {
var url = "/linkto/code.php" + params;
console.log(url);
window.open(url,"Doit","width=750, height=600");
}
</script>
I answer to myself - Solved.
IE, Edge and Chrome, all working ok on both cases. Firefox has a problem. When using
Do it!
result is not correct, but when using
Do it!
seems to work on all browsers
So what I'm trying to do is the following:
first: When the button add-location is clicked this loads a php file using AJAX.
jQuery
$('.add-location').click(function() {
var locationName = $(this).data('location');
$.post('http://www.example.com/reload-location-2.php?addparam',
{locationName: locationName}, function(data) {
$("textarea#location").html(data);
})
});
PHP FILE
<?php start_session();
$locationName = array_key_exists('locationName',
$_POST) ? (string) $_POST['locationName'] : '';
if(isset($_GET['delparam'])){
unset($_SESSION['locations'][$locationName]);
}
if(isset($_GET['addparam'])){
$_SESSION['locations'][$locationName] = $locationName;
}
?>
<?php foreach ($_SESSION['locations'] as $location): ?>
<?php echo htmlspecialchars($location); echo "\n"; ?>
<?php endforeach;?>
This all works like a charm! No worries here. No what I'm trying to do is when the button add-location is clicked this echo's the following code to a div called textarea#thema.
<?php foreach ($_SESSION['products'] as $product): ?>
<?php echo htmlspecialchars($product); echo "\n"; ?>
<?php endforeach;?>
OR, if that's easier when the page is loaded -> echo that code to the textarea#thema div.
I do not understand AJAX that much but I'm getting there. But I think the last option maybe the easiest solution?
Could anyone help me figure this one out?
What I tried
Right now, When the button add-location is clicked I reload a previous jQuery script:
$('.add-location').click(function() {
var productName = $(this).data('product');
$.post('http://example.com/reload-2.php?addparam',
{productName: productName}, function(data) {
$("textarea#thema").html(data);
})
});
This works, but it adds an extra <p>-tag leaving me with a line break in the code.
I also changed the .html(data); to .val(data); for the textareas. Also I made a new PHP file with just this code:
<?php foreach ($_SESSION['products'] as $product): ?>
<?php echo htmlspecialchars($product); echo "\n"; ?>
<?php endforeach;?>
And this jQuery code:
$('.add-location').click(function() {
var productName = $(this).data('product');
$.post('http://www.example.com/reload-3.php',
{productName: productName}, function(data) {
$("textarea#thema").val(data);
})
});
But still no go... And I don't think this is the way to go?? I hope I gave enough information.
You should use .val() function to fill textarea, not .html().
I am using Js code inbetween php. I am trying make the body empty and append php text for every loop. php code works fine, but js works only when php has completed the script fully. Someone Please help
<?php
while($row = $result->fetch_assoc()){
$count++;
$email = "";
$email = $row['email_id'];
$result_row_count = $result->num_rows;
?>
<script type ="text/javascript">
$(document).ready(function(){
$("body").empty();
});
</script>
<?php
echo '<h4> Sending Mails '.$count.' of '.$result_row_count.' --- '.$email.'</h4>';
flush();
ob_flush();
sleep(1);
?>
<script type ="text/javascript">$("body").empty();</script>
use this code
I've this PHP page:
<?php
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){
$message = htmlspecialchars($line);
?>
<div onclick="alert('<?=$message?>');"><div>
<?php
}
It generates this HTML results:
<div onclick="alert('I am happy');"><div>
<div onclick="alert('I'm happy');"><div>
This code seems to be correct, however, clicking on second "div" element an error occurs.
The ' char is equivalent to ' and javascript generates an error:
alert('I'm happy');"
I solved this problem adding to code addslashes() PHP function:
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){
$message = htmlspecialchars(addslashes($line));
?>
<div onclick="alert('<?=$message?>');"><div>
<?php
}
Correct results:
<div onclick="alert('I am happy');"><div>
<div onclick="alert('I\'m happy');"><div>
My question:
Is this the right/best solution?
Which is the best practice to manage this kind of problems?
Don't try to generate JavaScript string literals by mashing strings together. json_encode will do it for you along with all the escaping (', ", new lines, etc) that you need for JS. It is preferred to addslashes because it is designed for the target data format and isn't generic (generic escaping solutions tend to miss things).
Encode data for HTML attribute values as the last thing you do to the data before putting it in the value. Don't encode for HTML before putting data into JavaScript.
foreach ($lines as $line){
$message = json_encode($line);
$javascript = "alert($message)";
$html = htmlspecialchars($javascript);
?>
<div onclick="<?= $html ?>"><div>
<?php
}
That said, a modern approach would generally keep the JavaScript separate and store the data in a data attribute.
You should also avoid putting click events on div elements, they aren't designed to be user controls so they can't (without more mucking about) be triggered by (for example) focusing the element and pressing enter which creates accessibility problems.
foreach ($lines as $line){
$html = htmlspecialchars($line);
?>
<button type="button" data-message="<?= $html ?>">...</button>
<?php
}
with
<script>
function buttonAlert(event) {
var message = event.target.dataset.message;
if (message) {
alert(message);
}
}
addEventListener("click", buttonAlert);
</script>
Your correct result is actually wrong, and would output I'm happy instead of I'm happy.
Asside from that, yes your solution will work and i don't see any problem with that way of doing in your particular context.
You can use below code
<?php
$lines = array();
$lines[] = "I am happy";
$lines[] = "I'm happy";
foreach ($lines as $line){ ?>
<div onclick="alert('<?=addslashes($line); ?>');"><div>
<?php } ?>
Can I trigger the execution of a php file from another php file when performing an action? More specific, I have an anchor generated with echo, that has href to a pdf file. In addition of downloading the pdf I want to insert some information into a table. Here's my code, that doesn't work:
require('./database_connection.php');
$query = "select author,title,link,book_id from book where category='".$_REQUEST['categorie']."'";
$result = mysql_query($query);
$result2 = mysql_query("select user_id from user where username='".$_REQUEST["username"]."'");
$row2 = mysql_fetch_row($result2);
while($row= mysql_fetch_row($result))
{
echo '<h4>'.$row[0].' - '.$row[1].'</h4>';
if(isset($_SESSION["username"]) && !empty($_SESSION["username"]))
{
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo ' <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script language="javascript">
function insert_download() {
$.ajax({
type: "GET",
url: "insert_download.php" ,
success : function() {
location.reload();
}
});
}
</script>
<a onclick="insert_download()" href="'.$row[2].'" download> download </a>';
}
And here's the insert_download.php:
<?php
require('./database_connection.php');
$query = "insert into download(user_id,book_id,date)values(".
$_REQUEST["id_carte"].",".
$_REQUEST["id_user"].",".
date("Y-m-d h:i:s").")";
mysql_query($query,$con);
mysql_close($con);
?>
Can anyone help me with this? Thanks!
As I understand correctly, you want to display a link, and when the user clicks that link,
some data is inserted into a database or something;
the user sees a download dialog, allowing him to download a file?
If this is correct, you can use this code:
On your webpage:
download
result.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "";
?>
<!DOCTYPE html>
<html>
<head>
<title>Downloading...</title>
<script type="text/javascript">
function redirect(url) {
//window.location.replace(url);
window.location.href = url;
}
</script>
</head>
<body>
Download is starting...
<script type="text/javascript">
redirect("http://example.com/download.php?file=dummy.pdf");
</script>
</body>
</html>
download.php:
<?php
$file = isset($_GET['file']) ? $_GET['file'] : "nullfile";
$file_url = "download_dir_or_something/".$file;
// Put some line in a log file...
file_put_contents("logfile.txt", "successful on ".date("Y-m-d H:i:s")."\n", FILE_APPEND);
// ...or anything else to execute, for example, inserting data into a database.
header("Content-Type: application/octet-stream");
header("Content-Transfer-Encoding: Binary");
header("Content-disposition: attachment; filename=\"".basename($file_url)."\"");
readfile($file_url);
?>
Why not use a redirection instead of "complicated" AJAX?
<!-- in your first document -->
echo '<input type="hidden" name="id_carte" value="'.$row[3].'">';
echo '<input type="hidden" name="id_user" value="'.$row2[0].'">';
echo 'download';
and in download_pdf.php
<?php
require('./database_connection.php');
...
mysql_close($con);
header("location: " . $_GET['redirect']);
You're lacking basic skill of debugging. If I was you, I should:
Use a browser which supporting, ex: Chrome with "Network" inspecting tab ready
Try click on the link <a onclick="insert_download()" ... and see if the ajax request is performed properly (via Network inspecting tab from your chrome). If not, re-check the generated js, otherwise, something wrong with the download_pdf.php, follow next step
Inspecting download_pdf.php: turn on error reporting on the beginning (put error_reporting(E_ALL); and ini_set('display_errors', 1); on top of your file) try echoing something before and/or after any line you suspect that lead to bugs. Then you can see those ajax response from your Network inspecting tab... By doing so, you're going to narrow down which line/scope of code is causing the problem.
Note that the "echoing" trick can be avoid if you have a solid IDE which is supporting debugger.
Hope it can help