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

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.

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.

$.getJSON to a php with include_once fails but it did the work

I've a PHP webservice and when I call it with $.getJSON it goes to the .fail callback.
The problem appears only when i do an include_once at PHP. If I copy/paste what the included file does to the main php it works fine.
The responsetext is what I expected (a JSON with the data asked) and the status is 200, but inside the .fail callback.
It's strange. Anyone knows if there's any problems using include_once?
Then piece of PHP code is:
$bCarregat = include_once("sql/". $sConsulta .".php");
and if i replace it with:
$sSqlBase = "SELECT usuari, nom, moduls";
$sSqlBase .= " FROM www_usuari";
$sSqlBase .= " WHERE 1=1";
if (isset($aRestr['USUARI']) AND $aRestr['USUARI'] != "") {
$sSqlBase .= " AND usuari = '". str_replace("'", "''", $aRestr['USUARI']) ."'";
}
it works.
I solved the problem saving the secondary php file (the included) in UTF-8 without BOM.
I didn't know about the existence of different UTF-8 formats, but a little beginning char at response text (\ufeff) made me suspect.
I apreciate all your frustrated attempts to help me ;-P they have not been i vain.

In WordPress how do I pass multiple variables into the URL and retrieve them?

For some reason I can only retriever the first variable, in this instance, "product_category" out of the URL http://localhost/coffeesite/?product_category=coffee&brand=bourbon .
I'm outputting javascript to confirm that I've set the variable, but again, only coffee will be alerted, and not brand. I'm using WordPress's 'get_query_var'. See code below:
<?php
echo '<script> product_category = "' . get_query_var('product_category') . '";
brand = "' . get_query_var('brand') . '";
alert(product_category);
alert(brand);
</script>';
?>
Any help would be appreciated - I'm struggling to solve it!
Since you are testing, maybe you could test the php directly? The function get_query_var is just a wrapper for the generic php array $_GET. You should have these values available at $_GET['product_category'] and $_GET['brand']. But instead of assuming everything is where it is supposed to be, why not check what you actually have?
<?php
add_settings_error("var-test", "var-test", implode(", ", array_keys($_GET)));
?>
Disclaimer: I am a Drupal developer, not Wordpress, but they are both php.
I am using the documented message tool here, for a little cleaner php code.
https://codex.wordpress.org/Function_Reference/add_settings_error
You could still use your javascript if you would like:
<?php
echo '<script> alert( '. implode(", ", array_keys($_GET)) .');
</script>';
?>
Second possibility. The reason for using a wrapper function instead of the raw core is for what it provides in that wrap. My normal assumption is sanitation and security filters, which are poor for testing but essential for production environments. However, with a little bit of reading on the function you are using, it says it only returns values for known query objects and if you are using custom variables in the url you should register them. https://codex.wordpress.org/Function_Reference/get_query_var
Have you registered "brand"?

PHP and Javascript functions

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>"
?>

Concatenate php variables and symbol to javascript function in php echo

I finally got the php variables to pass to the javascript function but they are passing as multiple and getting a warning.
Use of undefined constant app_name - assumed 'app_name'
How can i define the variables?
echo('<li> <a href="#" onClick="runthis(\''.str_replace("'", "\\'", $row[activity]).'\',\''.str_replace("'", "\\'", $row[app_name]).'\');">');
Javascript
function runthis(activity) {
alert(activity);
//$('#live-area').load('../assets/php/multibox.php?id=' + activity);
}
I am trying to concat $row[activity] and $row[app_name] with /
my php explodes on / and breaks into variables
UPDATE
Here is what im doing with the data.
if (isset($_GET['id'])) {
$app = $_GET['id'];
$array2 = explode('/', $app);
$activity = $array2[0];
$app_name = $array2[1];
$SQL1 .= "WHERE activity = '$activity' ";
}
I don't think im handling the string properly.
What should this look like?
I updated the echo onClick to this
echo ('<li> <a href="#" onClick="runthis(\'' . $row['activity'] . '/' . $row['app_name'] . '\')">');
It passes correctly to javascript but when $_GET loads it i get no results
You're dumping PHP output into Javascript context. Use json_encode() to do this properly:
echo '<li>..... ', json_encode($row['activity']), '</li>';
As it stands right now, your array keys aren't quoted, which'll probably cause PHP to issue various warnings, and those warnings will get output in your JS code, causing syntax errors.
json_encode() will take care of ALL the necessary quoting/escaping for you. It'll also be far more readable/maintainable than the abomination you've come up with.
comment followup, split onto 3 lines for a bit more legibility:
echo '<li> <a href="#" onClick="runthis(';
echo json_encode("{$row['activity']}/{$row['app_name']}");
echo ')">';
You're getting Use of undefined constant app_name - assumed 'app_name' because you're saying $row[app_name] instead of $row['app_name'].

Categories