AJAX : Pass an image and data through Single AJAX [duplicate] - php

This question already has answers here:
How to send image to PHP file using Ajax?
(5 answers)
jQuery AJAX file upload PHP
(5 answers)
jQuery / ajax upload image and save to folder
(3 answers)
Upload image using jQuery, AJAX and PHP
(2 answers)
Closed 4 years ago.
I want to pass some text data and file through one ajax code
Here is my code's index.php :-
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="">
<meta name="author" content="Karthikeyan K">
<title>POST</title>
<!-- Bootstrap CSS file -->
<link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/css/bootstrap.min.css" />
<style type="text/css">
body {
padding: 45px;
}
footer {
margin: 10px 0;
}
.photo {
margin-bottom: 10px;
}
</style>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" />
<link rel="stylesheet" type="text/css" href="css/jquery.mentionsInput.css">
<style type="text/css">
#status-overlay {
height: 100%;
width: 100%;
background: rgba(0, 0, 0, 0.50);
position: fixed;
top: 0;
left: 0;
z-index: 99999;
overflow: hidden;
}
#highlight-textarea {
background: #fff;
}
.form-control:focus {
box-shadow: 0 0 0 2px #3399ff;
outline: 0;
}
h2 {
font-size: 20px;
}
</style>
<style>
#upload_button {
display: none;
border: 0px;
background: linear-gradient(180deg, #f44, #811);
border-radius: 5px;
color: #fff;
padding: 5px;
}
</style>
</head>
<body>
<div id="status-overlay" style="display: none"></div>
<form method="POST" class="form" enctype="multipart/form-data">
<div class="form-group">
<input type="text" name="title" id="title" class="form-control" placeholder="Post title..."><br>
<div id="highlight-textarea">
<textarea onclick="highlight();" name="postText" class="form-control postText mention" cols="10" rows="8" placeholder="What's going on?" dir="auto"></textarea>
</div><br>
<select class="form-control" name="type" id="type" required>
<option value="">Choose Post Type</option>
<option value="Closet">Closet</option>
<option value="Follower">Follower</option>
<option value="Group">Group</option>
</select><br>
<p><button id="upload_button">Click here to select file</button></p>
<p><input id="upload_input" name="upfile" type="file"/></p>
</div>
<input type="button" value="Post" class="btn btn-primary pull-right postMention">
</form>
<!-- Bootstrap Script file -->
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src='https://cdn.rawgit.com/jashkenas/underscore/1.8.3/underscore-min.js' type='text/javascript'></script>
<script src='js/lib/jquery.elastic.js' type='text/javascript'></script>
<script type="text/javascript" src="js/jquery.mentionsInput.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('textarea').on('click', function(e) {
e.stopPropagation();
});
$(document).on('click', function (e) {
$("#status-overlay").hide();
$("#highlight-textarea").css('z-index','1');
$("#highlight-textarea").css('position', '');
});
});
function highlight()
{
$("#status-overlay").show();
$("#highlight-textarea").css('z-index','9999999');
$("#highlight-textarea").css('position', 'relative');
}
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
//post text in jquery ajax
var post_data = "text="+encodeURIComponent(post_text);
var val1 = $('#title').val();
var val2 = $('#type').val();
//var val3 = $('#upload_input');
//var post_title = $('#title').val();
var form = new FormData(document.getElementById('.postMention'));
//append files
var file = document.getElementById('upload_input').files[0];
if (file) {
form.append('upload_input', file);
}
$.ajax({
type: "POST",
data: post_data+'&title='+val1+'&type='+val2+'&upload_input='+form,
url: 'ajax/post.php',
success: function(msg) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
}
});
} else {
alert("Post cannot be empty!");
}
});
});
//used for get users from database while typing #..
$('textarea.mention').mentionsInput({
onDataRequest:function (mode, query, callback) {
$.getJSON('ajax/get_users_json.php', function(responseData) {
responseData = _.filter(responseData, function(item) { return item.name.toLowerCase().indexOf(query.toLowerCase()) > -1 });
callback.call(this, responseData);
});
}
});
});
</script>
</body>
</html>
<?php } ?>
here's a code of my php file to insert data into database ajax/post.php
. . . .
<?php
session_start();
if (#$_SESSION['user']!=true) {
echo "<script>window.alert('You are not login.');</script>";
echo "<script>window.open('login.php','_self');</script>";
}
else {
include_once '../../connection.php';
$uid=$_SESSION['id'];
$query=mysqli_query($conn,"SELECT * FROM `register` WHERE `id`='$uid'");
$row=mysqli_fetch_array($query);
if(isset($_POST) && !empty($_POST['text']) && $_POST['text'] != '')
{
include '../config/config.php';
$user = $uid; //w3lessons demo user
$postid=mt_rand();
$text = strip_tags($_POST['text']); //clean the text
$title= $_POST['title'];
$type= $_POST['type'];
define('FIRST_MATCH_GROUP', 1);
preg_match_all("/#\[(.+)\]/U", $text, $tags); // Value under #[]
$tags = implode(',', $tags[FIRST_MATCH_GROUP]);
$upfile_name = $_FILES['upload_input']['name'];
$upfile_size =$_FILES['upload_input']['size'];
$upfile_tmp =$_FILES['upload_input']['tmp_name'];
$upfile_type=$_FILES['upload_input']['type'];
$upfile_t = explode(".", $_FILES["upload_input"]["name"]);
$upfile_name = mt_rand() . '.' . end($upfile_t);
if($upfile_type == "image/jpg" && $upfile_type == "image/png" && $upfile_type == "image/jpeg" && $upfile_type == "video/mp4"){
echo "<script>window.alert('extension not allowed, please choose a JPG or PNG or MP4 file.');</script>";
}
else {
if($upfile_size > 10485760){
echo "<script>window.alert('File size must be Less 10 MB');</script>";
}
else {
move_uploaded_file($upfile_tmp,"../../uploads/".$upfile_name);
$DB->query("INSERT INTO posts(post_id,title,content,user_id,type,tags,image) VALUES(?,?,?,?,?,?,?)", array($postid,$title,$text,$user,$type,$tags,$upload_input));
?>
<div class="media">
<div class="media-left">
<img src="https://cdn.w3lessons.info/logo.png" class="media-object" style="width:60px">
</div>
<div class="media-body">
<h4 class="media-heading">w3lessons</h4>
<p><?php echo getMentions($text); ?></p>
</div>
</div>
<hr>
<?php
} } } else {
echo "1"; //Post Cannot be empty!
}
function getMentions($content)
{
global $DB;
$mention_regex = '/#\[([0-9]+)\]/i'; //mention regrex to get all #texts
if (preg_match_all($mention_regex, $content, $matches))
{
foreach ($matches[1] as $match)
{
$match_user =$DB->row("SELECT * FROM register WHERE id=?",array($match));
$match_search = '#[' . $match . ']';
$match_replace = '<a target="_blank" href="' . $match_user['profile_img'] . '">#' . $match_user['first_name'] . '</a>';
if (isset($match_user['id']))
{
$content = str_replace($match_search, $match_replace, $content);
}
}
}
return $content;
}
}?>
When i submit form data was passing at my php page but images index is goes undefined...

change the way you pass data in request
try this
$(document).ready(function(){
$('.postMention').click(function() {
$('textarea.mention').mentionsInput('val', function(text) {
var post_text = text;
if(post_text != '')
{
var formData = new FormData($('.form')[0]);
formData.append('text',encodeURIComponent(post_text));
$.ajax({
url: 'ajax/post.php',
type: 'POST',
data: formData,
success: function (data) {
if(msg.error== 1)
{
alert('Something Went Wrong!');
} else {
$("#post_updates").prepend(msg);
//reset the textarea after successful update
$("textarea.mention").mentionsInput('reset');
}
},
cache: false,
contentType: false,
processData: false
});
} else {
alert("Post cannot be empty!");
}
});
});
and input name
<input id="upload_input" name="upload_input" type="file"/>

Related

On the click of the image it is not removing in jQuery

Selecting the multiple image from the input tag after that I am previewing the selected image but when I click on that image it should delete from the input tag it does not select that picture any more. But in my case that picture is removing only in preview not in input. And save it into database
Here is the code
<?php
include_once 'Functions.php';
$connect=new Connection();
$link=$connect->Connect();
print_r($_FILES['fil']['name']);
?>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
var image=('')
('input[type="file"]'). change(function(e){
var fileName = e. target. files[0]. name;
alert('The file "' + fileName + '" has been selected.' );
});
$(function() {
var imagesPreview = function(input,placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img class="picture" width="70" name="multipic">')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
$('.picture').click(function(){
$(this).remove();
});
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this,'div.gallery');
});
});
});
</script>
</head>
<body>
<form name="update" enctype='multipart/form-data' method="POST">
<input type="file" name="fil[]" multiple id="gallery-photo-add" class="a1">
<div class="gallery"></div>
<input type="submit" name="btnupdate" value="Update" />
</form>
</body>
</html>
Here is HTML Code :
<div class="container">
<form id="fileupload" action="#" method="POST" enctype="multipart/form-data">
<div class="row files" id="files1">
<h2>Files 1</h2>
<span class="btn btn-default btn-file">
Browse <input type="file" name="files1" multiple />
</span><br/>
<ul class="fileList"></ul>
</div>
<div class="row">
<button type="x" id="uploadBtn" class="btn primary start">Start upload</button>
</div>
<div class="row">
<div class="span16">
<table class="zebra-striped"><tbody class="files"></tbody></table>
</div>
</div>
</form>
</div>
Here is CSS Code :
.btn-file {
position: relative;
overflow: hidden;
}
.btn-file input[type=file] {
position: absolute;
top: 0;
right: 0;
min-width: 100%;
min-height: 100%;
font-size: 100px;
text-align: right;
filter: alpha(opacity=0);
opacity: 0;
outline: none;
background: white;
cursor: inherit;
display: block;
}
Here is jQuery Code :
$.fn.fileUploader = function (filesToUpload, sectionIdentifier) {
var fileIdCounter = 0;
this.closest(".files").change(function (evt) {
var output = [];
for (var i = 0; i < evt.target.files.length; i++) {
fileIdCounter++;
var file = evt.target.files[i];
var fileId = sectionIdentifier + fileIdCounter;
filesToUpload.push({
id: fileId,
file: file
});
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + fileId + "\">Remove</a>";
output.push("<li><strong>", escape(file.name), "</strong> - ", file.size, " bytes. ", removeLink, "</li> ");
};
$(this).children(".fileList")
.append(output.join(""));
//reset the input to null - nice little chrome bug!
evt.target.value = null;
});
$(this).on("click", ".removeFile", function (e) {
e.preventDefault();
var fileId = $(this).parent().children("a").data("fileid");
// loop through the files array and check if the name of that file matches FileName
// and get the index of the match
for (var i = 0; i < filesToUpload.length; ++i) {
if (filesToUpload[i].id === fileId)
filesToUpload.splice(i, 1);
}
$(this).parent().remove();
});
this.clear = function () {
for (var i = 0; i < filesToUpload.length; ++i) {
if (filesToUpload[i].id.indexOf(sectionIdentifier) >= 0)
filesToUpload.splice(i, 1);
}
$(this).children(".fileList").empty();
}
return this;
};
(function () {
var filesToUpload = [];
var files1Uploader = $("#files1").fileUploader(filesToUpload, "files1");
$("#uploadBtn").click(function (e) {
e.preventDefault();
var formData = new FormData();
for (var i = 0, len = filesToUpload.length; i < len; i++) {
formData.append("files", filesToUpload[i].file);
}
$.ajax({
url: "",
data: formData,
processData: false,
contentType: false,
type: "POST",
success: function (data) {
alert("DONE");
files1Uploader.clear();
},
error: function (data) {
alert("ERROR - " + data.responseText);
}
});
});
});
Try above code. Hope this will help

How to implement autocomplete using typeahead bootstrap and sql?

I'm trying to implement autocomplete from sql database using bootsrap typeahead.
When I'm trying it out in a demo it works perfectly, but when I put it inside the project nothing works.
CSS
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
<script type="text/javascript" src="typeahead.js"></script>
<style>
.typeahead {}
.tt-menu { width:300px; }
ul.typeahead{margin:0px;padding:10px 0px;}
ul.typeahead.dropdown-menu li a {padding: 10px !important; border-bottom:#CCC 1px solid;color:#FFF;}
ul.typeahead.dropdown-menu li:last-child a { border-bottom:0px !important; }
.bgcolor {max-width: 550px;min-width: 290px;max-height:340px;padding: 100px 10px 130px;border-radius:4px;text-align:center;margin:10px;}
.demo-label {font-size:1.5em;color: #686868;font-weight: 500;color:#FFF;}
.dropdown-menu>.active>a, .dropdown-menu>.active>a:focus, .dropdown-menu>.active>a:hover {
text-decoration: none;
background-color: #1f3f41;
outline: 0;
}
</style>
here is the script and HTML code
<div class="form-group">
<label>Srtudent Name or ID<span style="color:red;">*</span></label>
<input class="typeahead form-control" type="text" name="studentID" id="studentID" />
</div>
<script>
$(document).ready(function () {
$('#studentID').typeahead({
source: function (query, result) {
$.ajax({
url: "search-student.php",
data: 'query=' + query,
dataType: "json",
type: "POST",
success: function (data) {
result($.map(data, function (item) {
return item;
}));
}
});
}
});
});
</script>
Here's the PHP code
<?php
$keyword = strval($_POST['query']);
$search_param = "{$keyword}%";
$conn =new mysqli('localhost', 'root', '' , 'lms');
$sql = $conn->prepare("SELECT * FROM students WHERE studentName LIKE ?");
$sql->bind_param("s",$search_param);
$sql->execute();
$result = $sql->get_result();
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
$countryResult[] = $row["studentName"];
}
echo json_encode($countryResult);
}
$conn->close();
?>
Put
<script type="text/javascript" src="typeahead.js"></script>
as last script so no override to happen for the function typeahead. (this solved the problem)

How to send data with AJAX and PHP

I'm trying to implement a commenting box with AJAX and PHP (CodeIgniter framework). Here is the code.
The view (HTML code):
<form id="form" method="post">
<div class="input-group" id="input-group"><!-- input group starts-->
<textarea class="form-control" id="Comment" name="Comment" placeholder="Comment on Scenery..." maxlength="300" cols="70" rows="3" required></textarea>
<input type="hidden" id="uploader_id" value="<?php echo $uploader_id ?>"/>
<input type="hidden" id ="scenery_id" value="<?php echo $scenery_id ?>"/>
<button type="submit" id="submit"class="btn btn-info regibutton" >Post</button>
</div>
</form>
<hr/>
<div class="comment-block">
<?php
if ($comment==NULL){
//if no scenery comment echo disclaimer
echo " <ul style = ' margin-left: 0px;padding-left: 0px;'> <li style = 'list-style: none; background-color: #fff; padding : 5px 5px 5px 10px; margin: 5px 5px 5px 5px'>";
echo " No scenery Comments";
echo "</li>
</ul>";
} else {
foreach ($comment as $row){
// if the comments are availabe echo them
echo " <ul style = ' margin-left: 0px;padding-left: 0px;'> <li style = 'list-style: none; background-color: #fff; padding : 10px 5px 5px 10px; margin: 5px 5px 5px 5px'>";
echo $row->Comment;
echo "<br/>";
echo "<p style='font-size: 11px; color:#333; padding-top: 5px;'>".date(" D d M Y - H:i:s ",strtotime($row->Date_posted))."By - ". $row->Username. " </p>";
echo $row->Date_added;
echo "</li>
</ul>";
}
}
?>
</div>
The AJAX code:
<script>
$(document).ready(function(){
$('#submit').click(function(e){
// remove the error class
$('.input-group').removeClass('has-error');
//remove the previous
$('.help-block').remove();
var Comment = $('#Comment').val();
var scenery_id = $('#scenery_id').val();
var uploader_id = $('#uploader_id').val();
var datastring = 'Comment'+Comment+'&scenery_id'+scenery_id+'&uploader_id'+uploader_id;
$.ajax({
type:'POST',
url: "<?php echo base_url('display_scenery/add_comment')?>",
data: datastring,
datatype: 'json',
cache: 'false',
encode: true
});
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if(!data.success){
$('#data.errors.input-group'){
$('#iput-group').addClass('has-error');
$('#iput-group').append('<div class= "help">' + data.errors.Comment+'</div>');
} else {
$('#form').append('<div class="alert">'+ data.message+'</div>');
}
)};
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
}*/
// prevent default action
e.preventDefault();
});
});
</script>
The back end code in CodeIgniter:
public function add_comment(){
if(!$this->session->userdata('logged_in')) {
$data['error'] = 'Signup needed to comment on a scenery';
} else {
$this->load->library('form_validation');
$session_data = $this->session->userdata('logged_in');
$User_id= $session_data['User_id'];
$scenery_id = $_POST['Scenery_id'];
$Comment=$_POST['Comment'];
$this->form_validation->set_rules('Comment', 'Comment', 'trim|required');
if($this->form_validation->run() == FALSE) {
$data['error'] = validation_errors();
} else {
//loads the model image_display then redirects to scenery page
$this-> image_display->add_comment( $scenery_id,$User, $Comment);
$data['Comment']=$this-> image_display->get_comments($scenery_id);
$data['success'] = TRUE;
}
}
echo json_encode($data);
}
I want a system where the user can comment and the comments can be displayed. I'm trying to locate why the code is not working,kindly assist, I'm relatively new to AJAX.
try this :
<script>
$(document).ready(function(){
$('#submit').click(function(e){
// remove the error class
$('.input-group').removeClass('has-error');
//remove the previous
$('.help-block').remove();
var datastring = $("#form").serialize();
$.ajax({
type:'POST',
url: "<?php echo base_url('display_scenery/add_comment')?>",
data: datastring,
datatype: 'json',
cache: 'false',
encode: true
});
.done(function(data)
{
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if(!data.success){
$('#data.errors.input-group'){
$('#iput-group').addClass('has-error');
$('#iput-group').append('<div class= "help">' + data.errors.Comment+'</div>');
}
else
{
$('#form').append('<div class="alert">'+ data.message+'</div>');
}
)};
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
}*/
// prevent default action
e.preventDefault();
});
});
</script>

Post without form submit and GET

I was redirecting to new page start.php and passing variable in this way:
window.location.href = 'start.php?&userid=+ userid;`
Can I do it in this way:
$.post('start.php',{userid: userid});
window.location.href = 'start.php';
I dont want to use GET and Form submit.
Because on same page there are other processes which already post data to other page.
I tested above but on start.php it says var is not defined
UPDATE
start.php
<?php
$user_id=$_GET['userid']; //When I use GET
?>
<?php
$user_id=$_POST['userid']; //When I use POST
?>
login.php
<html>
<head>
<title>ThenWat</title>
<link href="css/button.css" rel="stylesheet" type="text/css">
<link href="css/rateit.css" rel="stylesheet" type="text/css">
<script src="//connect.facebook.net/en_US/all.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script src="js/jquery.rateit.js" type="text/javascript"></script>
<style>
.header{
background-color:#0B6121;
border:2px solid #0B6121;
padding:10px 40px;
border-radius:5px;
}
.middle{
background-color:Yellow;
}
.left{
background-color:Green;
}
.url{
box-sizing: border-box;
display: block;
}
.url:hover {
box-shadow: 2px 2px 5px rgba(0,0,0,.2);
}
html, body { margin: 0; padding: 0; border: 0 }
</style>
</head>
<body>
<div class="header" style="">
<table style="">
<tr>
<td><img src= "3.png" height="50" width="310"/></td>
</tr>
</table>
</div>
<table border="0" width="100%">
<tr>
<div class="middle">
<td style="width:40%">
<input type="button" id="loginButton" class="button" onclick="authUser();" value="Login | ThanWat" style="display:none; left:500px; position:relative"/>
<lable id="lable1" style="display:none;" ><i> Please wait .. </i> </lable>
<div class="rateit bigstars" id="rateit99" data-rateit-starwidth="32" data-rateit-starheight="32" style=" position:relative; top:-30px; display:none; left:300px" >
</div>
</td>
</div>
</tr>
</table>
<div id="fb-root"></div>
<script type="text/javascript">
var userid;
FB.init({
appId: '1412066',
xfbml: true,
status: true,
cookie: true,
});
FB.getLoginStatus(checkLoginStatus);
function authUser()
{
FB.login(checkLoginStatus, {scope:'email'});
}
function checkLoginStatus(response)
{
document.getElementById('lable1').style.display = 'block';
if(response && response.status == 'connected')
{
FB.api('/me?fields=movies,email,name', function(mydata)
{
console.log(mydata.email);
console.log(mydata.id);
userid=mydata.id;
var name=mydata.name;
//alert(name);
var email=mydata.email;
var json = JSON.stringify(mydata.movies.data);
var a = JSON.parse(json);
var picture="https://graph.facebook.com/"+userid+"/picture?type=small";
// alert(picture);
$.post('user_record.php',{'myd':a, name: name, email: email, userid:userid, picture:picture}, function(data)
{
window.location.href = 'start.php?userid='+userid;
});
});
console.log('Access Token: ' + response.authResponse.accessToken);
}
else
{
document.getElementById('lable1').style.display = 'none';
document.getElementById('loginButton').style.display = 'block';
}
}
</script>
</body>
</html>
UPDATE2
$.post('user_record.php',{'myd':a, name: name, email: email, userid:userid, picture:picture}, function(data)
{
var $form = $("<form id='form1' method='post' action='start.php'></form>");
form.append('<input type="hidden" name="userid" value="'+userid+'" />');
$('body').append($form);
window.form1.submit();
});
start.php
<?php
$user_id=$_POST['userid'];
echo $user_id;
?>
Here is a solution that worked for me. You need to add a new form using jquery after your first ajax response and then submit this form using javascript.
<script>
$.post('user_record.php',{'myd':a, name: name, email: email, userid:userid, picture:picture}, function(data){
var $form = $("<form id='form1' method='post' action='start.php'></form>");
$form.append('<input type="hidden" name="userid" value="'+data+'" />');
$('body').append($form);
window.form1.submit();
});
</script>
Please modify it according to your requirement. Hope this helps

append data and write comment the comment repeated

I have a problem
When added 3 posts and write a comment on the Post number 2 comment repeated.
Clarify more
when i added 3 posts
post 1 = a
post 2 = b
post 3 = c
and write a comment on post 2 this comment repeated pleas help
like this photo
this is the file
index.php
<? include("../post/includes/config.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$("#update_state").submit(function(){
var text = $(".text") .val();
var s = {
"text":text
}
$.ajax({
url:'action.php',
type:'POST',
data:s,
cache: false,
beforeSend: function (){
$(".loading") .show();
$(".loading") .html("loading...");
},
success:function(html){
$("#show_new_posts") .prepend(html);
$(".loading") .hide();
$(".text") .val("");
}
});
return false;
});
//add comment
$(".comment_form").submit(function(){
var id_post = $(this).attr('rel');
var text_comm = $(".commtext[rel="+id_post+"]") .val();
var s = {
"id_post":id_post,
"text_comm":text_comm
}
$.ajax({
url:'add_comment.php',
type:'post',
data:s,
beforeSend: function (){
$(".loadingcomm[rel="+id_post+"]") .show();
$(".loadingcomm[rel="+id_post+"]") .html("<img src=\"style/img/ajax/load1.gif\" alt=\"Loading ....\" />");
},
success:function(html){
$(".loadingcomm[rel="+id_post+"]").hide();
$(".commtext[rel="+id_post+"]") .val("");
$(".shownewcomm[rel="+id_post+"]").append(html);
}
});
return false;
});
});
</script>
</head>
<body>
<form id="update_state">
<textarea class="text" name="text"></textarea>
<input type="submit" value="go" />
</form>
<div class="loading"></div>
<div id="show_new_posts"></div>
<?
$select_posts = $mysqli->query("SELECT * FROM posts ORDER BY id DESC LIMIT 4 ");
$num_posts = $select_posts->num_rows;
if($num_posts){
while ($rows_posts = $select_posts->fetch_array(MYSQL_ASSOC)){
$id_posts = $rows_posts ['id'];
$post_posts = $rows_posts ['post'];
?>
<div style="padding: 5px; margin: 5px; background:#ccc; width:300px;">
<b>admin</b>
</div>
<div style="padding: 5px; margin: 5px; background:#ccc; width:300px;">
<? echo $post_posts; ?>
</div>
<div class="shownewcomm" rel="<? echo $id_posts; ?>"></div>
<form rel="<? echo $id_posts; ?>" class="comment_form">
<textarea rel="<? echo $id_posts; ?>" style="height: 20px;" placeholder="Comment.." class="commtext"></textarea>
<input type="submit" value="comment" />
</form>
<hr />
<?
}
}
?>
</body>
</html>
action.php
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(function(){
$(".comment_form").submit(function(){
var id_post = $(this).attr('rel');
var text_comm = $(".commtext[rel="+id_post+"]") .val();
var s = {
"id_post":id_post,
"text_comm":text_comm
}
$.ajax({
url:'add_comment.php',
type:'post',
data:s,
beforeSend: function (){
$(".loadingcomm[rel="+id_post+"]") .show();
$(".loadingcomm[rel="+id_post+"]") .html("<img src=\"style/img/ajax/load1.gif\" alt=\"Loading ....\" />");
},
success:function(html){
$(".loadingcomm[rel="+id_post+"]").hide();
$(".commtext[rel="+id_post+"]") .val("");
$(".shownewcomm[rel="+id_post+"]").append(html);
}
});
return false;
});
});
</script>
<?php
include("../post/includes/config.php");
$text = $_POST['text'];
$insert = $mysqli->query("INSERT INTO posts (id, post) VALUE ('', '$text')");
$id_posts = $mysqli->insert_id;
if($insert){
?>
<div style="padding: 5px; margin: 5px; background:#ccc; width:300px;">
<b>admin</b>
</div>
<div style="padding: 5px; margin: 5px; background:#ccc; width:300px;">
<? echo $text; ?>
</div>
<div class="shownewcomm" rel="<? echo $id_posts; ?>"></div>
<form rel="<? echo $id_posts; ?>" class="comment_form">
<textarea rel="<? echo $id_posts; ?>" style="height: 20px;" placeholder="Comment.." class="commtext"></textarea>
<input type="submit" value="comment" />
</form>
<hr />
<?
}
?>
add_comment.php
<?php
$id_post = $_POST['id_post'];
$text_comm = $_POST['text_comm'];
?>
admin : <? echo $text_comm; ?>
<br />
You have $(".comment_form").submit with ajax call in index.php and action.php. And in index.php you are prepending action.php result like this
$("#show_new_posts").prepend(html);
May be because of this there will be more than one ajax call. Remove all JavaScript code from action.php and try
Update:
Changes made in action.php are as below:
Removed jquery reference from it as already there in index.php and moved other JS code at the end
Added id in form
<form rel="<?php echo $id_posts; ?>" id="comment_form_<?php echo $id_posts; ?>" class="comment_form">
Updated submit handler to use form id like this:
$("#comment_form_<?php echo $id_posts; ?>").submit(function(){
Updated action.php code is as below:
<?php
include("../post/includes/config.php");
$text = $_POST['text'];
$insert = $mysqli->query("INSERT INTO posts (id, post) VALUE ('', '$text')");
$id_posts = $mysqli->insert_id;
if ($insert) {
?>
<div style="padding: 5px; margin: 5px; background:#ccc; width:300px;">
<b>admin</b>
</div>
<div style="padding: 5px; margin: 5px; background:#ccc; width:300px;">
<?php echo $text; ?>
</div>
<div class="shownewcomm" rel="<?php echo $id_posts; ?>"></div>
<form rel="<?php echo $id_posts; ?>" id="comment_form_<?php echo $id_posts; ?>" class="comment_form">
<textarea rel="<?php echo $id_posts; ?>" style="height: 20px;" placeholder="Comment.." class="commtext"></textarea>
<input type="submit" value="comment" />
</form>
<hr />
<script type="text/javascript">
$(function() {
$("#comment_form_<?php echo $id_posts; ?>").submit(function(){
var id_post = $(this).attr('rel');
var text_comm = $(".commtext[rel=" + id_post + "]").val();
var s = {
"id_post": id_post,
"text_comm": text_comm
}
$.ajax({
url: 'add_comment.php',
type: 'post',
data: s,
beforeSend: function() {
$(".loadingcomm[rel=" + id_post + "]").show();
$(".loadingcomm[rel=" + id_post + "]").html("<img src=\"style/img/ajax/load1.gif\" alt=\"Loading ....\" />");
},
success: function(html) {
$(".loadingcomm[rel=" + id_post + "]").hide();
$(".commtext[rel=" + id_post + "]").val("");
$(".shownewcomm[rel=" + id_post + "]").append(html);
}
});
return false;
});
});
</script>
<?php
}
?>

Categories