Not receiving dynamically generated form data - javascript

i am creating a form through php html and ajax that is specific for each row of a database table. I send the form data through ajax to another page which then takes that form data and uses it to pull data from another database based upon the results given and displays them.
I am fairly sure the problem is either with my select statement on the recipedisplay.php page or my syntax is wrong on how to echo out a returned variable.
select.php
<?php <script>
$('.button').click(function (e){
e.preventDefault();
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'pages/recipes/recipedisplay.php',
data: $('#f'+id).serialize(),
success: function(d){
$('#infodisplay').html(d);
}
});
});
</script>
<div id=\"a".$row['id']."\">
<form id=\"f" . $row['id'] . "\">
<input type=\"hidden\" name=\"recipeid\" id=\"recipeid\" value=\"" . $row['id'] . "\">
<div id=\"reciperesultbutton\" class=\"button\"><div id=\"centering\">" . $row['name'] ." </div></div>
<div id=\"reciperesulttext\"> " . $row['id'] ." " . $row['longdesc'] ."</div>
</form>
<br>
</div>
";
}
?>
recipedisplay.php
<?php
$con=mysqli_connect("localhost","test","test","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
$id = mysqli_real_escape_string($con, $_POST['recipeid']);
$sql= "SELECT * FROM recipes WHERE 'id' ='".$id."'";
$row = mysqli_fetch_array($sql);
$name = $row['name'];
$longdesc = $row['longdesc'];
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
echo " fail ";
echo " . $name . ";
};
echo " . $id . ";
echo " work ";
echo " . $longdesc . ";
echo "$row[name]";
mysqli_close($con);
?>

The problem is in :
$row = mysqli_fetch_array($sql);
because mysqli_fetch_array() takes mysqli_query() result not your $sql query
So try to run your query first by this code :
mysqli_query($con,$sql);
$row = mysqli_fetch_array($mysqli_query);
Also you can use mysqli_fetch_assoc() that takes mysqli_query() too as a parameter

Related

I have a single div and it needs to be duplicated dynamically

I have a single div and a unknown number(say n) of rows of data. i need to show that data on my html cards
and these cards are to be generated dynamically by the output value(n).
say if i have 10 rows of data.my div element needs to be created 10 times and each row data is to be displayed on each div
by the way i am using PHP for backend.
here is my codes
This is my div
<div class="row">
<div class="column">
<div class="card">
<h1><?php echo"$value"; ?></h1>
<h3><?php<?php echo"$description";?></h3>
</div>
</div>
</div>
and this is my php code
<?php
$conn=new mysqli("localhost","root","","programmingpioneers");
if(!$conn)
{
echo "connection_failed";
}
else{
//echo "sucess";
}
$query= "select title,description from problems where difficulty='hard'";
$result=mysqli_query($conn,$query);
$row=mysqli_fetch_array($result);
if (mysqli_query($conn, $query))
{
echo "sucess<br>";
while ($row=mysqli_fetch_array($result)) {
$title=$row[0];
$description=$row[1];
echo "$title <br> $description";
}
}
else {
echo "Error: " . $query . "<br>" . mysqli_error($conn);
}
?>
if i try to but my div inside
echo"$title <br>$description";
it is throwing the following error
Parse error: syntax error, unexpected 'row' (T_STRING), expecting ';' or ',' in C:\xampp\htdocs\myapp\useless.php on line 19
Use loop in the div you want to have again and again.Please check the code if it works for you.
enter image description here
enter image description here
Without having all your data available I'm unable to test it, but this should be the correct way of doing it. I left comments in the code and removed a bunch of syntax errors that you made:
<?php
// Create MySQLi object
$conn = new mysqli("localhost","root","","programmingpioneers");
// Verify MySQL connection
if ($conn->connect_errno) {
echo "Failed to connect to MySQL: (" . $conn->connect_errno . ") " . $conn->connect_error;
}
// Query
$query = "SELECT title,description FROM problems WHERE difficulty = 'hard'";
// Run query
if($result = $conn->query($query)) {
// Loop through query results
while ($row = $result->fetch_assoc()){
echo "<div class='row'>";
echo "<div class='column'>";
echo "<div class='card'>";
echo "<h1>". $row['title'] ."</h1>";
echo "<h3>". $row['description'] ."</h3>";
echo "</div></div></div>";
}
// Output query errors
} else {
echo "Failed to select title, description: (" . $conn->errno . ") " . $conn->error;
}
// Close the MySQLi connection
$conn->close();
?>

Multiple form action button in PHP

I have two form action buttons used in one of my php pages. When I click on first button, the second one is automatically loading. I am not PHP developer, so I do not know how to make button work separately. My form action button is like below:
//first button
<?php
echo
"<form action='' method='post'>
<input type='submit' class='btn btn-default' name='use_button' value='Remove Scores' />
</form>";
if(isset($_POST['use_button']))
{
$con=mysqli_connect('localhost', 'mydbuser', 'mydbpass', 'mydb');
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = "TRUNCATE TABLE contest_score";
mysqli_query($con, $sql);
mysqli_close($con);
{
echo "Score Cleared";
}
}
?>
<br>
// second button
<?php
echo
"<form action='' method='post'>
<input type='submit' class='btn btn-default' name='use_button' value='Load Questions' />
</form>";
if(isset($_POST['use_button']))
{
$webcon = mysqli_connect('localhost', 'mydbuser', 'mydbpass', 'mydb');
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
/**
* Queries for reading
*/
$questions = mysqli_query($webcon, 'SELECT * FROM `questions` ORDER BY RAND() LIMIT 30');
$mobcon = mysqli_connectmysqli_connect('localhost', 'mydbuser', 'mydbpass', 'mydb');
if (mysqli_connect_errno())
{
echo 'Failed to connect to MySQL: ' . mysqli_connect_error();
}
// remove old questions
$delete = "TRUNCATE TABLE questions";
mysqli_query($mobcon, $delete);
/**
* Insert data from old database
*/
// questions
while ($row = mysqli_fetch_array($questions))
{
// escape your strings
foreach($row as $key => $val)
{
$row[$key] = mysqli_real_escape_string($mobcon, $row[$key]);
}
mysqli_query($mobcon, "INSERT INTO `questions` (`option1`, `option2`, `option3`, `option4`, `correctans`, `question_text`, `cat_id`, `sub_cat_id`, `level_id`, `quesimage`) VALUES ('" . $row['option1'] . "', '" . $row['option2'] . "', '" . $row['option3'] . "','" . $row['option4'] . "','" . $row['correctans'] . "','" . $row['question_text'] . "','" . $row['cat_id'] . "','" . $row['sub_cat_id'] . "','" . $row['level_id'] . "','" . $row['quesimage'] . "');");
}
/*
Close Connections
*/
mysqli_close($mobcon);
mysqli_close($webcon);
{
echo "<script>alert('Questions Loaded');</script>";
}
}
?>
Can anyone suggest me to solve this issue?
Thanks.
I think the problem may be because you are using the same input name for the two buttons.
Try to change the second one to another name like:
<?php
echo
"<form action='' method='post'>
<input type='submit' class='btn btn-default' name='second_use_button' value='Load Questions' />
</form>";
if(isset($_POST['second_use_button']))
{

Change button text from "Like" to "Liked" when clicked

I am creating a forum where users are able to like and unlike posts and comments. The challenge I'm facing is that I would like the text of the like button to change without reloading the page. How can I go about differentiating between the buttons on the page and change individual button-texts from "Like" to "Liked" and vice versa? The buttons are, at the moment created and show like this:
<?php
$result3=mysqli_query($link, "SELECT * FROM cs_comments WHERE post_id = $postID");
while($row3 = mysqli_fetch_assoc($result3)){
$commentID=$row3['comment_id'];
$memberID=$row3['member_id'];
$likes=$row3['likes'];
$content= $row3['content'];
$anonymous=$row3['anonymous'];
if($anonymous=='1')
$name='Anonym';
else{
$result4= mysqli_query($link, "SELECT firstname, lastname FROM cs_members WHERE member_id = $memberID");
$row4=mysqli_fetch_assoc($result4);
$name = '' . $row4['firstname'] . " " . $row4['lastname'] . '';
}
$result5=mysqli_query($link,"SELECT * FROM cs_likes WHERE comment_id=$commentID AND member_id={$_SESSION['memberID']}");
if(mysqli_num_rows($result5)!=0)
$liked="unlike";
else
$liked="like";
echo '<div class="post_container">';
echo ' <div class="info_header">';
echo ' <div class="info_name">' . $name . '</div>';
echo ' <div class="info_group"></div>';
echo ' </div>';
echo ' <div class="post_content">';
echo $content;
echo ' </div>';
echo ' <div class="post_footer">';
echo ' <div class="like_button"><button onclick="likeComment('. $commentID . ')">' . $liked . '(' . $likes . ')</button></div>';
echo ' </div>';
echo '</div>';
}
mysqli_close($link);
?>
Javascript for onclick-event:
function likeComment(id) {
$.ajax({
url: '/resources/phpScript/like.php',
type: 'POST',
data: {comment_id:id},
success: function(data) {
console.log(data); // Inspect this in your console
}
});
Like.php
<?php
session_start();
include "./db-connect.php";
$memberID= $_SESSION['memberID'];
if(isset($_POST['post_id'])){
$postID=mysqli_real_escape_string($link,$_POST['post_id']);
$sqlCheck="SELECT * from cs_likes WHERE post_id = $postID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (post_id, member_id) VALUES ('$postID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE post_id= $postID AND member_id = $memberID";
}
elseif(isset($_POST['comment_id'])){
$commentID=mysqli_real_escape_string($link,$_POST['comment_id']);
$sqlCheck="SELECT * from cs_likes WHERE comment_id = $commentID AND member_id = $memberID";
$sqlInsert="INSERT INTO cs_likes (comment_id, member_id) VALUES ('$commentID','$memberID')";
$sqlDelete="DELETE FROM cs_likes WHERE comment_id= $commentID AND member_id = $memberID";
}
else
echo "Something went wrong";
$checkResult=mysqli_query($link, $sqlCheck);
if(mysqli_num_rows($checkResult)==0)
$result=mysqli_query($link,$sqlInsert);
else
$result=mysqli_query($link,$sqlDelete);
?>
Any help is appreciated!
So I found the solution! I have little to no experience with javascript, which is why this may have been too simple of a question for anyone to find out what I was after!
This is what I did:
I simply sent the element clicked by adding this to the function call on click:
echo ' <div class="like_button"><button onclick="likePost('. $postID . ',this)">' . $liked . '</button></div>';
I then added this tiny bit to my function:
function likePost(id, elem) {
if(elem.innerHTML== "like")
elem.innerHTML="unlike";
else
elem.innerHTML="like";
I still want to thank everyone who made and effort to try understanding what I was asking.

how to run a php function in javascript [duplicate]

This question already has answers here:
How can I call PHP functions by JavaScript?
(13 answers)
Closed 8 years ago.
<?php
session_start();
function printTable() {
$server = "XXXXXXXX";
$user = "XXXXXXXXX";
$password = "XXXXXXXX";
$database = "XXXXXXXX";
$conn = mysql_connect($server, $user, $password);
mysql_selectdb($database, $conn);
$query = "SELECT Image, ISBN, Name, Vol, Release_date, publisher, price FROM products p";
$resultset = mysql_query($query, $conn); // retrieve data from database
if ($resultset == null || $resultset == 1) {
echo mysql_error(); // print SQL error
die(); // exit PHP program
}
$numFields = mysql_num_fields($resultset);
echo "<table border=2 align=center><tr>";
echo "</tr>";
for ($i=0; $i<(mysql_num_rows($resultset)); $i++) { // print records
$fields = mysql_fetch_row($resultset);
echo "<tr>";
echo "<tr class=$color><td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
$fields = mysql_fetch_row($resultset);
if ($fields == null) break;
echo "<td><img width=100px src=$fields[0]></td>";
echo "<td> Name: " . $fields[2] . " (vol.". $fields[3] . ")</br>";
echo "<br> ISBN: " . $fields[1] . "</br>";
echo "<br> Publisher: " . $fields[5] . "</br>";
echo "<br> Release Date: " . $fields[4] . "</br>";
echo "<br> Price: HK$ " . $fields[6] . "</td>";
echo "<td><input type=\"submit\" value=\"Add to Cart\" onclick=\"combine($fields[1], '$fields[2]', $fields[3]);\"/></td>";
echo "</tr>";
}
echo "</table>";
}
mysql_close();
?>
<html>
<head>
<script>
function combine(value1, value2, value3) {
alert (value1 + value2 + value3);
//setcookie(value1);
}
</script>
</head>
<title>
Product Page
</title>
<body>
<body style="background:#A2A2AE">
<h1> <center> Product Page </center> </h1>
<p><center>-----------------------------------------------------------------------------------------------------------------------------------------------------------</center></p>
<?php printTable(); ?>
</body></html>
how I can run the function addcookies() to save value 1 as the cookies... Thank you!
function addcookies(value) {
$pid = $_POST['pid'];
$expiry = time() + 60 * 60 * 24 * 30;
// Update the number of items
if(isset($_COOKIE['count']))
$count = $_COOKIE['count'];
else
$count = 0;
// Put the item into shopping cart
$key = "item: ".$count;
setcookie($key, $pid, $expiry);
setcookie("count", $count+1, $expiry);
}
XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
First of all, your html code isn't correct. You oppened body tag 2 times and your title tag is out of the head tag, it's not even in the body.
As Biffen said in the comment, you cannot run the php after the page has loaded. Instead, you can use ajax. Ajax Documentation
You have to create a file with your php code inside it, and then execute it with ajax without reloading the page. And as I see you have written in a comment: "Put the item into shopping cart". Do not store shopping cart items in, neither, browser cookies nor session. Use your database instead because data stored in either cookies or session will be vulnerable.

Retrieving data from PHP using AJAX to send to different PHP file

Ok so I have:
A PHP file that queries a database and displays the results of the query,
a HTML file that displays the results using AJAX and
another PHP file that I need to send the data from the first PHP file to.
How can I do this?
My first PHP file displays:
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div class='result'><a id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></a>";
}
So the AJAX brings this in and displays it in the HTML. Is there a way of sending the ID field when the link is clicked so that it can be used in another PHP file to display the data for that specific ID.
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: $("#hiddenid"),
success: function (data) {
$("#individualshop").load("external-data/shop.php");
}
});
So that the data from the #hiddendiv ($row ['ID']) will be sent to the new PHP file. This isn't working.
shop.php has the code:
//get shop ID
$shopid = $_POST['ID'];
mysqli_select_db($db_server, $db_database);
$query = "SELECT * FROM shops WHERE ID='$shopid'";
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shops .= "<div class='searchresult'><strong>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div>";
}
But I'm not sure how to retrieve the ID?
Basically I need to be able to click on each search result and have another PHP file bring in specific data associated with the ID of the search result. Any suggestions??
Thanks in advance!
I'm not 100% sure this is what you want but this is one way.
This is your first php file. I've added an onclick listener to it so when a user clicks a row it will fire a JavaScript passing the $row['id'] variable.
$result = mysqli_query($db_server, $query);
if (!$result) die("Database access failed: " . mysqli_error($db_server));
while($row = mysqli_fetch_array($result)){
$str_shopresult .= "<div onclick='someFunction(" . $row['id'] . ")' class='result'><div id='shoplink' href='#shop'><strong><div id='hiddenid'>" .
$row['id'] . "</div>" .
$row['name'] . "</strong><br><br>" .
$row['address'] . "<br><br><i>" .
$row['sold'] . "</i></div></div>";
}
Then add this script to the header of the page.
<script>
function someFunction(d){
var response = httpGet("http://yourdomain.com/newphpfile.php?page_id=" +d);
document.getElementById('someResultArea').innerHTML = response;
}
function httpGet(theUrl)
{
var xmlHttp = new XMLHttpRequest();
xmlHttp.open( "POST", theUrl, false );
xmlHttp.send();
return xmlHttp.responseText;
}
</script>
Then your new php file should do something like this.
newphpfile.php
<?php
session_start();
$page_id = strip_tags($_GET['page_id']);
$processResult = 'handle your result';
echo $processResult;
?>
I hope this helps you out.
Use this;
$( "#result" ).click(function() {
$.ajax({
type: "POST",
url: "external-data/shop.php",
data: "ID=" + $("#hiddenid"),
success: function (data) {
$("#individualshop").html(data);
}
});
});
Note: Do not forget to return html in shop.php
You can fetch the clicked element id by using either javascript or jquery, and put it in the GET parameters on the php link
the ajax target would be ajax.php?id=test
Then get the value of id via $_GET['id']

Categories

Resources