I own a site called flopl.com. It's pretty basic. Upload your files, and get a URL back with a link to the file. But I wasn't the one coding it, and now I can't get help from the person who did anymore. There's something wrong in the code, but I don't know enough to figure out what. So.. Here's the code:
HTML:
<!DOCTYPE html>
<html style="width:100%">
<head>
<title>flopl</title>
<link rel="stylesheet" href="style.css">
<meta charset="utf-8" />
<link rel="shortcut icon" href="http://flopl.com/images/favicon.ico" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<style>
.progress { position:relative; width:400px; border: 1px solid #ddd; padding: 1px; border-radius: 3px; }
.bar { background-color: #B4F5B4; width:0%; height:25px; border-radius: 3px; }
.percent { position:absolute; display:inline-block; top:-1px; left:48%; }
</style>
</head>
<body style="width:100%">
<div style="background-color:#2d2d2d; width: auto; height:150px; padding:-10px; margin-top:-20px;">
</div>
<div style="background-color:#8be1ab; width: auto; height:10px; padding:-10px; margin-top:0px;">
</div>
<center>
<img width="275px" src="images/logo.png" style="position:absolute; margin-top:-145px; margin-left:-145px;" />
</center>
<div style="width:400px; margin:auto; position:relative; margin-top:15%;" >
<center>
<div style="margin-top:90px; margin-left:25px;">
<p style="word-spacing:0.6px; font-family:Helvetica font-weight:light; margin-top:-20px; position:center;">Upload any type of file,</p>
<p style="word-spacing:0.6px; font-family:Helvetica font-weight:light; margin-top:-20px; position:center;">with no compression!</p>
</div>
</center>
<form id="imageform" method="post" enctype="multipart/form-data" action='ajax_image.php'>
<img width="332px" src="images/upload.png" style="position:absolute; top:-120px; left:40px;"/>
<input type="file" name="photoimg" id="photoimg" style="padding: 0; margin: 0; display: none;" />
</form>
<div class="progress" style="display: none;">
<div class="bar"></div >
<div class="percent">0%</div>
</div>
<div id="status"></div>
<center>
<script type="text/javascript" >
$(document).ready(function() {
$('#photoimg').live('change', function() {
$("#preview").html('');
$("#preview").html('<img width="300" src="images/uploading.png" alt="Laddar upp...."/>');
var bar = $('.bar');
var percent = $('.percent');
var status = $('#status');
var progress = $('.progress');
$('#imageform').ajaxForm({
target: '#preview',
beforeSend: function() {
status.empty();
progress.show();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
success: function() {
var percentVal = '100%';
bar.width(percentVal);
percent.html(percentVal);
},
complete: function(xhr) {
//status.html(xhr.responseText);
}
}).submit();
});
});
</script>
<div id='preview' style="margin-top:40px;">
</div>
</center>
</div>
</div>
<div class="footer" id="footer">
<div id="top">
<img id="copyright" src="images/footer.png" alt="">
<a id="logo" href="http://www.simplyvisual.se" target="_blank">
<img width="150px" src="/images/SV.png" alt="Simply Visual">
</a>
</div>
<!--<div class="footer" id="footer"><img style="margin-top:1%; margin-left:0%" width="150" src="images/SV.png" /><img style="margin-top:0%;" src="images/footer.png" />--></div>
</body>
</html>
And the PHP:
<?php
session_start();
$session_id='1'; // User session id
$path = "upload/";
function url($url) {
$url = preg_replace('~[^\\pL0-9_]+~u', '-', $url);
$url = trim($url, "-");
$url = iconv("utf-8", "us-ascii//TRANSLIT", $url);
$url = strtolower($url);
$url = preg_replace('~[^-a-z0-9_]+~', '', $url);
return $url;
}
if(!empty($_POST) && !empty($_FILES['photoimg']) && $_SERVER['REQUEST_METHOD'] == 'POST')
{
$name = $_FILES['photoimg']['name'];
$size = $_FILES['photoimg']['size'];
$pi = pathinfo($name);
$txt = $pi['filename'];
$ext = $pi['extension'];
$actual_image_name = time().$session_id.".".$ext;
$tmp = $_FILES['photoimg']['tmp_name'];
if(move_uploaded_file($tmp, $path.$actual_image_name))
{
echo "Here's the link to your file: <a href='http://flopl.com/".$path.$actual_image_name."'>http://flopl.com/".$path.$actual_image_name."</a>";
}
} else {
echo "Something went wrong.";
exit;
}
?>
The progress-bar is showing, but I only get "Something went wrong" back. I've checked, the PHP.ini is set up correctly. The files are not uploading, and therefor also not giving me a URL back.
Could anyone figure out what's wrong?
Best regards,
primarypanda
I found at least 2 problems with your project.
Your host may allow upload big files but you need to check that file uploads are set or not in PHP.ini file. in most of the CPanels, they allow to make custom php.ini file settings, here you need to set max_file_uploads = 20M or so.
using isset() function may cause some problem, I use !empty() function instead because it checks whether the variable is set and not empty both. so you can do it in your code like...
if(!empty($_POST) && !empty($_FILES['photoimg']) && $_SERVER['REQUEST_METHOD'] == 'POST'){...}
You can notice that I have also checked that $_FILES['photoimg'] are also not empty, that means that the file is actually uploaded.
Best luck and Thank you
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 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
}
?>
I am developing an application where i am capturing images from a camera and streaming them online. To capture images i am using an opencv code. It stores(rewrites) the image on the same image file on server. This image is then streamed online. However if the streaming and storing take place simultaneously then the image gets corrupt. So i have synchronized those processes using system locks. The html page that checks that reloads the image every 2 secs checks if the img file has a system lock. If yes then it doesn't reload the image. So to check whether the file is locked or not i have to put some php code in my html file. I believe that my code is sytactically correct. Yet it is not giving the desired output.
<html>
<head>
<!--to keep requesting the server new page without displaying the image from the cache pragma
is used -->
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<title>YOUR SITE TITLE GOES HERE</title>
<style type="text/css">
#imgJSselbox{
position: absolute;
margin: 0px;
padding: 0px;
visibility: hidden;
width: 0px;
height: 0px;
border: 1px solid #006;
color: #fff;
background-image: url(selection_area.gif);
z-index: 20;
}
</style>
<script type="text/javascript" src="globalvar.js"></script>
<script language="Javascript">
var x = 2;
var y = 1;
var now;
function startClock() {
x = x-y;
document.form1.clock.value = x;
<?php
$fp1=fopen("a.jpg","r");
$fp2=fopen("b.jpeg","r");
if(flock($fp1,LOCK_EX|LOCK_NB)==0 && flock($fp2,LOCK_EX|LOCK_NB)==0)
$x=1;
else
$x=0;
?>
var ch;
ch=<?php echo $x; ?>
if (x < 1 && ch==1) reload();
<?php
$fp1=fopen("a.jpg","r");
$fp2=fopen("b.jpeg","r");
flock($fp1,LOCK_UN);
flock($fp2,LOCK_UN);
?>
timerID = setTimeout("startClock()", 1000);
}
function reload()
{
now = new Date();
<!-- to pass the new image to the src -->
var camImg = "a.jpg" + "?" + now.getTime();
document.campicture.src = camImg;
var crpImg = "b.jpeg" + "?" + now.getTime();
document.croppic.src = crpImg;
x = 2;
document.form1.clock.value = x;
}
</script>
<script type="text/javascript" src="image_cropper.js">
document.form1.x-coord.value=x1;
document.write(x1);
</script>
<script>
function window.open('im','imgg')
{
window.open('im','imgg');
}
</script>
</head>
<body bgcolor="white" onLoad="startClock()">
<center>
<font size=-1>
<h1>AYS WEBCAM PAGE</h1>
<h2>This page loads images and refreshes them after every given interval of time keeping
the same name of the image file</h2><p><br />
<div id="imgJSselbox"></div>
</center>
<img name="campicture" src="a.jpg" id="testimage" border=1 width=640 height=480
alt="AYS
founder's IMAGE" onClick="getImageCropSelectionPoint
'testimage',event,document.form1);">
====>>ROI==>>
<img name="croppic" src="b.jpeg" width=320 height=240 alt="cropped_image">
<center>
<form NAME="form1"action="image_cropper.php" method="POST"><b><font size="-1"
face="Arial">AutoReload in :==> </font>
<input TYPE="text" NAME="clock" SIZE="2" VALUE="5"> <font size="-1"
face="Arial">seconds.</font></b><br />
<br><br><input type="button" value="Crop" onclick= setImageCropAreaSubmit
("image_cropper.php",'testimage')><br><br>
</center>
<!-- <input type="text" name="x-coord" value=""><br>
<input type="text" name="y-coord" value=""><br>
<input type="text" name="wid" value="" ><br>
<input type="text" name="hght" value="" ><br>
-->
</form>
</body>
</html>
Thank you
Your problem is in the code timerID = setTimeout("startClock()", 1000);.
Use
timerID = setTimeout(startClock, 1000); instead.
See window.setTimeout - MDN.