How to call a function in a php file using jquery load? - javascript

I am trying to display the data i retrieve from the database but it is not being displayed. I have a function in the file getComments.php called "getComments(page)" page is just a integer parameter to choose that database. and as you can see that i need to call this function to print the users comments. I am trying to use "load" but it is not being successful i just want to call this function to load the comments on the page. thank you in advance.
<?php
use TastyRecipes\Controller\SessionManager;
use TastyRecipes\Util\Util;
require_once '../../classes/TastyRecipes/Util/Util.php';
Util::init();
function getComments($page){
echo "<br><br>";
$controller = SessionManager::getController();
$controller->getComments($page);
SessionManager::setController($controller);
}
and in my web page where i want to display it using java script, i tried the following
<div class="page" id="comments">
<p class="style">Comments</p>
<button class="btn" id="load-comments">See Previous Comments</button><br>
<br><br>
<?php
if(isset($_SESSION['u_id'])){
echo " <input type='hidden' id='uid' value = '".$_SESSION['u_uid']."'>
<input type='hidden' id='date' value = '".date('Y-m-d H:i:s')."'>
<textarea id='message'></textarea><br>
<button class = 'btn' type = 'submit' id = 'submitCom'>Comment</button>";
}
else{
echo "<p>Please log in to comment</p>";
}
?>
</div><br>
<script>
$(document).ready(function(){
$("#load-comments").click(function(){
document.getElementById('#comments').innerHTML =
$("#comments").load("../extras/getComments.php", getComments(1));
});
});
</script>

Just change your click handler to this:
$("#load-comments").click(function(){
$("#comments").load("../extras/getComments.php", { page: 1 }); //i also added where the elements are loaded
});
and in getComments.php (if practical, otherwise you might need to create a new PHP file which calls the getComments() function and call that from the click handler instead) add something like:
if (isset($_POST['page'])) {
getComments($_POST['page']);
// do any other necessary stuff
exit;
}

Related

Dynamically send javascript value via form

I don't know if it's possible, but I need to send some information across a form ou inside url come from checkbox value.
This code below is inside a products loop and create a checkbox on every products (product comparison approach).
In my case, it's impossible to make this code below across a form.
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
To resolve this point, I started to use an ajax approach and put the result inside a $_SESSION
My script to for the checbox value
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty create the list via ajax
if (chkArray.length !== 0) {
$.ajax({
method: 'POST',
url: 'http://localhost/ext/ajax/products_compare/compare.php',
data: { product_id: chkArray }
});
}
});
});
And at the end to send information on another page by this code. Like you can see there is no form in this case.
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
No problem, everything works fine except in my compare.php file, I have not the value of my ajax. I inserted a session_start in ajax file
But not value is inserted inside compare.php.
I tried different way, include session_start() inside compare.php not work.
My only solution is to include in my products file a hidden_field and include the value of ajax across an array dynamically, if it's possible.
In this case, values of hidden_fields must be under array and sent by a form.
This script must be rewritten to include under an array the chechbox value
without to use the ajax. How to insert the good code?
$(function() {
$('input[type=checkbox]').change(function() {
var chkArray = [];
$('#container').html('');
//put the selected checkboxes values in chkArray[]
$('input[type=checkbox]:checked').each(function() {
chkArray.push($(this).val());
});
//If chkArray is not empty show the <div> and create the list
if (chkArray.length !== 0) {
// Remove ajax
// some code here I suppose to create an array with the checkbox value when it is on true
}
});
});
and this code with a form
<?php
echo HTML::form('product_compare', $this->link(null, 'Compare&ProductsCompare'), 'post');
// Add all the js values inside an array dynamically
echo HTML::hidddenField('product_compare', $value_of_javascript);
?>
<div class="col-md-12" id="compare" style="display:none;">
<div class="separator"></div>
<div class="alert alert-info text-md-center">
<span class="text-md-center">
<button class="btn">Compare</button>
</span>
</div>
</div>
</form>
Note : this code below is not included inside the form (no change on that).
<?php
echo '<div><input type="checkbox" value="' . $products_id .'" id="productsCompare" title="Compare" onclick="showProductsCompare()" /> Compare</div>';
?>
My question is :
How to populate $value_of_javascript in function of the checkbox is set on true to send the information correctly inside compare.php
If my question has not enought information, I will edit this post and update in consequence.
Thank you.
You cannot pass JavaScript Objects to a server process. You need to pass your AJAX data as a String. You can use the JavaScript JSON.stringify() method for this...
$.ajax({
method: 'POST',
url : 'http://localhost/ext/ajax/products_compare/compare.php',
data : JSON.stringify({product_id: chkArray})
});
Once that has arrived at your PHP process you can turn it back into PHP-friendly data with PHP JSON methods...
<?
$myArray = json_decode($dataString, true);
// ... etc ... //
?>
See:
JSON # MDN
JSON # PHP Manual
Example: Form Submission Using Ajax, PHP and Javascript

Can't get my Javascript function to run more than once in a PHP foreach loop

I am trying to build a simple 'blog' that myself or a moderator can remove by calling a delete function. However, I only want the delete button to show for administrators. I created a function to validate the user, that is working fine. However, I am not familiar enough with Javascript to know whether to use window.onload or onopen or onchange, or how to attach the function to my Foreach loop to run for each blog post I have. When I have 10 blog posts, it only shows for the first (or last) post.
I have tried adding the "onload / onopen / onchange" commands to the body, to the foreach loop, and to my tags to see if it responds differently.
<script>
function ShowDelete()
{
var x = document.getElementById("Delete");
if (userid === "1") {
x.style.display="block";
}
else {
x.style.display="none";
}
}
window.onload = ShowDelete;
</script>
<?php foreach ($entries as $entry) : ?>
<?php if ($userid == 1) { ?>
<input type="submit" id="btnDelete" value="Delete Post" />
<?php } ?>
<?php endforeach; ?>
Ok Thank you all so much for the responses, I simply input the decision statement inside the loop to determine whether to show or skip. Thanks a ton!!!
You are creating an HTML input and then hiding it. Best practice is not to create the element in the first place based on your userid.
<?php foreach ($entries as $entry) : ?>
/* Check for userid here and create delete element if condition is met */
<?php endforeach; ?>
No need to call a function multiple times to set the style. In your onload event, capture all of the <input/> elements by class name and set your display style. Note that the id attribute must be unique, so the class attribute should be used instead of id.
const userid = "0";
window.addEventListener('DOMContentLoaded', () => {
let inputs = document.getElementsByClassName("Delete");
Array.from(inputs).forEach(input => {
input.style.display = userid === "1" ? "block" : "none";
});
});
<input type="submit" class="Delete" value="Delete Post" />
<input type="submit" class="Delete" value="Delete Post" />
<input type="submit" class="Delete" value="Delete Post" />
It may also be of benefit to take a look at this post regarding load listeners.

Ajax not firing in div populated by ajax

I have a div which is populated via an ajax request.
Within the div is a form which when completed should use the same type of ajax request to populate a further div. I have used the same method to create both but the second javascript does not run:
First one (which works):
<div class="content_text" id="searchbysurname">
<p><form name="searchbysurname">
<b>Search by Surname: </b><input class="inline" type="text" name="q">
<input type="submit"></form>
<script>
$('#searchbysurname form').submit(function(){
var data=$(this).serialize();
// post data
$.post('searchbysurname_test.php', data , function(returnData){
$('#resultstable').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
<div id="resultstable"></div>
Second one (which is in the resultstable div) that doesnt work:
<? require_once("dbcontroller.php");
$db_handle = new DBController();
$q = ($_POST['q']);
$employees=array();
$sql = "SELECT employees.employeeid, employees.firstname, employees.surname FROM employees where UCASE(employees.surname) LIKE UCASE('%".$q."%')";
$employees = $db_handle->runQuery($sql); ?>
<table class="invisible">
<?
if(isset($employees) && !empty($employees)){
foreach($employees as $k=>$v) {
?>
<tr><td><?php echo $employees[$k]["firstname"]; ?> <?php echo $employees[$k]["surname"]; ?> </td>
<td><div id="viewemployeedetails<? echo $employees[$k]["employeeid"]?>">
<form>
<input type="hidden" name="id" value="<? echo $employees[$k]["employeeid"]?>">
<input type="submit" value="View">
</form>
</div></td>
<div id="mainpart"><b></b></div>
<script>
$('viewemployeedetails<? echo $employees[$k]["employeeid"]?> form').submit(function(){
var data=$(this).serialize();
// post data
$.post('viewemployeedetails.php', data , function(returnData){
$('#mainpart').html( returnData)
})
return false; // stops browser from doing default submit process
});
</script>
I know it's not related to your question but you shouldn't be using the PHP short tag notation, it has been deprecated: https://softwareengineering.stackexchange.com/questions/151661/is-it-bad-practice-to-use-tag-in-php
Your first block of code is HTML with inline Javascript, which is an awful way to do things, you will get hard to debug errors if you insist on using Javascript in this way. You should be putting your Javascript in a separate file from the HTML and including it just before the final body tag. Ideally you should be using window.onload (or other similar methods, like a closure or jQuery's .ready() method) to ensure that DOM traversing elements of your script are only parsed after the DOM is fully loaded.
Your second block of Javascript code will never run because it doesn't exist when the browser parses the HTML. It's only injected later but Javascript doesn't work that way. You can inject javascript dynamically but not like that. You would have to do something like this:
var headID = document.getElementsByTagName("head")[0];
var newScript = document.createElement('script');
newScript.type = 'text/javascript';
newScript.src = 'http://www.somedomain.com/somescript.js';
headID.appendChild(newScript);
I took this code from here: http://www.hunlock.com/blogs/Howto_Dynamically_Insert_Javascript_And_CSS

JQuery: Post variable to the second file, and when the enter key pressed, the web will direct me to the first search result page

I created an instant search similar to google search using JQuery.
Q1.
The post to search.php using search function searchq() then print out the returned result works fine, but the createq() function doesn't work at all, it didn't triggered when I using alert() to test, any ideas on how to fix it so the variable txt could be post to create_object.php (which has been post successfully to search.php).
Q2
I want to create a function that allow the user to direct to the first search result(which is anchored with an url) when the enter is pressed, any idea how to achieve this? I tried something but it messed up.
Note that I didn't include the connect to database function here. Coz I think the database username and password setting would be different to yours.So please create your own if you want to test it. The mysql is set with a table is called "objects", and it has one column named "name".
Thanks in advance!
<html>
<!-- google API reference -->
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<!-- my own script for search function -->
<center>
<form method="POST">
<input type="text" name="search" style="width:400px " placeholder="Search box" onkeyup="searchq();">
<input type="submit" value=">>">
<div id="output">
</div>
</form>
</center>
<!-- instant search function -->
<script type="text/javascript">
function searchq(){
// get the value
var txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<div id=\"create\" onclick=\"creatq()\"><br>Not found above? Create.</div>");
});
}
else{
$("#search_output").html("");
}
};
function createq(){
// allert for test purpose
alert("hi");
$.post( "create_object.php",{creatVal:txt} );
}
</script>
</html>
PHP file (search.php)
<?php
if(isset($_POST["searchVal"])){
//get the search
$search=$_POST["searchVal"];
//sort the search
$search=preg_replace("#[^0-9a-z]#i","",$search);
//query the search
echo "<br/>SELECT * from objects WHERE name LIKE '%$search%'<br/>";
$query=mysqli_query($conn,"SELECT * from objects WHERE name LIKE '%$search%'") or die("could not search!");
$count=mysqli_num_rows($query);
//sort the result
if($count==0){
$output="there was no search result";
}
else{
while($row=mysqli_fetch_assoc($query)){
$object_name=$row["name"];
$output.="<div><a href='##'".$object_name."</a></div>";
}
}
echo $output;
}
?>
php file (create_object.php)
<?php
if(isset($_POST["createVal"])){
$name=$_POST["createVal"];
var_dump($name);
}
?>
Two questions in one!
Q1: The problem appears to be a misspelling in the onclick function:
onclick=\"creatq()\"
should be
onclick=\"createq()\"
Q2: Pressing enter will submit the form, so you use the submit handler to catch the enter press then redirect:
$(function() { //shorthand document.ready function
$('form ').on('submit', function(e) { //use on if jQuery 1.7+
e.preventDefault(); //prevent form from submitting
$url = $('#search_output div:first a').attr('href'); // find first link
window.location.href = $url; // redirect
});
});
(credit to this answer for most of the work)

Automatically update another page without refreshing

I have this problem on how I could automatically update my webpage without refreshing. Could someone suggest and explain to me what would be the best way to solve my problem? Thanks in advance
add.php file
In this php file, I will just ask for the name of the user.
<form id="form1" name="form1" method="post" action="save.php">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
save.php In this file, I will just save the value into the database.
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
$sql->execute();
studentlist.php In this file, i want to display the name I enter
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
Problem
When the two pages is open, I need to refresh the studentlist.php before i can see the recently added data.
thanks :D
You'll want to use ajax and jquery. Something like this should work:
add.php
add to the head of the document:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){//loads the information when the page loads
var saveThenLoad = {
url: "save.php",//the file sending data to
type: 'POST',//sends the form data in a post to save.php
dataType: 'json',
success : function(j) {
if(j.error = 0){
$("#student_info").html(j.info);//this will update the div below with the returned information
} else {
$("#student_info").html(j.msg);//this will update the div below with the returned information
}
}
}
//grabs the save.submit call and sends to the ajaxSubmit saveThenLoad variable
$("#save").submit(function() {
$(this).ajaxSubmit(saveThenLoad);
return false;
});
//grabs the submit event from the form and tells it where to go. In this case it sends to #save.submit above to call the ajaxSubmit function
$("#add").click(function() {
$("#save").submit();
});
});
</script>
<!-- put this in the body of the page. It will wait for the jquery call to fill the data-->
<div id="student_info">
</div>
I would combine save and studentlist into one file like this:
$return['error']=0;
$return['msg']='';
$firstname=isset($_POST['firstname'])? $_POST['firstname'] : '';
$lastname=isset($_POST['lastname'])? $_POST['lastname'] : '';
$sql="Insert into student (sno,firstname,lastname) values ('','$firstname','$lastname')";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error saving data';
}
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
if(!$sql->execute()){
$return['error']=1;
$return['msg']='Error retrieving data';
}
$output="The List of students <br></br>";
while($result=$sql->fetch(PDO::FETCH_ASSOC))
{
$output.="".$result['firstname']." ".$result['lastname']."<br></br>";
}
$return['$output'];
echo json_encode($return);
Does this need to be in three separate files? At the very least, could you combine add.php and studentlist.php? If so, then jQuery is probably the way to go. You might also want to use some html tags that would make it easier to dynamically add elements to the DOM.
Here's the combined files:
<form id="form1" name="form1">
<input type="text" name="firstname" id="firstname"/>
<input type="text" name="lastname" id="lastname"/>
<input type="submit" name="add" id="add" value="add"/>
</form>
The List of students <br></br>
<ul id="student-list">
<?php
//I assume you're connecting to the db somehow here
$sql="Select firstname, lastname from student";
$sql=$db->prepare($sql);
$sql->execute();
while($result=$sql->fetch(PDO::FETCH_NUM)) //this might be easier to output than an associative array
{
//Returns will make your page easier to debug
print "<li>" . implode(" ", $result) . "</li>\n";
}
?>
</ul>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$('#form1').submit(function(event){
event.preventDefault();
//submit the form values
var firstname = $('#firstname').val();
var lastname = $('#lastname').val();
//post them
$.post( "test.php", { firstname: firstname, lastname: lastname })
.done( function(data) {
//add those values to the end of the list you printed above
$("<li>" + firstname + ' ' + lastname + "</li>").appendTo('#student-list');
});
});
});
</script>
You might want to do some testing in in the $.post call above to make sure it was handled properly. Read more about that in the docs.
If you really need three files, then you'll might need to use ajax to do some sort of polling on studentlist.php using setTimeout to see if you have any new items.
The cheap-way is using a meta-refresh to refresh your page (or use JavaScript setInterval and ajax).
The more expensive way is having a Realtime JavaScript application. Look at Socket.IO or something like that.

Categories

Resources