I cannot get the AJAX code to accept the value from "onclick" - javascript

I apologize for the grammatical errors in my writing, I am not very good in language at all. Conceptually, I have some knowledge in software however, I have never written a line of code...
MY SOFTWARE DESCRIPTION:
I have thousands of songs/videos parked in my computer. Computer audio is connected to AV receiver and video is connected to a TV (for video). I'd like to write a piece code that I can play the music/video from the mobile devices, remotely. Here is my sequence for playing song:
use XAMMP, create the database holding the list of song/video names
completed and working
create html page, connect to the database, read, and display song names
completed and working
when click on the song name, a SongID is passed to Ajax code for posting SongID back to the server and then update the database with PlayID
I cannot get Ajax code working here!
other code will read PlayID from the database and play the song via VLC player
Any help would be appreciated.
<!DOCTYPE html>
<html>
<body>
<div id = "SongList">
<?php
// Connect to mysql database
$servername = "localhost";
$username = "NangHa";
$password = "";
$dbname = "ListSong";
$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// retrieve song list from mysql database table nangha_SongList
$sql = "SELECT * FROM nangha_SongList";
$result = $conn->query($sql);
if ($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$song = (string)$row["SongID"] . " - " . $row["SongName"];
?>
<!-- display list of songs with the onclick to call addSongFunction
and pass the song id - $row["SongID"]
-->
<p id = "<?php echo $song;?>" onclick="addSongFunction(<?php echo $row["SongID"];?>)"><?php echo $song;?></p>
<?php
}
}
// close the database connection
mysqli_close($conn);
?>
<script>
function addSongFunction(SongID){
//convert song id to integer for testing
var songID_STR = SongID.toString();
var ID_SONG = SongID;
// pass song id string to SongSearch div for testing
document.getElementById("SongSearch").innerHTML = songID_STR;
// display song id
alert(+ ID_SONG);
// SO FAR IS GOOD UP TO THIS POINT
// JUST DON'T KNOW HOW TO GET AJAX WORKING
$.ajax({
type: "POST",
data: {
songID: ID_SONG
},
url: "UpdateKaraoke.php",
dataType: "json",
async: true,
beforeSend: function(){
alert(good);
$(".ajaxTest").text("Trying to update ...");
},
success: function(data){
alert(+ data.a);
}
});
}
</script>
</div>
</body>
</html>

Related

Forms not rendering from database

I am using formbuilder plugin (https://formbuilder.online/) in jquery and I am trying to create a php application that stores forms in mysql database for a user. I am not able to display the forms on back from database to the html. Form data is in JSON.
I have tried a lot of different things and I am running out of ideas. Any suggestions would be helpful. I just need the right direction to think.
PHP file (form.php)
$dbhost = 'localhost';
$dbuser = 'abc';
$dbpass = 'password';
$dbname = 'xyz';
$conn = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
$sql = "SELECT id, code FROM data";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo $row["code"];
}
} else {
echo "0 results";
}
mysqli_close($link);
Jquery File
$('ul li a').click(function (e) {
$.post("./form.php", function (text) {
toggleEdit();
var renderedForm = $('.render-wrap');
formRenderOpts = {
dataType: 'json',
formData: text
};
console.log(text);
renderedForm.formRender(formRenderOpts);
});
});
So, I am getting all the entries for JSON in console. But I am looking for single entry. For example, lets say I have 2 forms stored in database I want to display 1st form on the website. Instead I am not getting anything displayed. But I am getting all the entries in JSON format in console. I new to PHP and I think that is why I am not able to figure this out.

Creating Javascript array via php

After spending an embarrassing number of hours on this, I still can't figure out an answer. I have a Javascript/HTML program that has a large dynamic table in it with lots of buttons in the cells of the table. I'd like to send the user's selections of buttons to a database when the user is finished with the page. I will then use those in the receiving php program to display a graph. I've got all of the values of the buttons into a Javascript array, so now I'd like to send the entire array and then use them as a Javascript array in the new program. Every time I try this, I get no results. Here is an example based on what I've found on stackoverflow:
Sending program:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
</head>
<script>
var ourObj={};
ourObj.data="4";
ourObj.arPoints = [{'x':1, 'y': 2},{'x': 2.3, 'y': 3.3},{'x': -1, 'y': -4}];
$.ajax({
url: 'testb2.php',
type: 'post',
data: {"points" : JSON.stringify(ourObj)},
success: function(data) {
alert("success");
}
});
</script>
</html>
Receiving php program:
<?php>
// Test if our data came through
echo "starting";
if (isset($_POST["points"])) {
// Decode our JSON into PHP objects we can use
$points = json_decode($_POST["points"]);
// Access our object's data and array values.
echo "Data is: " . $points->data . "<br>";
echo "Point 1: " . $points->arPoints[0]->x . ", " . $points->arPoints[0]->y;
$servername = "localhost";
$username = "xxx";
$password = "yyy";
$dbname = "zzz";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$sql = "
INSERT INTO FootprintAction(UserID, ActionValue, fpID)
VALUES (?, ?, ?);
";
if ($stmt = mysqli_prepare($conn, $sql)) {
mysqli_stmt_bind_param($stmt, "iss", $points->data, "1", "1");
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
} else {
//echo "no result from attempt to insert people into fpAction". "<br>";
//echo $sql;
}
}
?>
What I get is a blank screen from the sending program with only an alert saying "success" (i.e., no answer from the receiving program) and no insertion into the database.
Can you suggest what I am doing wrong? Or even better, is there a simple way using php to get a javascript array from a client-side program to a server-side program? The array I'm trying to send is a set of string data, without labels; here's a row of the array:
actions[ 5] = new Array( "Install Photovoltaic (Solar) Panels","6.33","1020","33121","0","25","149.8","0","0","0","1","1","Photovoltaic (solar) systems allow you to produce green electricity on your own rooftop. Vendors often offer both purchase and lease options. ","3","1.5","10","5.75","0");
I'd like to end up with a Javascript array in the receiving program identical to that in the sending program.
Thanks!!!

Json dynamic display vs server ressources

I'm aiming to display dots with javascript by their coordinates. Each person click on an image, (X,Y) will be stored in the database. On the same image will be displayed all dots, when a person is visualing the image with dots and another person will submit new dot, this last will appears because array_x and array_y tabs will be refreshed every 1s.
The question is : is it the best way in terms of using server ressources of doing that ? suppose i've 1000 persons that will participate to this study, that signify that for one person there is at least one request every 1s. Suppose that one person will spend 30s, that will be a huge amount of requests.
I am afraid to have a server breakdown due to multiple requests. Is it a way more guaranteed than this one ?
My js :
window.setInterval(loadNewPosts, 1000); //load simultaneous choice in 1 second
function loadNewPosts(){
$.ajax({
type: "GET",
cache: false,
dataType: "json",
url: "latest.php",
data: "current_id=" + current_id +"&nextType=" + nextType,
success: function(data) {
for (var i = 0; i < data['array_x'].length; i++) {
array_x.push(data['array_x'][i]);
array_y.push(data['array_y'][i]);
}
}
});
}
my php latest.php :
$servername = "";
$username = "";
$password = "";
$dbname = "";
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
$current_id = intval($_GET['current_id']);
$Type = (string)$_GET['nextType'];
$sql = "SELECT * FROM `table` WHERE id > $current_id and Type='".$Type."'";
$result = mysqli_query($conn, $sql);
$array_x= [];
$array_y= [];
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
array_push($array_x,$row["X"]);
array_push($array_y,$row["Y"]);
}
} else {
echo "";
}
mysqli_close($conn);
// return the posts as a JSON object
header('Content-Type: application/json');
$data=array(
'array_x' => $array_x,
'array_y' => $array_y
);
echo json_encode($data);

PHP code not returning correct MySQL result

I'm querying a set of data from MySQL on a hosted server. When I did it on my local machine, it worked fine, but on the hosted server, it's not returning anything. The weird thing is, when I use this GUI for the hosted environment to run the same query, it does return the results.
So here are some codes, etc.
This is index.php:
<?php
$servername = "username.db.theservername.ether.com";
$mysqllogin = "username";
$mysqlpassword = "thepassword";
$dbName = "StepsMath";
$conn = new mysqli($servername, $mysqllogin, $mysqlpassword, $dbName);
if($conn->connect_error){
die ("connection failed: " . $conn->connect_error);
echo "connection failed.";
}
$set_name = 'test_set';
$query = "select word, definition from word_list where set_name = '$set_name'";
$result = $conn->query($query);
$conn->close();
// *********************************************
echo $query; // <-------- *******this prints the query*******
// *********************************************
$result = mysqli_fetch_array($result);
?>
<!DOCTYPE html>
<html lang="en"><head>
<title>this is a title</title>
<script type="text/javascript">
var json = '<?= json_encode($result) ?>';
var word_list = JSON.parse(json);
console.log(word_list); //line 24
console.log(json); //line 25
function getUserId(){
return '<?= $user_id ?>';
}
if(!getUserId()) window.location = 'login.html';
</script>
</head>
<body>body stuff</body>
</html>
Table word_list only has three columns: word, definition, and set_name
The above code is supposed to return rows of words and definitions. Instead, as I check in the browser console, it returns the following:
{"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null}
This is the query that runs:
select word, definition from word_list where set_name = 'test_set'
If I copy that exact query and run it in the MySQL GUI in the hosted server,
the following is returned:
So to summarize the question, why is there a discrepancy in the result between the GUI and the code??
change this line:
$result = mysqli_fetch_array($result);
to this:
while ($row = mysqli_fetch_assoc($result)) {
$res[] = $row;
}
var_dump($res);
The information you previously got: {"current_field":null,"field_count":null,"lengths":null,"num_rows":null,"type":null} are all mysqli_result properties.
Read this, it will help you uderstand what you did wrong:http://php.net/manual/en/class.mysqli-result.php

Using ajax to display new database inputs without refreshing the page

I am using ajax to post comments to a certain page, I have everything working, except for when the user posts a comment I would like it to show immediately without refreshing. The php code I have to display the comments is:
<?php
require('connect.php');
$query = "select * \n"
. " from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '$s_post_id' ORDER BY comments.id DESC";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$c_comment_by = $row['comment_by'];
$c_comment_content = $row['comment_content'];
?>
<div class="comment_box">
<p><?php echo $c_comment_by;?></p>
<p><?php echo $c_comment_content;?></p>
</div>
<?php } ?>
</div>
</div>
<?php
}
}
and the code I have to post comments is:
<?php
$post_comment = $_POST['p_post_comment'];
$post_id = $_POST['p_post_id'];
$post_comment_by = "Undefined";
if ($post_comment){
if(require('connect.php')){
mysql_query("INSERT INTO comments VALUES (
'',
'$post_id',
'$post_comment_by',
'$post_comment'
)");
echo " <script>$('#post_form')[0].reset();</script>";
echo "success!";
mysql_close();
}else echo "Could no connect to the database!";
}
else echo "You cannot post empty comments!"
?>
JS:
function post(){
var post_comment = $('#comment').val();
$.post('comment_parser.php', {p_post_comment:post_comment,p_post_id:<?php echo $post_id;?>},
function(data)
{
$('#result').html(data);
});
}
This is what I have for the refresh so far:
$(document).ready(function() {
$.ajaxSetup({ cache: false });
setInterval(function() {
$('.comment_box').load('blogpost.php');
}, 3000);.
});
Now what I want to do is to use ajax to refresh the comments every time a new one is added. Without refreshing the whole page, ofcourse. What am I doing wrong?
You'll need to restructure to an endpoint structure. You'll have a file called "get_comments.php" that returns the newest comments in JSON, then call some JS like this:
function load_comments(){
$.ajax({
url: "API/get_comments.php",
data: {post_id: post_id, page: 0, limit: 0}, // If you want to do pagination eventually.
dataType: 'json',
success: function(response){
$('#all_comments').html(''); // Clears all HTML
// Insert each comment
response.forEach(function(comment){
var new_comment = "<div class="comment_box"><p>"+comment.comment_by+"</p><p>"+comment.comment_content+"</p></div>";
$('#all_comments').append(new_comment);
}
})
};
}
Make sure post_id is declared globally somewhere i.e.
<head>
<script>
var post_id = "<?= $s_post_id ; ?>";
</script>
</head>
Your new PHP file would look like this:
require('connect.php');
$query = "select * from comments inner join blogposts on comments.comment_post_id = blogposts.id WHERE blogposts.id = '".$_REQUEST['post_id']."' ORDER BY comments.id DESC";
$result = mysql_query($query);
$all_comments = array() ;
while ($row = mysql_fetch_array($result))
$all_comments[] = array("comment_by" => $result[comment_by], "comment_content" => $result[comment_content]);
echo json_encode($all_comments);
Of course you'd want to follow good practices everywhere, probably using a template for both server & client side HTML creation, never write MySQL queries like you've written (or that I wrote for you). Use MySQLi, or PDO! Think about what would happen if $s_post_id was somehow equal to 5' OR '1'='1 This would just return every comment.. but what if this was done in a DELETE_COMMENT function, and someone wiped your comment table out completely?

Categories