I have a 'like' button that I have implemented with PHP/MySqL, AJAX and Jquery, which increments likes by +1 each time. It all seems to work fine and updates the database with the new value; however, the response that is returned from the AJAX call is returning all of the html in my .php file that comes before the post handler in my index.php. Other than moving the handler all the way to the top of the page, is there a way of fixing this?
Code below:
index.php
<?php
include './includes/header.php';
?>
<?php
include './includes/title_box.php';
?>
<?php
include './includes/categories_box.php';
?>
<?php
include './includes/roadmap_box.php';
?>
<?php
if(isset($_POST['liked'])) {
$postid = $_POST['postid'];
$query = "SELECT * FROM posts WHERE post_id=$postid";
$result = mysqli_query($connection, $query);
$row = mysqli_fetch_array($result);
$n = $row['post_upvotes'];
$query = "UPDATE posts SET post_upvotes=$n+1 WHERE post_id=$postid";
mysqli_query($connection, $query);
echo $n + 1;
exit();
}
?>
<button class="upvote-button" value=<?php echo $id ?>><?php echo $upvotes ?></button>
script.js
$(document).ready(function(){
$(".upvote-button").click(function(){
var postID = $(this).val();
$post = $(this);
$.ajax({
url: './index.php',
type: 'post',
data: {
'liked': 1,
'postid': postID
},
success: function(response){
$post.html(response);
}
});
});
});
console.log(response)
element.style {
}
user agent stylesheet
body {
display: block;
margin: 8px;
}
script.js:14
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script
src="https://code.jquery.com/jquery-3.6.0.js"
integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk="
crossorigin="anonymous"></script>
<title>Product Feedback App</title>
</head>
<body><div class="title-box">
<h1>Frontend Mentor</h1>
<p>Feedback Board</p>
</div><div class="categories-box">
<ul>
<li>All</li>
<li>UI</li>
<li>UX</li>
<li>Enhancement</li>
<li>Bug</li>
<li>Feature</li>
</ul>
</div>
<div class="roadmap-box">
<h2>Roadmap</h2>
View Roadmap
<ul>
<li>Planned - 2</li>
<li>In-Progress - 3</li>
<li>Live - 1</li>
</ul>
</div>
134
Move your if(isset($_POST['liked'])) and all associated code to a separate file and call that file in your Ajax query url.
You will probably need to include the file that connects to your database in the new file as well, but without seeing the contents of your included files it's hard to give specific advice.
Related
I am getting user data by passing the id in url and using the select statement where it matches the id in url and display result
But I want this by using ajax. Please help me
<div id="show_data">
<?php
$id=$_GET['id'];
$category=$_GET['category'];
if ($category==Hosted) {
$result = $wpdb->get_results ("SELECT * FROM wp_user_host WHERE user_id=$id");
foreach ( $result as $print ){
?>
<table>
<tr>
<td>Name: <?php echo $print->drive_name;?</td>
<td>Date: <?php echo $print->drive_date;?</td>
</tr>
</table>
<?php
}
}
?>
</div>
<a href="page.php?id=2&category=Hosted:>VIEW DATA</a>
lets say i have an index file like follow
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<div>TODO write content</div>
<button id="testDom">click to load dom</button>
<p id="domOutput"></p>
<script>
document.getElementById("testDom").addEventListener('click', function(){
loadAjax();
});
function loadAjax(){
var xmlHttp = new XMLHttpRequest();
var requestUrl = 'test.php';
xmlHttp.onreadystatechange = function(){
if( this.readyState == 4 && ( this.status > 200 || this.status < 300 ) ){
console.log("ok");
document.getElementById("domOutput").innerHTML = xmlHttp.responseText;
}
}
xmlHttp.open('GET', requestUrl);
xmlHttp.send();
}
</script>
</body>
lets say if u click the button ajax call made to the php file called test.php
<?php
echo "php file loaded";
ouput will printed in the index.html on p tag.
I'm have a problem. I want connect PHP and PostgreSQL, but don't know how.
HTML:
<?php
?>
<!DOCTYPE html>
<html lang = "pt-br">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- Título -->
<title>test</title>
<!-- Bootstrap CSS -->
<link href="css/bootstrap.css" rel="stylesheet">
<!-- Font-Awesome CSS -->
<link href="css/font-awesome.min.css" rel="stylesheet">
<!-- Ubicua-cloud CSS -->
</head>
<body>
<form action = "" name = "f1" method = "post" style = "">
<input type = "text" id = "telefone">
<button type = "button" id = "init">iniciar sessão</button>
</form>
<!-- jQuery -->
<script src="js/jquery.min.js"></script>
<!-- Bootstrap JS -->
<script src="js/bootstrap.min.js"></script>
<!-- Ubicua-cloud-js -->
<script src="login.js"></script>
</body>
</html>
DB connect:
<?php
$connect=pg_connect ("host=localhost dbname=test port=5432 user=postgres password=28974220")or
die("Error");
?>
JS to catch user informations:
$(document).ready(function(){
$('#init').click(function(){
var telefone=$('#telefone').val();
alert(telefone);
$.ajax({
type:"POST",
dataType:'json',
url:'login.Ajax.php',
data:{telefone:telefone},
success: function(response){
if(response.resposta==true){
$('#msg').html(response.msg);
window.location='test.php';
}
else{
$('#msg').html(response.msg);
}
},error:function(){
alert('error');
}
});
});
});
The PHP code to validate informations:
<?php
include_once('includes/connect.php');
$msg_ok=false;
$msg_error='O sistema está indisponível.';
if(isset($_POST['telefone']))
if($_POST['telefone']!="")
$telefone=$_POST['telefone'];
$consulta=pg_query($connect, ("Select * from test where telefone='$telefone"));
if(pg_num_rows($consulta)>0)
$msg_ok=true;
$usua=pg_fetch_array($consulta);
session_start();
$_SESSION['id']=$usua[0];
$_SESSION['telefone']=$usua[1];
$msg_error='Logado';
else
$msg_error='Telefone não existe.';
endif;
else
$msg_error='Telefone incorreto.';
endif
else
$msg_error='Erro.';
endif;
$saidaJson=array('resposta' => $msg_ok, 'msg' => msg_error);
echo json_encode($saidaJson);
?>
I received error messages to catch user informations, help, please.
I'm assuming you are using PDO. If so, you need make changes to the database connection file(substitute the variables with your database values):
<?php
$db = new PDO("pgsql:dbname=$dbname;host=$host";port=$port, $dbuser, $dbpass);
?>
I solved the problem, but now I'm needing exchange informations between the php and js...I have a script that simulates a person typing and need it to talk to users calling them by their proper names, but I don't know how, I need concatenate one variable in JS, but before that I need store one PHP variable in one JS variable.
var init = document.getElementById('init_text');
var init_text = 'Hi <nome>, I'm your friend!';
function digit(str, el) {
var char = str.split('').reverse();
var typer = setInterval(function () {
if (!char.length) return clearInterval(typer);
var next = char.pop();
el.innerHTML += next;
}, 60);
}
digit(init_text, init);
I have a page showing a picture of a product. Underneath that I have tabs for the Description, Contact Details and Comments. When you click on the Comments tab a comments page is loaded into the div="info" using Jquery.
products.php:
<html>
<head></head>
<body>
<img src="image.jpg">
<hr>
<a id="det"><h3>Details</h3></a>  <a id="contact"><h3>Contact</h3></a>
 <a id="comments"><h3>Comments</h3></a>
<div id="info"></div>
</body>
<html>
Jquery:
<script>
$(document).ready(function(){
$("#comments").click(function(){
$("#info").load("comments.php");
});
});
</script>
The comments.php page below uses pagination for the comments.
When I click on the pagination links the page refreshes the comments.php?page=* removing it from the div="info".How do I keep the comments in the div id="info" when I use pagination?
comments.php:
<?php
// 1)Set current page
$current_page = ((isset($_GET['page']) && $_GET['page'] > 0) ?
(int)$_GET['page'] : 1);
require 'connect.php';
// 2)Get total amount of rows
$sql = "SELECT * FROM comments";
$result=mysqli_query($conn,$sql);
$totalrows = mysqli_num_rows($result);
// Offset - calculation to skip to the data you want to display
$results_per_page = 10;
$offset = ($current_page-1)*$results_per_page;
?>
/*------- Comments Form -----*/
/*------- Comments from Database ---- */
<?php
//Here is the code for displaying link and page number.
$number_page = $totalrows/$results_per_page;
for ( $page = 1; $page <= $number_page; $page ++ )
{
echo "<a href='comments.php?page={$page}'>{$page}</a>";
}
?>
You know... you could end this problem doing a js making every link inside the #info element update only inside it. Not sure if is that what you need.
$('#info').on('click', 'a', function (e){
e.preventDefault();
$("#info").load($(this).attr('href'));
});
You need to attach a click event to the links that are loaded in the ajax partial.
The simplest way to do that is to add a class property to any of the links you want to load via ajax, then attach your event to that class.
Example:
<?php
// example just increments the page param
if(strtolower(filter_input(INPUT_SERVER, 'HTTP_X_REQUESTED_WITH', FILTER_SANITIZE_STRING)) == 'xmlhttprequest') {
die('<a class="ajaxlink" href="?page='.($_GET['page']+1).'">Goto page '.($_GET['page']+1).'</a>');
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
</head>
<body>
<h3><a class="ajaxlink" href="index.php">Contact</a></h3>
<div id="info"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<script>
$(document).on("click", ".ajaxlink", function(event) {
event.preventDefault();
if ($(this).prop('href').length > 0) {
$("#info").load($(this).prop('href'));
}
return false;
});
</script>
</body>
</html>
I'm trying to pass the data-value of the < li > I clicked to PHP in the same page. I'm using AJAX to pass the data to PHP, to be used in querying. I think the ajax request is working, but the php code inside the if is not running.
The codes:
offices.php
<?php
include 'connect.php';
$page = 'offices';
include 'header.php';
if (isset($_POST['postdata'])){
$filter1 = $_POST['postdata'];
echo $filter1;
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div class="filter1">
<ul>
<li class="fteacher" data-value="teacher">Professor</li>
<li class="foffice" data-value="office">Gabinete</li>
</ul>
</div>
<script src="js/offices.js"></script>
</body>
</html>
offices.js
$('.filter1 li').click(function(){
$.ajax({
type: 'POST',
url: 'offices.php',
data: {'postdata': $(this).attr('data-value')},
success: function(msg){
alert('Success');
}
});
});
I tried the code you provided, but had to ommit the two includes at the beginning of your PHP script, and it worked. Testing was done using file_put_contents("test.txt", "test"); in the if-clause.
You may have a look at what the PHP script returns by using alert(msg). Note that everything after the PHP part is returned, too. It might also help to use error_reporting(E_ALL) in the PHP to search for problems in the included scripts.
Please try this. Hope you are only expecting the output $filter1
<?php
if (isset($_POST['postdata'])){
$filter1 = $_POST['postdata'];
echo $filter1;
}else {
include 'connect.php';
$page = 'offices';
include 'header.php';
?>
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.min.js"></script>
</head>
<body>
<div class="filter1">
<ul>
<li class="fteacher" data-value="teacher">Professor</li>
<li class="foffice" data-value="office">Gabinete</li>
</ul>
</div>
<script src="js/offices.js"></script>
</body>
</html>
<?php
}
?>
I'm working with a main PHP page that has four included templates:
<?php session_start(); ?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=9" />
<title>Example Page</title>
</head>
<body>
<?php include ("script/select.class.php"); ?>
<div class="content">
<?php
include("./templates/one.php");
include("./templates/two.php");
include("./templates/three.php");
include("./templates/four.php");
?>
</div>
</body>
</html>
'two.php' contains a form (the_form) submitted via AJAX:
$('#button').click(function(){
$.ajax({
type: "POST",
url: "script/add_new.php",
data: $("#the_form").serialize(),
success: function(data){
newID = data;
alert(newID);
}
});
});
On 'add_new.php', once the INSERT is completed, I have this PHP code:
if (!mysqli_query($con,$sql)) {
die('Error: ' . mysqli_error($con));
}
$_SESSION['new_id'] = mysqli_insert_id($con);
echo $_SESSION['new_id'];
The problem I'm experiencing is that even though $_SESSION['new_id'] will pass back through the Ajax 'data' var and show up in the 'alert', I get an Unidentified Index error if I attempt to display on the next tempate page (three.php) using <?php echo $_SESSION['new_id'] ?>.
Any suggestions?
Cheery is correct. I'll need to take a different approach.