oI am having problem fetching comments from MySQL database using jQuery.
I am trying this way, but its not working.
PHP (comments.php)
<?php
if (isset($_POST['value1'])) {
$id = ($_POST['value1']);
}else{
$id = '';
}
if (isset($_POST['value2'])) {
$database = ($_POST['value2']);
}else{
$database = '';
}
if (isset($_POST['value3'])) {
$tablename = ($_POST['value3']);
}else{
$tablename='';
}
require_once('rt-connect.php');
$find_data = "SELECT * FROM $tablename";
$query = mysqli_query($connection, $find_data);
?>
<?php while($row = mysqli_fetch_assoc($query)):?>
<div class="comment-container">
<div class="user-info"><?php echo $row['user_name']; ?></div>
<div class="comment"><p><?php echo $row['comment']; ?></p></div>
</div>
<?php endwhile;?>
Jquery(comments.html)
var id=2;
var database='comments_db';
var tablename='comments';
$.post('comments.php', {value1:id, value2:database, value3:tablename}, function(data)
{
$('#comments').load('comments.php .comment-container');
});
Html(div on comments to load on comments.html)
<div id="comments"></div><!--end of comments-->
Please see and suggest any possible way to do it.
Thanks
Try This one it will help you.
This is jquery Ajax post method requesst if you want to show your data is loaded or not just remove the commet.
$.ajax({
type: "POST",
url: url,
data: { value1:id, value2:database, value3:tablename}
}).done(function( data ) {
//alert(data); return false;
$("#comments").html(html);
});
You have $.load() inside success function of $.post(), try this..
$.post('comments.php', {value1:id, value2:database, value3:tablename}, function(data)
{
$('#comments').html(data);
});
In your javascript, you are posting data to a url, accepting response and if the response is successful, you are sending another request to the PHP script, this time without parameters. Your comments box is displaying the result of your second request.
You do not require :
$('#comments').load('comments.php .comment-container');
in your javascript, since you have already received a response. Instead, use :
$('#comments').html(data);
which will display the response data in the comments div.
You could try this one,
var id = 2;
var database = 'comments_db';
var tablename = 'comments';
$.ajax({
type :"POST",
data :"id="+id+"&database="+database+"&tablename="+tablename,
url : comments.php,
success: function(msg){
$("#comments").html(msg);
}
});
Related
I'm trying to save some data to a database without the use of an html form and was wondering if anyone could help me as I'm no expert in PHP. So far I have got:
JQuery
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: //Data to send,
success: function () {
$('.success_message').html("success");
}
});
});
There is no issue at the first stage as all my values are stored in the variables correctly. I just don't know in what format to send them across to save.php.
save.php
<?php
require_once 'dbconfig.php';
//Connects to database
if($_POST)
{
//Not sure what to post here
$current_date = date('Y-m-d');
try{
$stmt = $db_con->prepare("INSERT INTO entry(user_id, date, weight, bmi, calories_consumed, calories_burned, calorific_deficit) VALUES(:user, :date, :weight, :bmi, :consumed, :burned, :deficit)");
$stmt->bindParam(":user", $user_id);
$stmt->bindParam(":date", $current_date);
$stmt->bindParam(":weight", $summary_weight);
$stmt->bindParam(":bmi", $summary_bmi);
$stmt->bindParam(":consumed", $summary_consumed);
$stmt->bindParam(":burned", $summary_burned);
$stmt->bindParam(":deficit", $summary_total);
if($stmt->execute())
{
echo "Successfully Added";
}
else{
echo "Query Problem";
}
}
catch(PDOException $e){
echo $e->getMessage();
}
}
?>
I'm not sure how to post this data to save.php and then how to process it to be sent to the database. I've also added a variable of current_date to send the current date to a field in the database.
Can anyone help me and fill in the blanks? Or maybe I'm going about this the wrong way?
Send your data in an object, like so:
// Declare data as an empty object
var data = {};
// Assemble the properties of the data object
data.summary_weight = $('#summary_weight').text();
data.summary_bmi = $('#summary_bmi').text();
data.summary_consumed = $('#summary_consumed').text();
data.summary_burned = $('#summary_burned').text();
data.summary_total = $('#summary_total').text();
data.user_id = $('#user_id').text();
$.ajax({
type: "POST",
url: "save.php",
// pass the data object in to the data property here
data: data,
success: function () {
$('.success_message').html("success");
}
});
Then, on the server side, you can access directly via $_POST superglobal:
$summary_weight = $_POST['summary_weight'];
$summary_bmi = $_POST['summary_bmi'];
// etc...
You can send all this data in the data parameter as given below:
$('.summary').on('click', '#btn_save', function () {
var summary_weight = $('#summary_weight').text();
var summary_bmi = $('#summary_bmi').text();
var summary_consumed = $('#summary_consumed').text();
var summary_burned = $('#summary_burned').text();
var summary_total = $('#summary_total').text();
var user_id = $('#user_id').text();
//All values stored correctly
$.ajax({
type: "POST",
url: "save.php",
data: {summary_weight: summary_weight, summary_bmi:summary_bmi, summary_consumed:summary_consumed, summary_burned: summary_burned, summary_total:summary_total, user_id:user_id },
success: function () {
$('.success_message').html("success");
}
});
});
And the, process it in save.php like this
$summary_weight = $_POST['summary_weight'];
and use it in the query to save it in database.
This question already exists:
Database values are not updating?
Closed 8 years ago.
I am using this code to call ajaxvote.php
$('.vote').click(function(){
$.ajax({
url: 'ajaxvote.php',
type: 'POST',
cache: 'false',
success: function () { alert("Success!"); } ,
error: function () { alert("Error!"); }});
var self = $(this);
var action = self.data('action');
var parent = self.parent().parent();
var postid = parent.data('postid');
var score = parent.data('score');
if (!parent.hasClass('.disabled')) {
if (action == 'up') {
parent.find('.vote-score').html(++score).css({'color':'orange'});
self.css({'color':'orange'});
$.ajax({data: {'postid' : postid, 'action' : 'up'}});
}
else if (action == 'down'){
parent.find('.vote-score').html(--score).css({'color':'red'});
self.css({'color':'red'});
$.ajax({data: {'postid' : postid, 'action' : 'down'}});
};
parent.addClass('.disabled');
This is the code from my webpage
<div class="item" data-postid="<?php echo $rows['ID'] ?>" data-score="<?php echo $rows['VOTE'] ?>">
<div class="vote-span">
<div class="vote" data-action="up" title="Vote up"><i class="fa fa-camera-retro"></i></div>
<div class="vote-score"><?php echo $rows['VOTE'] ?></div>
<div class="vote" data-action="down" title="Vote down"><i class="fa fa-camera-retro"></i></div>
</div>
This is my php code
if ($_SERVER['HTTP_X_REQUESTED_WITH']) {
if (isset($_POST['postid']) && (isset($_POST['action']))) {
$postId = $_POST['postid'];
if (isset($_SESSION['vote'][$postId])) return;
$query = $mysqli - > query("SELECT VOTE from stories WHERE ID = $postId LIMIT 1");
while ($rows = mysqli_fetch_array($query)) {
if ($_POST['action'] === 'up') {
$vote = ++$rows['VOTE'];
} else {
$vote = --$rows['VOTE'];
}
$mysqli - > query("UPDATE stories SET VOTE = $vote WHERE ID = $postId ");
$_SESSION['vote'][$postId] = true;
}
}
}
I know I can connect to database because I can login. I also get the alert success I have set up above, However, the values are not updating in Database.
EDIT
I have added more Ajax code that I had already written.
When posting via ajax, you need to send through the data you actually want to post.
var postData = {name:"Mister",lastName:"Frodo"}; //Array
$.ajax({
url : "ajaxvote.php",
type: "POST",
data : postData,
success: function(data, textStatus, jqXHR)
{
//Handle response
},
error: function (e) {
// Handle error
}
});
In this case, the post ID and score needs to be grabbed. You also need to grab what kind of action is clicked (typically through a click event bind on the divs with class="vote". For example purposes, let's just set it to "up" for now:
var postId = $('div.item').attr('data-postid').val();
var score = $('div.item').attr('data-score').val();
var postData = {postId: postId, score: score, action: 'up'}
You can now post that "postData" to your ajaxvote.php.
Also, you can use jQuery's $.POST method
$.post("ajaxvote.php", { name: "Mister", lastName: "Frodo" } );
Now for parsing your form, have a look at jQuery's serialize which goes through your form takes each input's [name] attribute along with the value to create a data-string.
Example
name=Mister&lastName=Frodo
This is ideal for sending through with the "data" attribute in $.ajax. Have a look at this answer for more regarding jQuery's serialize.
I am using Wordpress and I have a page where I have a drop down that when the links are clicked it will make an Ajax call and pass the data variable to PHP, at least that is what I'm attempting to do lol.
When clicking on the link I check my browser and in the Network tab for the page I receive a variable for the data object in the html and the ajax post's to the php page but for some reason I can't get a value.
My HTML
<div class="category-submenu">
<ul>
<li>Corporate</li>
<li>Office1</li>
<li>Office2</li>
<li>Office3</li>
</ul>
</div>
My jQuery
$('.category-submenu a').click(function(){
$.ajax({
type: "POST",
url: "/load-team.php",
dataType: 'json',
data: {office: $(this).data('office')},
success: function(data) {
$.each( data, function(i, item) {
alert(data[i].start);
});
}
});
});
My PHP
<?php
$office = $_GET['office'];
$link = mysql_pconnect("localhost", "root", "root") or die("Could not connect");
mysql_select_db("somedb") or die("Could not select database");
$arr = array();
$query = mysql_query("SELECT first_name, last_name FROM ic_team_members WHERE office ='" . $office . "'");
while($obj = mysql_fetch_object($query)) {
$arr[] = $obj;
}
echo '{"members":'.json_encode($arr).'}';
?>
I'm sure there is some code missing or my syntax might be incorrect in some parts but I can't seem to find where, if any place.
Again I want to grab the data object from HTML element, pass it through Ajax into PHP and return the result as json object, which I can do but for some reason I think the error is in my PHP.
Any help would be appreciated.
You are passing it by POST, and therefore you need to receive it with POST:
$office = $_POST['office'];
Otherwise, use GET to send the ajax request:
$.ajax({
type: "GET",
...
});
How to make an animated table only animate when a new record is added to the database.
Ajax/Js (in index.php):
$.ajax({
url : 'Not sure what goes here?',
data : {Not sure what goes here?},
dataType : 'application/json', // Is this correct?
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
var newitem = function(response){
var item = $('<div>')
.addClass('item')
.css('display','none')
.text(response)
.prependTo('#scroller')
.slideDown();
$('#scroller .item:last').animate({height:'0px'},function(){
$(this).remove();
});
}
My php (latest.php):
include ('db.php');
$sql2 = "SELECT * FROM `feed` ORDER BY `timez` DESC";
$res2 = mysql_query($sql2) or die(mysql_error());
while($row3 = mysql_fetch_assoc($res2)){
$user = $row3['username1'];
$action = $row3['action'];
$user2 = $row3['username2'];
echo ''.$user.''.$action.''.$user2.'<br>'; // Needs to be a json array?
I can't get this to work, here's how the table operates http://jsfiddle.net/8ND53/ Thanks.
$.ajax({
url : your_php_file.php',
data : {data you'r going to send to server}, // example: data: {input:yourdata}
success: function(response) {
$('#table_id').append('<tr>'+response+'</tr>'); // response is the date you just inserted into db
}
});
in your_php_file.php:
add the item into db
echo that inserted data # if you echo, then you can catch this with ajax success function then you append it into your table.
try to fill as below:
$.ajax({
type: "post"
url : 'locationOfphpCode/phpCode.php',
data : {data you want to pass}, //{name: "dan"}
success: function(response) {
// Only when successful animate the content
newItem(response);
}
});
in your php code you need to receive the data you have passed from the ajax call:
<?php
$name = $_POST['name'];
...
?>
you may add some validations in your php code.
hope this will help you.
the example you have given is using setInterval(newitem, 2000)
so you have to call ajax function on some fixed interval.
When I click on share on a users link..It shares that post fine, yet it posts it twice. I've checked firebug and when clicked (Once) it shows up two POST requests, inserts two posts to the database and then shows them in the users feed.
I really don't understand where I'm going wrong.
SHARE LINK
echo'<a class="sharelink" title="Share '.$poster_name['fullusersname'].'s status" href="#"
data-streamitem_creator='.$streamitem_data['streamitem_creator'].'
data-streamitem_target='.$_SESSION['id'].'
data-streamitem_content='.$streamitem_data['streamitem_content'].'
data-streamitem_type_id=4>Share</a>';
AJAX
$(document).ready(function() {
$('.sharelink').click(function(e) {
e.preventDefault();
var streamitem_creator = $(this).data('streamitem_creator');
var streamitem_target = $(this).data('streamitem_target');
var streamitem_content = $(this).data('streamitem_content');
var streamitem_type_id = $(this).data('streamitem_type_id');
$.ajax({
type: "POST",
url: "../include/share.php",
data: {
streamitem_creator: streamitem_creator,
streamitem_target: streamitem_target,
streamitem_content: streamitem_content,
streamitem_type_id: streamitem_type_id
},
success: function(data) {
$(".usermsg").html(data);
}
});
});
});
SHARE.php
<?
session_start();
require"load.php";
if(isset($_POST['streamitem_type_id'])&isset($_POST['streamitem_creator'])&isset($_POST['streamitem_content'])&isset($_POST['streamitem_target'])){
user_core::create_streamitem(4,$_SESSION['id'],$_POST['streamitem_content'],1,$_POST['streamitem_creator']);
}
?>
LOAD.PHP
public function create_streamitem($typeid,$creatorid,$content,$ispublic,$targetuser){
global $mysqli;
$content = $content;
// $content = strip_tags($content);
if(strlen($content)>0){
$insert = "INSERT INTO streamdata(streamitem_type_id,streamitem_creator,streamitem_target,streamitem_timestamp,streamitem_content,streamitem_public) VALUES ($typeid,$creatorid,$targetuser,UTC_TIMESTAMP(),'$content',$ispublic)";
$add_post = mysqli_query($mysqli,$insert) or die(mysqli_error($mysqli));
$last_id = mysqli_insert_id($mysqli);
if(!($creatorid==$targetuser)){
$fromuser= rawfeeds_user_core::getuser($creatorid);
$_SESSION['id']==$content;
}
return;
}else{
return false;
}
I can't see any problem.. By any chance, don't you have that $('.sharelink').click handler registered twice within your page?