How can I write PHP code into JavaScript/Ajax? - javascript

I want to know how to write a pice of PHP code into JavaScript/Ajax.
This is my PHP code:
if ($folder = opendir('data/Tasklist/')) {
while (false !== ($file = readdir($folder))) {
if ($file != '.' && $file != ".."){
$data=file_get_contents("data/Tasklist/".$file);
$poc=explode(";",$data);
echo '<li class="taskli">
<button id="'. $file . '" class="Del"> Delete </button>
'. $poc[0] . " " . $poc[1] . '<div class="hidinfo">' . $poc[2] . '</div></li>';
}
}
closedir($handle);
}
And i want to write : id="'. $file . '" inside this code:
$.post( "data/remove.php",{HERE})

Since you're storing the $file variable in the <button> id, you can grab it from there:
$('.Del').click(function(){
var file = $(this).attr('id');
$.post( "data/remove.php",{id:file});
return false;
});

Related

How to use javascript and HTML to add a sql and button?

I have an application where I want to ADD an AND button that, than creates the option to add an AND statement to the query. This is the php and html code I have to do this at the moment. The problem is I don't know how to connect the php part to the javascript part to create a button that adds exacte the same code?
This the html code:
This is the php code:
<?php
include "connect.php";
$table = $_POST['tableSelected'];
$field = $_POST['fieldSelected'];
$attribute = $_POST['attributeSelected'];
$operator = $_POST['operatorSelected'];
$fieldList = $_POST['fieldList'];
if (!empty($table)){
if (!empty($fieldList)){
$fieldstr = $fieldList . ",ST_AsGeoJSON(ST_Transform(l.geom,4326),6)";
} else {
$fieldstr = "";
}
$pairs = [];
foreach ($_POST['fieldSelected'] as $key => $field) {
if (!empty($field) && !empty($_POST['operatorSelected'][$key]) && !empty($_POST['attributeSelected'][$key])) {
$pairs[] = $field . " " . $_POST['operatorSelected'][$key] . " '" . $_POST['attributeSelected'][$key] . "'";
}
}
if (count($pairs) > 0) {
$sql .= ' WHERE ' . implode(' AND ', $pairs);
}
//echo ($sql);
?>
And this my html at the moment:
<select name="field[]">...</select>
<select name="operator[]">...</select>
<select name="value[]">...</select>
This is what I want:
Button click should produce something like it Javascript (jQuery):
newElement = $("#someSelector").clone(false);
// Some modification of new element. Change id for example
$(newElement).attr("id",newIdValue);
newElement.appendTo("#parentElement");

Javascript/PHP ignore quotes in string

I'm making a music player using php and javascript. I list the files like this:
<?php
if (isset($_GET["action"])) {
$action = htmlspecialchars($_GET["action"]);
if ($action == "listen") {
function listFolderFiles($dir) {
$ffs = scandir($dir);
echo '<ol>';
foreach($ffs as $ff){
if($ff != '.' && $ff != '..'){
echo '<li>'. $ff . '';
if (is_dir($dir . '/' . $ff)) listFolderFiles($dir . '/' . $ff);
echo '</li>';
}
}
echo '</ol>';
}
listFolderFiles("music");
}
} else {
echo '> listen';
}
?>
And I change the song like this:
<script>
function changesong(url) {
$("#audioplayer").attr("src", url);
$("#audioplayer").trigger('play');
}
</script>
The problem is that songs with quotes in them won't play (for example Don't Stop Me Now). Is there an easy way to fix this?
You should use addslashes(), like this:
echo '<li>'. $ff . '';
You can escape quotes for javascript function in HTML code like this:
Note that you probably need to escape double quotes as well, since they can interfere with HTML tag.
$link = $dir . '/' . $ff;
$link = str_replace("'", "&apos;", $link);
$link = str_replace('"', """, $link);
echo '<li>'. $ff . '';

php javascript autopopulated image gallery

I get the error message syntax error missing ; before statement at "var galleryarray=new Array();" . "\n"; here is the php code
function returnimages($dirname=".") {
$pattern="\.(jpg|jpeg|png|gif|bmp)$";
$files = array();$curimage=0;
if($handle = opendir($dirname)) {
while(false !== ($file = readdir($handle))){
if(eregi($pattern, $file)){
echo 'galleryarray[' . $curimage .']=["' . $file . '"];' . "\n";
$curimage++;
}
}
closedir($handle);
}
return($files);
}
echo "var galleryarray=new Array();" . "\n";
returnimages();
and here is the javascript:
var galleryarray=new Array();
var curimg=0
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "slideshow_images/"+galleryarray[curimg])
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0
}
window.onload=function(){
setInterval("rotateimages()", 2500)
}
i just don't see my mistake any help with this problem would be appreciated
klein
Replace your below line:
echo "var galleryarray=new Array();" . "\n";
with the following line:
echo "<script>var galleryarray=new Array();</script>";
You are adding a JS code without script tag so you need to add this tag.
EDITED:
echo 'galleryarray[' . $curimage .']=["' . $file . '"];' . "\n";
You also have error in the above line replace it with the below line:
echo '<script>galleryarray["' . $curimage .'"]=["' . $file . '"];</script>';

PHP and AJAX: How can I display json_encode data in PHP while loop?

I am very new to using AJAX and passing data with json_encode. I have this "aht" button when clicked it will send an AJAX request to my show_aht.php script, which will run a query. I want to save the results and display it to my map.php.
Problem:
In my map.php I have a while loop that outputs square(desk) DIVs with another DIV(station) when clicked that displays content inside of it. Here is the fiddle so you may understand. I want the results of show_aht.php "TIME" to be displayed in the DIVs being produced by my WHILE LOOP in map.php.
How is it possible to do this? I know that AJAX and PHP cannot interact with eachother and thats why I need help. If this can't be done, how else can I display the TIME from show_aht.php to their corresponding usernames on each DIV being output? I have around 200 of them being displayed.
Thanks in advance.
map.php (only showing the last line of the while loop, outputs all DIVs)
//desk DIV
while(somequery){
....
echo '<div class="' . $class . '" data-rel="' . $id . '" style="left:' . $x_pos . 'px;top:' . $y_pos.'px;">' . $sta_num . '</div>' . "\n";
}//end while
//station DIV
while(some query){
.....
echo '<div class="station_info_" id="station_info_' . $id . '" style="left:' . $x_pos . 'px;top:' .$y_pos . 'px;"><p class="numb">User:' . $user .'<br>Station:' . $hostname . '<br>Pod:' . $sta_num . '<br>Section:' . $sec_name . '<br>State:' . $state .'<br></p></div>' . "\n";
}//end while
map.php (AJAX part)
<div id="aht"><!--aht button-->
<button id="aht_button">AHT</button>
</div><!--aht button-->
<script type="text/javascript">
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
}//end success
});//end ajax
});//end click
});//end rdy
</script>
show_aht.php (showing the loop and part I where I want the data to be returned)
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
echo " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
echo "User: " . $m . " Time: N/A <br>";
}
}
}
Don't output anything except one valid json string. In your case you do that by replacing the echo's with building an array (or object...) and output that at the very end:
For example:
$data = array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$data[] = " User: " .$m. " Time: " . $v['avg_handle_time'] . "<br>";
}
elseif( $v['memo_code'] != $m){
$data[] = "User: " . $m . " Time: N/A <br>";
}
}
}
// Output your json string
echo json_encode($data);
Note that I have simply replaced your echos with an assignment but you could also add arrays in your array to return just the data parts and process that afterwards in javascript.
For example (this would depend a bit on your exact data structure...):
...
$data[] = array($m, $v['avg_handle_time']);
...
change show_aht.php to
$res=array();
foreach($memo_data as $v){
foreach($user_data as $m){
if($v['memo_code'] == $m){
$res[]= " User: " .$m. " Time: " . $v['avg_handle_time'];
}
elseif( $v['memo_code'] != $m){
$res[]= "User: " . $m . " Time: N/A <br>";
}
}
}
echo json_encode($res);
and map.php ajax to
$(document).ready(function() {
$('#aht').click(function(){
$.ajax({
type:"POST",
url : "show_aht.php",
data: , // pass data here
dataType: 'json',
success : function(data){
for(i=0;i<data.length;i++){
//append data[i] to div
}
}//end success
});//end ajax
});//end click
});//end rdy

Adding comments into database with PHP (Using AJAX to prevent page reload)

I'm trying to make a comments system which adds to the database using PHP and AJAX without having to reload the page (if I reload the page it will pick another film suggestion at random).
At the moment it doesn't seem to work - when I click "Submit comment" it reloads the page (loading a different film) and nothing is inserted to the database.
I'd also like to be able to have the comment appear in the comments section below after submission if possible.
Thanks for your help
yourfilm.php (the process page that displays a film, specified by options selected on a form on the previous page)
<?php //recaptcha_process.php
require_once("php/checklog.php");
require_once('php/functions.php');
require_once('php/db_connect.php');
include_once("php/home_start_logged.php");
if (!$db_server){
die("Unable to connect to MySQL: " . mysqli_connect_error());
$db_status = "not connected";
}else{
//CODE TO QUERY DATABASE TO GO HERE
//Capture form data, if anything was submitted
if (isset($_POST['genreList']) && ($_POST['genreList'] != '')){
$genre = clean_string($db_server, $_POST['genreList']);
//create the SQL query
$query = "SELECT * FROM films WHERE genreID=$genre ";
//$endquery = " AND (";
$endquery = "";
$orFlag = false;
if (isset($_POST['streamingCheckbox1']) && ($_POST['streamingCheckbox1'] != '')){
$endquery .= " netflix IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox2']) && ($_POST['streamingCheckbox2'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " lovefilmInstant IS NOT NULL";
$orFlag = true;
}
if (isset($_POST['streamingCheckbox3']) && ($_POST['streamingCheckbox3'] != '')){
if($orFlag){
$endquery .= " OR ";
}
$endquery .= " blinkbox IS NOT NULL";
}
if($endquery != "") $query .= " AND (" . $endquery . ")";
$query .= " ORDER BY (SELECT FLOOR(MAX(filmID) * RAND()) FROM films) LIMIT 0,1;";
//query the database
mysqli_select_db($db_server, $db_database);
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server) . $query);
//if there are any rows, print out the contents
if ($row = mysqli_fetch_array($result)) {
//Whether to display links or not for purchase and streaming
if ($row['netflix'] == null){
$netflixLink = "";
}else{
$netflixLink = "<a href='" . $row['netflix'] . "'>" . "<img class='streamingLogo' src='images/netflix_logo.jpg' alt='Watch on Netflix'></a>";
}
if ($row['lovefilmInstant'] == null){
$lovefilmLink = "";
}else{
$lovefilmLink = "<a href='" . $row['lovefilmInstant'] . "'>" . "<img class='streamingLogo' src='images/Lovefilm_logo.jpg' alt='Watch on LoveFilm'></a>";
}
if ($row['blinkbox'] == null){
$blinkboxLink = "";
}else{
$blinkboxLink = "<a href='" . $row['blinkbox'] . "'>" . "<img class='streamingLogo' src='images/blinkbox_logo.jpg' alt='Watch on Blinkbox'></a>";
}
if ($row['itunes'] == null){
$iTunesLink = "";
}else{
$iTunesLink = "<a href='" . $row['itunes'] . "'>" . "<img class='streamingLogo' src='images/itunes_logo.jpg' alt='Buy now on iTunes'></a>";
}
if ($row['googlePlay'] == null){
$googleplayLink = "";
}else{
$googleplayLink = "<a href='" . $row['googlePlay'] . "'>" . "<img class='streamingLogo' src='images/googleplay_logo.jpg' alt='Buy now on Google Play'></a>";
}
if ($row['amazon'] == null){
$amazonLink = "";
}else{
$amazonLink = "<a href='" . $row['amazon'] . "'>" . "<img class='streamingLogo' src='images/amazon_logo.jpg' alt='Buy now on Amazon'></a>";
}
//Body content for film
$str_result = "<section>
<div class='sectionColumnThird'>
<img class='poster' src='images/posters/" . $row['poster'] . ".jpg'>
</div>
<div class='sectionColumnTwoThirds'>
<h2>" . $row['filmName'] . "</h2>
<p class='filmDate'>(" . $row['filmYear'] . ")</p>
<a class='formButton' href='#comments'>Jump to comments</a>
</div>
</section>
<section>
<h3>Not interested?</h3>
<a class='formButton' href='#yourfilm.php'>Find another film</a>
</section>
<section>
<h3>Rating</h3>
<p><span class='bold'>IMDB:</span> " . $row['ratingIMDB'] . "</p>
<p><span class='bold'>Rotten Tomatoes:</span> " . $row['ratingRottenTomatoes'] . "</p>
<p><span class='bold'>Metacritic:</span> " . $row['ratingMetacritic'] . "</p>
</section>
<section>
<h3>Synopsis</h3>
<p>" . $row['synopsis'] . "</p>
</section>
<section>
<h3>Trailer</h3>
<div class='videoWrapper'>
<iframe src='//www.youtube.com/embed/" . $row['trailer'] . " ' frameborder='0' allowfullscreen></iframe>
</div>
</section>
<section>
<h3>Cast & Crew</h3>
<p><span class='bold'>Director:</span> " . $row['director'] . "</p>
<p><span class='bold'>Writers:</span> " . $row['writer'] . "</p>
<p><span class='bold'>Cast:</span> " . $row['cast'] . "</p>
</section>
<section>
<h3>Details</h3>
<p><span class='bold'>Certificate:</span> " . $row['certificate'] . "</p>
<p><span class='bold'>Country:</span> " . $row['country'] . "</p>
<p><span class='bold'>Language:</span> " . $row['language'] . "</p>
</section>
<section>
<h3>Streaming Services</h3>"
. $netflixLink . $lovefilmLink . $blinkboxLink ."
</section>
<section>
<h3>Buy now</h3>"
. $iTunesLink . $googleplayLink . $amazonLink ."
</section>
<section>
<form id='frmFilmComments' action='yourfilm.php' method='post'>
<a id='comments' class='anchor'></a><h3>Comments</h3>
<p><span class='bold'>Did you like " . $row['filmName'] ."?</span></p>
<select class='selectbox' name='yesornoList'>
<option value='Yes'>Yes</option>
<option value='No'>No</option>
</select>
<p id='commentResult'></p>
<p><span class='bold'>Provide your feedback here:</span></p>
<textarea id='commentBox' class='insertComment' rows='2' cols='30' name='comment'></textarea><br>
<input class='formButton' type='submit' id='submitComment' name='submitComment' value='Submit comment' />
</form>";
$filmID=$row['filmID'];
mysqli_free_result($result);
//Print out Like it - Comments
$likeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='Yes' AND filmID=$filmID";
$likeitResult = mysqli_query($db_server, $likeitQuery);
if (!$likeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($likeitResult)){
$str_likedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($likeitResult);
$likedcomments = "<div class='half subSection'>
<h4>Liked it</h4>"
. $str_likedcomments .
"</div>";
//Print out disike it - Comments
$dislikeitQuery = "SELECT * FROM comments
JOIN users on users.userID = comments.userID
WHERE likeit='No' AND filmID=$filmID";
$dislikeitResult = mysqli_query($db_server, $dislikeitQuery);
if (!$dislikeitResult) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($dislikeitResult)){
$str_dislikedcomments .= "<p>" . $row['username'] . " - " . $row['commDate'] . "<br>"
. $row['comment'] . "<br>
▲(" . $row['upvotes'] . ") ǀ ▼ (" . $row['downvotes'] . ")</p>";
}
mysqli_free_result($dislikeitResult);
$dislikedcomments = "<div class='half subSection'>
<h4>Disliked it</h4>"
. $str_dislikedcomments .
"</div>";
}else{
$str_result = "<section><h3>Sorry</h3><p>We couldn't find any films that match your terms. </br> <a href='home.php'>Please try again.</a></p></section>";
}
}else{
$str_result = "<section><h3>Sorry</h3><p>No genre was chosen.</br><a href='home.php'>Please try again.</a></p></section>";
}
$message = $str_result . $likedcomments . $dislikedcomments . "<section/>";
}
//Comments
$userID = $_SESSION['userID'];
$likeit = $_POST['yesornoList'];
$comment = clean_string($db_server, $_POST['commentBox']);
//Get any submitted comments and insert
if ($comment != '') {
$query = "INSERT INTO comments (userID, filmID, comment, likeit) VALUES ($userID, $filmID, $comment)";
mysqli_select_db($db_server, $db_database);
mysqli_query($db_server, $query) or
die("Insert failed: " . mysqli_error($db_server));
$message = "Thanks for your comment!";
}
require_once('php/db_close.php');
?>
<div id="top" class="content container headerMargin">
<div class="content wrapper">
<?php echo $message; ?>
</div>
</div>
<?php
require_once('php/home_end.php');
?>
addCommentAJAX.js
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
$("#frmFilmComments").submit( function() {
return false;
});
function clearInput() {
$("#frmFilmComments :input").each( function() {
$(this).val('');
});
}
home_start_logged.php is simply a header template, I won't post it all but it contains:
<script src="js/addCommentAJAX.js" type="text/javascript"></script>
EDIT: Added more specific info about the error (see above).
there is not enough data to make an exact solution, but i see two problems :
1 - you are not preventing the default form submit in your submit function event.preventDefautlt() or just change the input type attribut in your form to button rather than submit
2 - if you wan't the comment that the user just sent to show up then you can use the function append() to make it show at the end of the comment section this is the fastest way to do this rather than waiting for it to show from the database
So what is probably happening here is that you haven't used event.preventDefault() This will stop your submit button from reloading the page, which will allow your ajax code and your code posting the comment to finally get run.
http://api.jquery.com/event.preventdefault/
The idea behind preventDefault is that it stops the submit button from doing its default behavior, which is submitting a form and reloading the page.
can you change this
$("#submitComment").click( function() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
});
to
function onclicksth() {
$.post( $("#frmFilmComments").attr("action"),
$("#frmFilmComments :input").serializeArray(),
function(info){ $("#commentResult").html(info);
});
clearInput();
}
and change submitComment type to button? There is a better way to do this too:
//rough code including the submit and post data
$('form.frmFilmComments').on('submit', function() {
if(confirm('Do u want to input that field')){
fields-=1;
var obj = $(this),
url = obj.attr('action'),
method = obj.attr('method'),
data = {};
$("#hdnlstcount").val(fields);
//console.log(fields);
obj.find('[name]').each(function(index, value) {
var obj = $(this),
name = obj.attr('name'),
value = obj.val();
data[name] = value;
});
$.ajax({
url: url,
type: method,
data: data,
success: function(response2) {
//do sth with success response
}
});
return false; //disable refresh
clearInput();
}
});

Categories