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
}
?>
Related
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"/>
I am trying to delete files inside folder, using delete_file.php, which is action file offcourse. It can recieve data as $_POST['filename1'] only, but for every foreach() iteration , this value is getting over-written. Any suggestions, what else can SOLVE this subject? Thanks in Advance.
Problem:
delete_file.php is catching filename1 as $_POST['filename1']
But with each foreach iteration, filename1 is getting over-written.
And delete_file.php, is deleting LAST ENTRY ONLY, EVERY TIME.
<!DOCTYPE HTML>
<html>
<head>
<title></title>
<meta charset="utf-8"/>
<meta name="viewport" content="width=device-width, initial-scale=1"/>
<!--[if lte IE 8]>
<script src="assets/js/ie/html5shiv.js"></script><![endif]-->
<link rel="stylesheet" href="assets/css/main.css"/>
<!--[if lte IE 8]>
<link rel="stylesheet" href="assets/css/ie8.css"/><![endif]-->
<!--[if lte IE 9]>
<link rel="stylesheet" href="assets/css/ie9.css"/><![endif]-->
<script src="assets/js/jquery.min.js"></script>
<script src="assets/js/jquery.leanModal.min.js"></script>
</head>
<body class="no-sidebar">
<table border="1px solid" style="text-align:center; margin-left:auto; margin-right:auto; width:900px">
<tr>
<th><strong>S.No</strong></th>
<th><strong>Image-Name</strong></th>
<th><strong>Image/Logo</strong></th>
<th><strong>Image Size</strong></th>
<th><strong>Action</strong></th>
</tr>
<?php
$dirname = "../assets/img/logos/";
$images = glob($dirname . "*.{jpg,png,gif,tiff,jpeg,JPG}", GLOB_BRACE);
$sn = 1;
foreach ($images as $image) {
$imageName = str_replace("../assets/img/logos/", "", $image);
$variable_id = str_replace(".", "_", $imageName);
?>
<!---///////////////////// IMAGE-<?= $sn++ ?> STARTS //////////////////////----------->
<tr>
<td><?= $sn++ ?></td>
<td><?php echo $imageName; ?></td>
<td><img src="<?php echo $image; ?>" width="150px" height="100px"/></td>
<td><?php echo filesize($image) / 1000 . " KB"; ?></td>
<!-------
<td>
<a id="delete" href="delete_plogos.php?filename=<?//=$imageName ?>" style="color:#D00A0D"><strong>Delete</strong></a>
</td>
-------->
<td>
<p style="text-align: center; font-size: 10px; margin-top: 5px;">
<a id="modaltrigger_<?= $variable_id ?>" href="#<?= $variable_id ?>" class="btn"
style="border: none !important;">Delete</a>
</p>
</td>
</tr>
<!----------------------popup for delete----------------------->
<div id="<?= $variable_id ?>" class="popupContainer" style="display:none;">
<header class="popupHeader" style="background: #F4F4F2;
position: relative;
padding: 10px 20px;
border-bottom: 1px solid #DDD;
font-weight: bold; height: 55px;">
<span class="header_title">Delete</span>
<span class="modal_close"><i class="fa fa-times"></i></span>
</header>
<section class="popupBody">
<!-- Register Form -->
<div class="deleteplogo_<?= $variable_id ?>">
<form id="newpageform_<?= $variable_id ?>" name="newpageform_<?= $variable_id ?>" method="post">
<input name="filename_<?= $variable_id ?>" id="filename_<?= $variable_id ?>" type="text" style="display:none"
value="<?= $imageName ?>"/>
<p><strong><?= $imageName ?> - Image will be deleted Permanently. <br/>Proceed
?</strong></p>
<br/>
<div class="action_btns">
<div class="one_half" style="float:none;">
<a id="ajax-submit_<?= $variable_id ?>" class="btn btn_red" style="cursor: pointer"
>Yes! I
Agree
.Delete</a></div>
</div>
</form>
</div><!--------delete_plogo----------->
</section>
</div> <!----------------------#modal ENDS----------------------->
<!---------------- delete image : pop up ------------------------------>
<script type="text/javascript">
var magica = "<?php echo $variable_id; ?>";
$('#modaltrigger_' + magica).leanModal({top: 200, overlay: 0.6, closeButton: ".modal_close"});
$(function () {
$('#modaltrigger_' + magica).click(function () {
$('.deleteplogo_' + magica).show();
return false;
});
})
/////// 3.) AJAX-FORM SUBMIT - + then reload
$("#ajax-submit_"+magica).click(function () {
var filename = $("#filename_"+magica).val();
if (filename == '') {
alert("File doesn't EXIST....!!");
} else {
$.post("delete_plogos_action.php", {filename1: filename}, function (data) {
$("span.modal_close > i").trigger("click"); // to auto-close leanModal window
alert(data).fadeOut("slow");
window.location=trustedpartners_listviewdel_logos.php;
//close_modal("modal");
});
}
});
</script>
<!---///////////////////// IMAGE-ENDS //////////////////////----------->
<?php
}
?>
</table>
</body>
</html>
You can try something like removing the php loop:
<script type = "text/javascript" >
$(function() {
$('div[id^="modaltrigger_"]').leanModal({
top: 200,
overlay: 0.6,
closeButton: ".modal_close"
});
$('div[id^="modaltrigger_"]').click(function() {
magica = $(this).attr('id').split('_')[1];
$('.deleteplogo_' + magica).show();
return false;
});
})
$('div[id^="ajax-submit_"]').click(function() {
magica = $(this).attr('id').split('_')[1];
var filename = $("#filename_" + magica).val();
if (filename == '') {
alert("File doesn't EXIST....!!");
} else {
$.post("delete_file.php", {
filename1: filename
}, function(data) {
$("span.modal_close > i").trigger("click");
//alert(data).fadeOut("slow"); damn you can't fade out a alert box :))
window.location = mypage.php;
} // else ends here
});
}); < /script>
A better solution will be to replace the ids with a class and append a data-attribute to the elements iwth the value of magica
Deleted all AJAX-JQUERY code & used :
file1.php
<td>
<p style="text-align: center; font-size: 10px; margin-top: 5px;">
<a id="modaltrigger_<?= $variable_id ?>" href="delete.php?id=<?php echo $imageName; ?>" class="btn"
style="border: none !important;">Delete</a>
</p>
</td>
delete.php
<?php
$filePath = "D:/folder/".$_GET['id'];
if(is_file($filePath)){
#unlink($filePath);
echo ('<strong>SUCCESS! Deleted: <span style="color:red">'. $_GET['id']. '</span>, file from Directory</strong>');
}
else if(!unlink($filePath)){
echo ("Error deleting file : ". $_GET['id']. " Already deleted OR doesn't EXIST");
}
?>
Worked like Charm ! Thanks !
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
I'm trying to dynamically load a form that will is populated from the number of rows in a sql data base. The data returns a hex color, name, and price. I want to display the color and the name to the user within the form and on the POST, I want to send the price attached to that specific color. I've spent all day trying to figure this out.
Any help would be greatly appreciated!
EDIT: (here's what I have so far
Here's an example of what I have :http://hruska-schuman.com/test2/feedback_form.php
Code:
$query = "SELECT
`name`,
img,
price
FROM `gutter`";
try
{
$stmt = $db->prepare($query);
$stmt->execute();
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$rows = $stmt->fetchAll();
$form =
'<ol id="selectable" name="selectable">';
foreach($rows as $row):
$prices[] = htmlentities($row['price'], ENT_QUOTES, 'UTF-8');
$form .= '<li class="ui-widget-content" style="background:#'.htmlentities($row['img'], ENT_QUOTES, 'UTF-8').'">'.htmlentities($row['name'], ENT_QUOTES, 'UTF-8').' Price: '.htmlentities($row['price'], ENT_QUOTES, 'UTF-8').'</li>';
endforeach;
$form .=' </ol>';
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Hruska Gutter Estimator</title>
<link rel="stylesheet" href="../extras/selecttable/development-bundle/themes/base/jquery.ui.all.css">
<script src="../extras/selecttable/development-bundle/jquery-1.9.1.js"></script>
<script src="../extras/selecttable/development-bundle/ui/jquery.ui.core.js"></script>
<script src="../extras/selecttable/development-bundle/ui/jquery.ui.widget.js"></script>
<script src="../extras/selecttable/development-bundle/ui/jquery.ui.mouse.js"></script>
<script src="../extras/selecttable/development-bundle/ui/jquery.ui.selectable.js"></script>
<link rel="stylesheet" href="../extras/selecttable/development-bundle/demos/demos.css">
<style>
#feedback { font-size: 1.4em; }
#selectable .ui-selecting { background: #000000; }
#selectable .ui-selected { background: #000000; color: white; }
#selectable { list-style-type: none; margin: 0; padding: 0; width: 60%; }
#selectable li { margin: 3px; padding: 0.4em; font-size: 1.4em; height: 18px; }
</style>
<SCRIPT type="text/javascript">
function isNumberKey(evt)
{
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
</SCRIPT>
<script type="text/javascript">
$(function() {
$( "#selectable" ).selectable({
stop: function() {
var result = $( "#select-result" ).empty();
$( ".ui-selected", this ).each(function() {
var index = $( "#selectable li" ).index( this );
result.append( "" + ( index + 1) );
return index;
});
}
});
});
</script>
</head>
<body>
<h1>New Gutter Estimator!</h1>
<form action="sendmail.php" method="post">
<table>
<tr>
<td>Gutter Color:</td>
<td>
<?php echo $form; ?>
<span id="select-result" name="result">none</span>
<span id="select-result" name="price"><?php echo $prices; ?></span>
</td>
</tr>
<tr>
<td>Board Feet:</td>
<td>
<input type="txtChar" onkeypress="return isNumberKey(event)" name="spouts" value="" maxlength="120" />
</td>
</tr>
<tr>
<td>Number of Spouts:</td>
<td>
<input type="txtChar" onkeypress="return isNumberKey(event)" name="board_feet" value="" maxlength="120" />
</td>
</tr>
<tr>
<td>E-mail to Recieve Estimate:</td>
<td>
<input type="text" name="email_address" value="" maxlength="120" />
</td>
</tr>
<tr>
<td>Additional Comments:</td>
<td>
<textarea rows="10" cols="50" name="comments"></textarea>
</td>
</tr>
<tr><td> </td>
<td>
<input type="submit" value="Get Your Free Estimate!" />
</td>
</tr>
</table>
</form>
</body>
</html>
Using JQuery UI select table: http://jqueryui.com/selectable/
I just don't know how to get get the selected index and post "$prices[selectedIndex]"
You should use a custom attribute (like data- attribute) to your color elements.
$form .= '<li class="ui-widget-content" style="background:#'.
htmlentities($row['img'], ENT_QUOTES, 'UTF-8').'"
data-price=".$row['price'].">'.
htmlentities($row['name'], ENT_QUOTES, 'UTF-8').
' Price: '.htmlentities($row['price'], ENT_QUOTES, 'UTF-8').
'</li>
so then in your js you can do something like this:
$(function() {
$( "#selectable" ).selectable({
stop: function() {
var result = $( "#select-result" ).empty();
$( ".ui-selected", this ).each(function() {
var price = $( "#selectable li" ).attr('data-price');
result.append( "" + ( price ) );
// or you can set it directly to an input / hidden input
$('#price-input').val(price);
return price;
});
}
});
});
Where #price-input could be a hidden input into the form:
<input type="hidden" name="selectedPrice" />
Of course you could also use radio inputs for this.
I have these two files:
<?php
include('db.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=iso-8859-1" />
<title>Generic Title</title>
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".edit_tr").click(function()
{
var ID=$(this).attr('id');
$("#time_"+ID).hide();
$("#character_"+ID).hide();
$("#message_"+ID).hide();
$("#status_"+ID).hide();
$("#time_input_"+ID).show();
$("#character_input_"+ID).show();
$("#message_input_"+ID).show();
$("#status_input_"+ID).show();
}).change(function()
{
var ID=$(this).attr('id');
var time=$("#time_input_"+ID).val();
var character=$("#character_input_"+ID).val();
var message=$("#message_input_"+ID).val();
var status=$("#status_input_"+ID).val();
var dataString = 'id='+ ID +'&time='+ time + '&character='+ character + '&message='+ message+ '&status='+ status;
$("#character_"+ID).html('<img src="load.gif" />');
if(time.length>0 && message.length>0 && character.length>0 && status.length>0)
{
$.ajax({
type: "POST",
url: "table_edit_ajax.php",
data: dataString,
cache: false,
success: function(html)
{
$("#time_"+ID).html(time);
$("#character_"+ID).html(character);
$("#message_"+ID).html(message);
$("#status_"+ID).html(status);
}
});
}
else
{
alert('Enter something.');
}
});
$(".editbox").mouseup(function()
{
return false
});
$(document).mouseup(function()
{
$(".editbox").hide();
$(".text").show();
});
});
</script>
<style>
body
{
font-family:Arial, Helvetica, sans-serif;
font-size:14px;
}
.editbox
{
display:none
}
td
{
padding:7px;
}
.editbox
{
font-size:14px;
width:135px;
background-color:#ffffcc;
border:solid 1px #000;
padding:4px;
}
.edit_tr:hover
{
background:url(edit.png) right no-repeat #80C8E5;
cursor:pointer;
}
th
{
font-weight:bold;
text-align:left;
padding:4px;
}
.head
{
background-color:#333;
color:#FFFFFF
}
</style>
</head>
<body bgcolor="#dedede">
<div style="margin:0 auto; width:750px; padding:10px; background-color:#fff; height:800px;">
<table width="100%">
<tr class="head">
<th>Time</th><th>Character</th><th>Message</th><th>Status</th>
</tr>
<?php
$sql=mysql_query("select * from script");
$i=1;
while($row=mysql_fetch_array($sql))
{
$id=$row['id'];
$character=$row['character'];
$time=$row['time'];
$message=$row['message'];
$status=$row['status'];
if($i%2)
{
?>
<tr id="<?php echo $id; ?>" class="edit_tr">
<?php } else { ?>
<tr id="<?php echo $id; ?>" bgcolor="#f2f2f2" class="edit_tr">
<?php } ?>
<td width="10%" class="edit_td">
<span id="time_<?php echo $id; ?>" class="text"><?php echo $time; ?></span>
<input type="text" value="<?php echo $time; ?>" class="editbox" id="time_input_<?php echo $id; ?>" />
</td>
<td width="25%" class="edit_td">
<span id="character_<?php echo $id; ?>" class="text"><?php echo $character; ?></span>
<input type="text" value="<?php echo $character; ?>" class="editbox" id="character_input_<?php echo $id; ?>"/>
</td>
<td width="55%" class="edit_td">
<span id="message_<?php echo $id; ?>" class="text"><?php echo $message; ?></span>
<input type="text" value="<?php echo $message; ?>" class="editbox" id="message_input_<?php echo $id; ?>"/>
</td>
<td width="10%" class="edit_td">
<span id="status_<?php echo $id; ?>" class="text"><?php echo $status; ?></span>
<input type="text" value="<?php echo $status; ?>" class="editbox" id="status_input_<?php echo $id; ?>"/>
</td>
</tr>
<?php
$i++;
}
?>
</table>
</div>
</body>
</html>
and
<?php
include("db.php");
if($_POST['id'])
{
$id=mysql_escape_String($_POST['id']);
$time=mysql_escape_String($_POST['time']);
$character=mysql_escape_String($_POST['character']);
$message=mysql_escape_String($_POST['message']);
$status=mysql_escape_String($_POST['status']);
$sql = "update script set time='$time',character='$character',message='$message',status='$status' where id='$id' ";
mysql_query($sql)
or die("display_db_query:" . mysql_error());
}
?>
They don't seem to be throwing errors, but edits also aren't committing to the database. Where am I going wrong?
db.php contains the connect script with all the right "stuff" (all the right fields are showing, the UPDATE just doesn't seem to want to play right)
A working demo to show what it's supposed to do (most of the code is borrowed) is at http://demos.9lessons.info/table_edit/TableEdit.htm
Thanks in advance for any light you can help shed on this, I'm a stumped noob.
character is a reserved word in MySQL. If you want to use it, you'll need to escape it with backticks
UPDATE script SET time='$time', `character` = '$character' ...