PHP and Javascript functions - javascript

I am having issues with displaying my database products from a certain category when I click a link that calls a script function.
<li><button onclick="GPUclick()">GPU</button></li>
This is where I call my script to filter my products only to graphics cards, and I have that done with script / html like so:
function GPUclick() {
document.getElementById("parts").innerHTML = "<main> " +
" <img src='Images/760_ASUS.png' class='myClass'> " +
" <span class='myClass2'><ul><li>Asus GeFroce GTX 760</li><li>PCI-E 3.0, 2048MB VRAM</li><li>Price: £161.99</li></ul></span> "+
" <img src='Images/outOfStock.png' class='myClass3' alt='No stock'> " +
"</main>";
}
however now that I am using a database I need to filter through products that are being added into the database instantly.
I have a mysqli query that deals with the SQL:
$test = mysqli_query($conn, "SELECT * FROM products WHERE Category_ID = 2
I am just struggling now with printing anything out relating to that SQL command, I can do a in the javascript but that isn't really leading me to anything I can use or figure out without help and after looking for a while I can't find anything to help me either.
I appreciate any help / pushes in the right direction, thanks in advance.
I have tried adding "<?php echo $test['product_ID']?> " + to my JS function but that either outputs nothing or breaks the JS from even working.

You cannot use PHP in Javascript;
All PHP content must be in a PHP file and PHP is serverside, so all PHP is proceed on the Server.
In php use echo $test; or i would try this Php code:
<?php
echo "<script> var test = $test </script>"
?>

Related

automatically load dynamic content with ajax and php

I have a PHP chat application that automatically get messages from database and displays it, currently everything works fine but page must be manually reloaded to display new messages .. How do I implement JQuery ajax to get the messages or silently refresh the specific messages list div without refreshing the whole page? Here is my code (not the full code on the page but the main PHP part I want to use ajax on)
Some answers I read online specified that the PHP code must be on a separate file but Some of the functions and variables in the code below depends on the main file holding this code therefore making it useless if put in a separate file.
<?php
// Attempt select query execution
global $db;
$id = $_GET["id"];
$sql = "SELECT * FROM msg WHERE id='$id' ";
if ($result = $db->query($sql)) {
if ($result->rowCount() > 0) {
while ($row = $result->fetch()) {
echo '<div class="chat-messages-item ' . chattype($row['sender']) . '">';
echo '<div class="chat-avatar chat-avatar-lg circle"><img src="' . senderpic($row['sender'], 'thumbnail', '100', '100') . '" alt=""></div>';
echo '<div class="chat-messages-content">';
echo '<div class="chat-messages-bubble ' . $msg_visibility . '">';
echo '<p>' . $row['message'] . '</p>';
echo '</div>';
echo '<ul class="chat-messages-info">';
echo '<li>';
echo '<div class="chat-time chat-seen"><span>' . $row["time"] . '</span>';
echo '</li>';
echo '</ul>';
echo '</div>';
echo '</div>';
}
unset($result);
} else {
echo "<p class='lead'><em>No Chat</em></p>";
}
} else {
echo "ERROR: Could not able to execute $sql. " . $mysqli->error;
}
Thanks
[EDIT]
What i've tried :
1. Moving the code above into a separate PHP file and using jquery to to get the page with the following js code but nothing appears and no errors displayed. if i open the page in browser it displays the list of all messages
function update() {
$.get("aj/messages.php", function(data) {
$("#allmessages").html(data);
window.setTimeout(update, 10000);
});
}
here is the page structure
- Message.php (the main message page that displays other chat information like contacts, messages list, messages, send message input etc)
aj/msg.php (a php page that gets all the messages from database and wraps it in style/css/html which is also the php code above and expected to be inside a div with the id="allmessages" located inside Message.php)
As you mentioned, it is a good practice to separate your PHP Code and your HTML/JavaScript Code. Yes, this may mean you have to write more PHP Code, yet if PHP Scripts must use the same code snippet, this is where PHP include and include_once can be used so that you can store specific functions in one script and them import them to other scripts. Please see:
https://www.php.net/manual/en/function.include.php
Currently, there is not enough of an example to be able to properly answer your question. I would suggest that you either create a more functional PHP Script that can accept new Chat input or another that can show the current chat transcript from the Database.
In this use case, each member of the chat must send new data to the database and then periodically get/refresh their view of the transcript. You can send new data to the database at any time and then based on a specific refresh rate, look for differences in the transcript. So your JavaScript will have a few function. Something like
startChat()
sendMessage()
getMessages()
endChat()
These will send data to the PHP Script and the PHP Script may give a response. This can all be done with AJAX. AJAX is the use of HTTP GET or POST along with JavaScript. This is basically how a Client Side Script language like JavaScript can talk to a Server Side Scripting language like PHP. PHP is processed when the HTTP request is handled by the Web Server and once the data is sent to the browser, PHP can no longer interact with it, this is why it's a pre-processor. JavaScript can only run in the browser and is processed after all the data from the server is received by the browser.
So if you have some HTML like:
<div class="chat-window">
<div class="transcript">
</div>
<div class="user-input">
<input type="text" /> <button>Send</button>
</div>
</div>
You can use JavaScript to perform tasks when the User types in text and clicks the button. One of those tasks can be to collect the text entered by the User and send it to the PHP Script to be added to the Database. Another task can be to update the field if there are any new messages in the Database since the last time the script checked.
Using jQuery Framework for JavaScript, it might be something like:
function sendMessage(user, txt){
$.post("chat_input.php", { u: user, msg: txt });
}
This creates a HTTP POST call to a PHP Script with a payload of info, such as the User and some Text. You'll need to collect this information from the HTML based on a specific Event.
$(".user-input > button").click(function(){
sendMessage("jsmith", $(this).parent().find("input").val());
});
This bit of jQuery binds a anonymous function as a callback to the click event. When the User clicks the button, it runs that code in the function.
The PHP Code might be something like:
<?php
$user = $_POST['u'];
$txt = $_POST['msg'];
include_once 'db_conn.php';
$stmt = $mysqli->prepare("INSERT INTO 'chat' VALUES (?, ?)");
$stmt->bind_param("ss", $user, $txt);
$stmt->execute();
$stmt->close();
?>
As you can see, this is very rudimentary and will not answer your overall question. You must do a lot of research and I would advise you find example PHP/jQuery Chat example that you can learn from or begin taking some JavaScript/jQuery Tutorials.
See More:
https://api.jquery.com/jQuery.post/
https://api.jquery.com/click/
https://api.jquery.com/category/selectors/
Update
If your PHP Code is setup to collect some data and "send" it back to an AJAX script, then you would prepare it like any other PHP Page, and output the data to the page in some fashion.
<?php
$results = new array();
/* Assuming connection to DB */
/* Assuming SQL Query and result set is now in $results */
header('Content-Type: application/json');
echo json_encode($results);
?>
When you navigate to this page, you will see the collected data in JSON format. Something like:
[
{
"sender": "jsmith",
"message": "Hello World!",
"time": "12/27/2019 10:28:01"
},
{
"sender": "ssmith",
"message": "shut up john",
"time": "12/27/2019 10:28:12"
}
]
When AJAX sends a request to this script, it will get the data back and can then iterate each item in the array, create HTML for it as needed. You can use HTML or Text or XML too, I just use JSON when possible.
In jQuery, this function might look like:
function getMessages(){
var lastMessage = $(".chat-messages-item:last .chat-time").text().trim();
$.get("chatmessages.php", function(data){
$.each(data, function(i, msg){
if(lastMessage < msg.time){
var newMsg = $("<div>", {
class: "chat-messages-item " + chattype(msg.sender),
}).insertAfter($(".chat-messages-item:last"));
var av = $("<div>", {
class: "chat-avatar chat-avatar-lg circle"
}).appendTo(newMsg);
$("<img>", {
src: senderpic(msg.sender, 100, 100),
class: "thumbnail"
}).appendTo(av);
$("<div>", {
class: "chat-messages-content"
}).html("<p>" + msg.message + "</p>").appendTo(newMsg);
}
});
});
}
setTimeout(getMessages, 10000);
This is just an example based on your code.

Server error 500 in PHP

So today I have another small little issue with my PHP, that is causing me to get a server error. You see, I have this javascript function:
$.post('script.php', { limit: str }, function(result) {
console.log(result);
});
which of course makes a call to my php file:
require_once("../data/db-settings.php");
require_once("../data/file.php");
global $pdo;
$list = array();
$limit = $_POST["limit"];
chop($limit, ";");
$stmt = $pdo->prepare("SELECT cust_id, cust_addr FROM project WHERE " . $limit . " = cust_id");
$stmt->execute();
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$list[] = $row;
}
echo $list;
The point of the php is to grab some information from a database that a user can dynamically change and use. The issue, I'm assuming, is with how I'm using PDO, because the code I'm using is in working order in another section. I also know that my function call is sending data and working properly, because when I check for just what I send, it sends properly.
Thanks for any help guys.
Check your query FROMproject can not be together.
Your query should look like this:
$pdo->prepare("SELECT cust_id, cust_addr FROM project WHERE " . $limit . " = cust_id");
It is an unobvious error!
So you step by step following the : http://pcsupport.about.com/od/findbyerrormessage/a/500servererror.htm
PDO doesn't throw Internal server error. Must be require_once.
checkout db-settings.php and file.php files. Require_once throws 500 error if it can't find files.
If the paths are correct, then check out included files.
proper way: check your log files.

echo Javascript Function to be held by Simple Pie function on Php not working

this is my first attempt to ask here, hoping for your kind attention =) so here it is, I'm making a simple news aggregator site that will shows random news base on the site viewer location (COUNTRY). I'm using geoplugin and javascript to locate them and store their credentials in a variable that I will use to pass in php to generate specific NEWS, the problem is Simple Pie is not recognizing it, here's my code
<?php
$rssLocal = "<script> document.write('http://samplenews.org/' + geoplugin_countryCode().toLowerCase() + '/rss.xml') </script>";
$rssLocalLink = "http://samplenews/ph/rss.xml";
echo $rssLocal . ' ORIG <br />';
echo $rssLocalLink;
$feed = new SimplePie($rssLocal);
$feed->set_feed_url($rssLocalLink);
$feed->enable_cache(true);
$feed->set_cache_location(storage_path().'/cache');
$feed->set_cache_duration(60*60*12);
$feed->set_output_encoding('utf-8');
$feed->init();
?>
by the way, those two echo return the same result like this
http://samplenews.org/ph/rss.xml ORIG
http://samplenews.org/ph/rss.xml

calling a php function, within html code, within a php echo statement

Ok so ive looked at AJAX and to be honest im having trouble understanding how i am going to apply it to my code. Il go into more depth about what i am trying to do, and maybe someone can help me better understand how to incorporate an AJAX call.
So i have one function, called add_signups which takes in 3 parameters and inserts some data into a mysql table.
function add_signup($society, $student_email, $event) {
$member_fields = array('name','student_num','student_email',);
$fields = '`' . implode('`, `',($member_fields)) . '`';
$query = mysql_query("SELECT $fields FROM `$society members` WHERE `student_email`='$student_email'");
$elems = mysql_fetch_assoc($query);
array_walk($elems, 'array_sanitize');
$data = '\'' . implode('\', \'', $elems) . '\'';
$result = mysql_query("INSERT INTO `$event` ($fields) VALUES ($data)");
}
I have another method, called get_names which prints a list of email addresses. I am trying to call the add_signup method once a user clicks on one of the email addresses, this will insert that users email address, along with some other info into the table.
function get_names($society, $event){
$records= mysql_query("SELECT `student_email` FROM `$society members` ORDER BY `student_email`");
while($emails = mysql_fetch_assoc($records)){
echo ' <li style="cursor:pointer;" onclick="' add_signup($society, $emails['student_email'], $event) '); ">' .$emails['student_email'] . "</li>";
}
}
What i dont understand is where to put what in terms of using an ajax call. Im thinking i need to put the add_signup() method in a seperate php file, then in the html file within <script> tags put the following
function jsfunction(){
$.ajax({
type: "POST",
url: "add_signupmethod.php",
data: { "what to put here??" },
success: " what to put here? "
});
}
obviously i would need to change the onclick event to call the js function but is that anywhere near correct?
Or do i even need to use ajax and is there a much easier way of doing it? Ive been stuck on this for almost two days now, the frustrating thing is i know that the add_signup() function works as i tested it outside of the otherfunction. Would greatly appreciate anyone helping me out with this.
Original message
echo ' <li style="cursor:pointer;" onclick="' add_signup($society, $emails['student_email'], $event) '); ">' .$emails['student_email'] . "</li>";
Can anyone help with this? Im trying to call a php function once a list element is clicked, only the html code is being generated itself by another php function in an echo statement.
I keep getting syntax errors so is it as simple as that or is it even possible at all to do this? if not, what could i do to get the result i want? the actual error code is
Parse error: syntax error, unexpected 'add_signup' (T_STRING), expecting ',' or ';' in C:\Users. . .
You're missing the dot (concatenation) before and after your add_signup method.
echo ' <li onclick="document.write(' . add_signup($society, $names['name'], $event) . '); ">' . $names['name'] . "</li>";
That will get rid of your syntax error. However it will also execute the add_signup method immediately, and not when the button is clicked.
To call this when the button is clicked, start looking into how to make Ajax calls client-side.

DELETE query onclick automized

Having a slight problem here. I'm trying to create an admin side function to delete FAQ's, and despite the fact that I got a script working, I need to figure out how to automate a [WHERE clause] per added question.
To describe it, every question gets posted and has an ID in the database. I want to delete on that ID, but per question I add the
DELETE FROM faq [WHERE faq_id=#]
My current code:
$sql = "SELECT question, answer FROM faq";
$queryresult = mysql_query($sql) or die (mysql_error());
while ($faqResult = mysql_fetch_array($queryresult)){
$faqQuestion = $faqResult['question'];
$faqAnswer = $faqResult['answer'];
echo "<p class='faqQuestionAdmin'>$faqQuestion</p>" .
"<p class='faqAnswerAdmin'>$faqAnswer</p>" .
"<a class=faqDelete>X</a>";
}
if(mysql_num_rows($queryresult) <= 0) {
echo("<div><p>No Questions available</p></div>");
}
mysql_free_result($queryresult);
mysql_close($conn);
that serves as the deleting button. I was thinking a get function, but does anyone know how can I do this? Currently the only columns in the database for each question is the ID, question, and answer.
Thanks in advance!
If you have in the database:
Id | Question
--------------------------
1 | This is a question
2 | This is question 2
And when you render your page and have a own delete page
<?php
//You have get the questions by a query and stored in the local $sqlResults
echo "<table>
<tr><th>Id</th><th>Question</th><th>Delete</th></tr>";
foreach($sqlResults as $result)
{
echo "<tr><td>" . $result["id"] . "</td><td>" . $result["question"] . "</td>";
echo "<td><a href='your-domain.com/delete.php?id=" . $result["id"] . "'>X</a></td></tr>";
}
echo "</table>";
?>
And when you have a javascript function which makes a AJAX post call, make the href like:
yourDeleteJavascriptFunction(" . $result["id"] . ")
In both cases you render a list, and per item you add the id of the question. You can get the value when you receive the id and delete only that question by his id ;-)
If you want to avoid AJAX, you could simply put a link in your anchor tag to php file with GET variable in it:
X
Than in deleteFAQ.php you use
$id = $_GET['id'];
$query = "DELETE FROM faq WHERE faq_id=$id";
best way you can use ajax call and call php file and pass id to that file and write delete query in that php file

Categories