Upload images to the chat function as the message - socialkit script - javascript

Sorry questions I might be confusing but this should reveal that I can help from the teacher teacher here. This script is part of the social network socialkit script.
How to keep the chat function directly upload images could serve as the messaging menu.
<div class="chat-textarea">
<textarea class="auto-grow-input" onfocus="SK_focusChat();" onkeyup="SK_sendChatMessage(this.value,<?php echo $sk['chat']['recipient']['id']; ?>,event);"></textarea>
<div class="advanced-options">
<i class="icon-smile cursor-hand" onclick="javascript:$('.chat-emoticons-wrapper').toggle();"></i>
<div class="chat-emoticons-wrapper">
<?php
$emoticons = SK_getEmoticons();
if (is_array($emoticons)) {
foreach ($emoticons as $emo_code => $emo_icon) {
echo '<img src="' . $emo_icon . '" width="16px" onclick="addEmoToChat(\'' . $emo_code . '\');">';
}
}
?>
</div>
</div>
<input class="message-photo-input hidden" name="photos[]" type="file" accept="image/jpeg,image/png" onchange="SK_uploadMessageForm();">
<div class="options-wrapper" style="float:left ; margin-top:5px">
<i class="icon-camera progress-icon cursor-hand" title="<?php echo $lang['upload_photo']; ?>" valign="middle" onclick="$('.message-photo-input').click();"></i>
</div>
</div>
<?php
}
?>
</div>
</div>
And this is the javascript on the chat.
<script>
function SK_sendChatMessage(text,recipient_id,e) {
document.title = document_title;
textarea_wrapper = $('.chat-textarea');
chat_messages_wrapper = $('.chat-messages');
if (e.keyCode == 13 && e.shiftKey == 0) {
e.preventDefault();
textarea_wrapper.find('textarea').val(''); chat_messages_wrapper.append('<div class="chat-text align-right temp-text" align="right"><div class="text-wrapper float-right">' + text + '<div class="marker-out"><div class="marker-in"></div></div></div><div class="float-clear"></div></div>');
$.post(SK_source() + '?t=chat&a=send_message', {text: text, recipient_id: recipient_id}, function (data) {
chat_messages_wrapper
.append(data.html)
.scrollTop(chat_messages_wrapper.prop('scrollHeight'))
.find('.temp-text')
.remove();
});
}
}
// upload photo chat
function SK_uploadMessageForm() {
document.title = document_title;
$('chat_messages_wrapper').submit();
SK_progressIconLoader($('.chat-textarea').find('.options-wrapper'));
}
</script>
It javascript to be able to send picture messages
function SK_sendMessageForm(e) {
document.title = document_title;
if (e.keyCode == 13 && e.shiftKey == 0) {
e.preventDefault();
$('form.send-message-form').submit();
SK_progressIconLoader($('.textarea-container').find('.options-wrapper'));
}
}
function SK_uploadMessageForm() {
document.title = document_title;
$('form.send-message-form').submit();
SK_progressIconLoader($('.textarea-container').find('.options-wrapper'));
}
It send the form of a message
<div class="textarea-container" align="center">
<form class="send-message-form" method="post" enctype="multipart/form-data">
<textarea class="message-textarea auto-grow-input" name="text" placeholder="<?php echo $lang['write_a_message_label']; ?>..." onkeyup="SK_sendMessageForm(event);" onfocus="SK_sendMessageForm(event);" data-height="22" disabled></textarea>
<input class="message-photo-input hidden" name="photos[]" type="file" accept="image/jpeg,image/png" onchange="SK_uploadMessageForm();">
<div class="options-wrapper">
<i class="icon-camera progress-icon cursor-hand" title="<?php echo $lang['upload_photo']; ?>" valign="middle" onclick="$('.message-photo-input').click();"></i>
</div>
<input name="timeline_id" value="<?php echo $sk['user']['id']; ?>" type="hidden">
<input id="recipient-id" name="recipient_id" value="0" type="hidden">
</form>
</div>
</div>
</div>
My questions, this code upload image not work on chat.
<input class="message-photo-input hidden" name="photos[]" type="file" accept="image/jpeg,image/png" onchange="SK_uploadMessageForm();">
<div class="options-wrapper" style="float:left ; margin-top:5px">
<i class="icon-camera progress-icon cursor-hand" title="<?php echo $lang['upload_photo']; ?>" valign="middle" onclick="$('.message-photo-input').click();"></i>
</div>
I look forward to help you all.

Related

How to serialize form data by number in javascript and submit with a specific number

I'm working on a personal project, where I've more forms than one (comment forms under each post). Each form I give a number according to post id.
<form id="postCommentsForm<?php echo $ansRow['id'];?>" class="form">
<div class="input-group mb-3">
<a href="user/<?php echo $username;?>">
<img class="p-1 m-0" src="images/<?php echo $userAvatar;?>" width="35" height="35" alt="<?php echo $userAvatar;?> profile picture">
</a>
<input name="post_comment<?php echo $ansRow['id'];?>" id="add_comments" type="text" autofocus autocomplete="off" class="add_comments form-control pl-3 pr-3" placeholder="<?php echo $userFname;?>, type something" aria-label="Recipient's username" aria-describedby="button-form">
<input type="text" hidden id="question_id" name="question_id" value="<?php echo $row['id'];?>">
<input type="text" hidden id="answer_id" name="answer_id" value="<?php echo $ansRow['id'];?>">
<input type="text" hidden id="session_id" name="session_id" value="<?php echo $_SESSION['id'];?>">
<div class="input-group-append">
<button class="btn btn-secondary submit-comments" type="submit" name="submit_comment<?php echo $ansRow['id'];?>" id="postComments">Comment</button>
</div>
</div>
</form>
javascript code
$(document).ready(function() {
$("[id^=postCommentsForm]").on("submit", function(e) {
e.preventDefault();
var add_comments = $("#add_comments").val();
var question_id = $("#question_id").val();
var answer_id = $("#answer_id").val();
// var session_id = $("#session_id").val();
if(add_comments == "" ){
$("#error-message").html("All fields are required!").slideDown();
$("#success-message").slideUp();
}else{
//Ajax
$.ajax({
url: "include/forms-data/comments.php",
type: "POST",
data: {
add_comments: add_comments,
question_id: question_id,
answer_id: answer_id
},
success: function(data) {
if (data != 0) {
$("[id^=postCommentsForm").trigger("reset");
$("#success-message").html("Question Added Successfully!").slideDown();
$("#error-message").slideUp();
} else {
//alert("Can't save record");
$("#error-message").html("Something went wrong!").slideDown();
$("#success-message").slideUp();
}
}
});
}
});
});
How I can fetch #comments(postID here), and submit form data successfully under the postID?
I hope I define well the question.
Jquery's "starts with selector" can help. check out here
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
var element_id = this.getAttribute("id");
});
});
Live Demo:
$(document).ready(function() {
$("[id^=comments]").click(function(e) {
console.log($(this).attr('id'));
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id='comments1'>b</button>
<button id='comments2'>a</button>

Multiple Ajax Forms using Wordpress Loop

I am trying to make multiple Ajax forms work in a Wordpress loop. I have given the form and fields in each form a unique ID. I'm trying to reference each form within the javascript in order to submit the AJAX form but instead the page refreshes as if it's trying to submit the form using php. I am no expert and can't figure out how this works. The script works for an individual form as I can reference the actual form_id directly within the javascript. I want to be able to submit the form on each post within the loop without having to refresh the page. Thanks in advance for your help.
Javascript in the template that contains the loop.
<script>
var form_id = $(this).closest("form").attr('id');
form_id.validate({
highlight: function(element, errorClass, validClass) {
$(element).parent('label').addClass('errors');
},
unhighlight: function(element, errorClass, validClass) {
$(element).parent('label').removeClass('errors');
},
submitHandler: function(form) {
$.ajax({
type: "POST",
url: '<?php echo admin_url(); ?>admin-ajax.php',
data: form_id.serialize(),
beforeSend: function() {
$("input[name=submit],button", form).attr('disabled', 'disabled');
$("div.loading", form).show();
$("div.status", form).hide();
},
success: function(result) {
if (result == 1 || result == '1') {
$("div.loading", form).hide();
$("div.thanks").slideDown();
document.forms["leadForm"].reset();
} else {
$("div.loading", form).hide();
$("input[name=submit],button", form).removeAttr('disabled');
$("div.status", form).html(result).show();
}
}
});
}
});
</script>
The form within the loop.
<?php $pid = get_the_ID(); ?>
<form name="leadForm" method="post" id="leadForm-<?php echo $pid; ?>" action="#">
<div class="grid-x grid-padding-x">
<div class="medium-12 cell">
<textarea tabindex="2" rows="6" cols="30" maxlength="350" title="Please enter a message" name="message" id="message-<?php echo $pid; ?>" placeholder="Your message" ></textarea>
</div>
<div class="medium-6 cell">
<label>Full Name
<input type="text" placeholder="Full Name" class="required" autocomplete="off" name="fullname" id="fullname-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-6 cell">
<label>Email Address
<input type="email" placeholder="Email Address" class="required" autocomplete="off" name="email" id="email-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-12 cell">
<label>Phone Number
<input type="tel" placeholder="Phone Number" class="required" autocomplete="off" name="phone" id="phone-<?php echo $pid; ?>" >
</label>
</div>
<div class="medium-12 cell">
<button class="button submit radius expanded" type="submit" >Send</button>
<div class="loading" style="display:none;" >
<img src="<?php echo get_template_directory_uri(); ?>/images/progress.gif" alt="Loading..." />
</div>
<div class="status callout radius alert small" style="display:none; text-align:center;">There was an error sending your message.
</div>
<div class="thanks callout radius success small" style="display:none; text-align:center;">Thank you.
</div>
<input type="hidden" name="current_url" value="<?php echo the_permalink(); ?>" class="button" />
<input type="hidden" name="current_title" value="<?php echo the_title(); ?>" class="button" />
</div>
</div>
</form>
The php script within the Wordpress - functions.php
<?php
add_action('wp_ajax_nopriv_leadForm', 'core_leadForm');
add_action('wp_ajax_leadForm', 'core_leadForm');
function core_leadForm()
{
if (!((isset($_POST['fullname']) && !empty($_POST['fullname'])) && (isset($_POST['email']) && !empty($_POST['email'])) && (isset($_POST['phone']) && !empty($_POST['phone'])) && (isset($_POST['message']) && !empty($_POST['message'])) ))
{
echo 'Enter all fields';
}
else if (!is_email($_POST['email']))
{
echo 'Email is not valid';
}
else
{
if (function_exists('ot_get_option'))
{
//$to = ot_get_option('cont_email');
$to = 'email#website.com';
}
else
{
$to = '';
}
}
}
ob_start();
?>
<br>
<table>
<tr>
<td><b><u>CONTACT DETAILS</u></b><br>
<br></td>
<td> </td>
</tr>
<tr>
<td><b>Full Name:</b></td>
<td><?php echo $_POST['fullname'] ?></td>
</tr>
<tr>
<td><b>Phone Number:</b></td>
<td><?php echo $_POST['phone'] ?></td>
</tr>
<tr>
<td><b>Email Address:</b></td>
<td><?php echo $_POST['email'] ?></td>
</tr>
<tr>
<td><b>Link:</b></td>
<td><?php echo $_POST['current_title'] ?></td>
</tr>
<tr>
<td><b>Message:</b></td>
<td><?php echo $_POST['message'] ?></td>
</tr>
</table>
<?php
$message = ob_get_contents();
ob_end_clean();
$subject = 'NEW MESSAGE';
$headers[] = 'From: ' . $_POST["fullname"] . ' <' . $_POST["email"] . '>';
add_filter('wp_mail_content_type', 'core_html_content_type');
function core_html_content_type()
{
return 'text/html';
}
if (wp_mail($to, $subject, $message, $headers))
{
// echo "test";
echo 1;
}
else
{
echo 'Your message failed to send. Please try again.';
}
die();
?>
Hard to replicate all the issues that WP might have with your code. But it would be one of these:
this when used outside of an reference to an html object refers to window. .closest travels up the dom tree, not down, so it will not find forms within the window object. The same effect of what you want to achieve can be achieved by $('form').attr('id'), i.e. return the id of the 1st form found.
You need to ensure $ is defined before using, this is a WP quirk of using the shipped version of jquery, you substitute the word jQuery for $
I see no evidence that jQuery is loaded by the time you use it, you are also using another library, .validate, make use of $(document).ready();
Also on a side note, learn how to use the console (e.g. in chrome), you can output js here to test variables, any errors in your code will output here too.

Change image according to id in mysql

Good Day, I am working on a simple project so that I could get used to php,mysql,
Here is my code
PHP
if(isset($_POST["edit"]))
{
$update_data = array(
'crit_1' => mysqli_real_escape_string($data->con, $_POST['crit_1']),
'crit_2' => mysqli_real_escape_string($data->con, $_POST['crit_2']),
'crit_3' => mysqli_real_escape_string($data->con, $_POST['crit_3']) ,
);
$where_condition = array(
'id' => $_POST["id"]
);
if($data->update("tbl_tabulation", $update_data, $where_condition))
{
header("location:index.php?updated=1");
}
}
if(isset($_GET["updated"]))
{
$success_message = 'Post Updated';
}
?>
And my HTML:
<div id="pagewrap">
<section id="content">
<script type = "text/javascript">
function pic1()
{
document.getElementById("img").src = "img/new.jpg";
}
function pic2()
{
document.getElementById("img").src ="img/new2.gif";
} </script>
<div class="table-responsive">
<div class="list-group">
cand1
cand2s
</table>
</div>
</section>
<section id="middle">
<img src="" id="img">
<img src="" id="img">
</section>
<aside id="sidebar">
<form method="post">
<?php
if(isset($_GET["edit"]))
{
if(isset($_GET["id"]))
{
$where = array(
'id' => $_GET["id"]
);
$single_data = $data->select_where("tbl_tabulation", $where);
foreach($single_data as $post)
{
?>
<label width="20%"><?php echo $post["cand_name"]; ?></label>
<br />
<!--CRITERIA -->
<label>Poise & Bearing</label>
<input type="text" name="crit_1" value="<?php echo $post["crit_1"]; ?>" class="form-control" width="20%" />
<br />
<label>Modeling</label>
<input type="text" name="crit_2" value="<?php echo $post["crit_2"]; ?>" class="form-control" width="20%"/>
<br />
<label>Overall Impact</label>
<input type="text" name="crit_3" value="<?php echo $post["crit_3"]; ?>" class="form-control" width="20%"/>
<br />
<input type="hidden" name="id" value="<?php echo $post["id"]; ?>" />
<input type="submit" name="edit" class="btn btn-info" value="Edit" />
<?php
}
}
}
else
{
}
?>
<span class="text-success">
<?php
if(isset($success_message))
{
echo $success_message;
}
?>
</span>
</form>
</aside>
<footer>
<h4>Footer</h4>
<p>Footer text</p>
</footer>
</div>
Problem is When I click cand1 or cand2the image will show only for a second. And the middle will be empty again as soon as the URL changes.
Is there any work around for this? any help would be appreciated.
Change this:-
<script type = "text/javascript">
function pic1()
{
document.getElementById("img").src = "img/new.jpg";
}
function pic2()
{
document.getElementById("img1").src ="img/new2.gif";
} </script>
<section id="middle">
<img src="" id="img">
<img src="" id="img1">
</section>
The id shouldn't be the same, id should be unique
Because you are using below code for immediate update and redirect page to updated=1 if you don't want to redirect then use ajax
if($data->update("tbl_tabulation", $update_data, $where_condition))
{
header("location:index.php?updated=1");
}
You need to prevent the default action of the link if you want just the image to change:
cand1
cand2s
If that isn't what you want, then you need to change the image by index.php when it loads the news page. Other options are to use event.preventDefault():

Image upload Ajax PHP Mysql

I am writing a code for image upload and want to implement AJAX for real time preview. As I have to upload four images on different button and they call different PHP file to upload in respective directory.
My code is working fine for single image upload as it needs to pass form ID.
but not working for all four images.
Please help me out and provide solution.
Below is the code -
<script type="text/javascript">
$(document).ready(function (e) {
$("#upload").on('submit',(function(e) {
e.preventDefault();
$.ajax({
url: "update_profile_img.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data)
{
$("#targetLayer").html(data);
},
error: function()
{
}
});
}));
});
</script>
<div class="col-md-6">
<!-- Horizontal Form -->
<div class="box box-info">
<div class="box-header with-border">
<h3 class="box-title">Upload Documents</h3>
</div><!-- /.box-header -->
<!-- form start -->
<?php include('update_profile_img.php');?>
<?php include('update_car_img.php');?>
<?php include('update_licen_img.php');?>
<?php include('update_doc_img.php');?>
<p style="color:green"><?php echo $successMessage;?></p>
<p style="color:red"><?php echo $Error;?></p>
<div class="box-body">
<form role="form" action="#" id="upload" method="POST" enctype="multipart/form-data">
<div class="form-group">
<img class="form-control" style="width:100px; height:100px" alt="" src=<?php echo $target_file; ?> >
<label for="exampleInputFile">Profile Image</label>
<input type="file" class="form-control" name="image" id="image" />
<input type="hidden" class="form-control" name="user_id" value="<?php echo $user_id;?>" />
<button type="submit" name="profile_btn" class="btn btn-primary">Upload</button> <!-- -->
<small>File should be in image format.</small>
</div>
<div class="form-group">
<img class="form-control" style="width:100px; height:100px" alt="" src=<?php echo $target_file1;?> >
<label for="exampleInputFile">Car Image</label>
<input type="file" class="form-control" name="car_image" id="car_image" />
<button type="submit" name="car_btn" class="btn btn-primary">Upload</button>
<small>File should be in image format.</small>
</div>
<div class="form-group">
<img class="form-control" style="width:100px; height:100px" alt="" src=<?php echo $l_img;?> >
<label for="exampleInputFile">Driving License</label>
<input type="file" class="form-control" name="drivelic" id="drivelic"/>
<button type="submit" name="licen_btn" class="btn btn-primary">Upload</button>
<small>File should be in image format.</small>
</div>
<div class="form-group">
<img class="form-control" style="width:100px; height:100px" alt="" src=<?php echo $d_img;?> >
<label for="exampleInputFile">Vehicle Documents</label>
<input type="file" class="form-control" name="vehicledoc" id="vehicledoc"/>
<button type="submit" name="doc_btn" class="btn btn-primary">Upload</button>
<small>File should be in image format.</small>
</div>
</form>
<div class="box-footer">
</div>
</div><!-- /.box-body -->
</form>
</div><!-- /.box -->
</div><!-- /.box-body -->
</div><!--/.col (right) -->
</div> <!-- /.row -->
</section><!-- /.content -->
</div><!-- /.content-wrapper -->
PHP code to upload profile image update_profile_img.php-
<?php
include('../config/conn.php');
$Error ="";
$successMessage ="";
if (isset($_POST['profile_btn'])){
if(!empty($_POST['user_id']) && !empty($_FILES['image']))
{
if($_FILES['image'] != "jpg" && $_FILES['image'] != "png" && $_FILES['image'] != "jpeg" && $_FILES['image'] != "gif" && $_FILES["image"]["size"] > 2097152 )
{
//echo "6";
$Error="Invalid Image!";
}
else
{ $id=$_POST['user_id'];
$target_dir = "images/profile/";
$db_dir = "images/profile/";
$date=rand(0,999);
$datemd=md5($date);
$date=substr($datemd,2,-7);
//$unique_id=substr($date, 3, -3);
$target_file = $target_dir .$date. basename($_FILES["image"]["name"]);
$user_image = $db_dir .$date. basename($_FILES["image"]["name"]);
//$pic=addslashes (file_get_contents($_FILES['image']['tmp_name']));
if (move_uploaded_file($_FILES["image"]["tmp_name"], $target_file))
{
$sql = "UPDATE pooler SET image='$user_image' WHERE id='$id'";
if ($conn->query($sql) === TRUE)
{
//echo "1";
$successMessage="Profile Image Updated Successfully!";
return '$target_file';
}
else
{
//echo "2";
$Error="Error in Updating Image!";
}
}
else
{
$Error="Image Not Inserted Properly!";
}
}
}
else
{
//echo "4";
$Error="Fill The Required Fields!";
}
}
?>
PHP code to upload car image
<?php
include('../config/conn.php');
$Error ="";
$successMessage ="";
if (isset($_POST['car_btn'])){
if(!empty($_POST['user_id']) && !empty($_FILES['car_image']))
{
if($_FILES['car_image'] != "jpg" && $_FILES['car_image'] != "png" && $_FILES['car_image'] != "jpeg" && $_FILES['car_image'] != "gif" && $_FILES["car_image"]["size"] > 2097152 )
{
//echo "6";
$Error="Invalid Image!";
}
else
{ $id=$_POST['user_id'];
$target_dir = "images/car/";
$db_dir = "images/car/";
$date=rand(0,999);
$datemd=md5($date);
$date=substr($datemd,2,-7);
//$unique_id=substr($date, 3, -3);
$target_file1 = $target_dir .$date. basename($_FILES["car_image"]["name"]);
$user_image = $db_dir .$date. basename($_FILES["car_image"]["name"]);
//$pic=addslashes (file_get_contents($_FILES['image']['tmp_name']));
if (move_uploaded_file($_FILES["car_image"]["tmp_name"], $target_file1))
{
$sql = "UPDATE pooler SET car_image='$user_image' WHERE id='$id'";
if ($conn->query($sql) === TRUE)
{
//echo "1";
$successMessage="Car Image Updated Successfully!";
return 'target_file1';
}
else
{
//echo "2";
$Error="Error in Updating Image!";
}
}
else
{
$Error="Image Not Inserted Properly!";
}
}
}
else
{
//echo "4";
$Error="Fill The Required Fields!";
}
}
?>
I also try to include all upload file code in one file and pass different Target_file variable as target_file and target_file1.

Using a name selector instead of an id

How can I change the following code to work off of a name selector instead of the id?
<div id="light" class="change_group_popup">
<a class="close" href="javascript:void(0)">Close</a>
JavaScript
$('.change_group').on('click',function(){
$("#light,.white_overlay").fadeIn("slow");
});
$('.close').on('click',function(){
$("#light,.white_overlay").fadeOut("slow");
});
UPDATE:
I added more of my code to show the loop to help explain what I am doing in more detail.
$runUsers2 = mysqli_query($con,"SELECT * FROM users ORDER BY id DESC");
$numrows2 = mysqli_num_rows($run2);
if( $numrows2 ) {
while($row2 = mysqli_fetch_assoc($run2)){
if($row2['status'] == "Approved"){
//var_dump ($row2);
$approved_id = $row2['user_id'];
$approved_firstname = $row2['firstname'];
$approved_lastname = $row2['lastname'];
$approved_username = $row2['username'];
$approved_email = $row2['email'];
if ($approved_firstname == true) {
echo "Name - ". $approved_firstname . " " . $approved_lastname . "</br>" .
"Username - ". $approved_username . "</br></br>"
?>
<div class="change_group_button">
<a class="change_group" href="javascript:void(0)">Change User Permission</a>
</div><br>
<div class="change_group_popup light">
<a class="close" href="javascript:void(0)">Close</a>
<div class="group_success" style="color: red;"></div><br>
<form class="update_group" action="" method="POST">
<div class="field">
<label for="group">Group</label>
<input type="hidden" value="<?php echo $approved_id; ?>" name="approved_id" />
<input type="hidden" value="<?php echo $approved_firstname; ?>" name="approved_firstname" />
<input type="hidden" value="<?php echo $approved_lastname; ?>" name="approved_lastname" />
<input type="hidden" value="<?php echo $approved_username; ?>" name="approved_username" />
<input type="hidden" value="<?php echo $approved_email; ?>" name="approved_email" />
<select name='group_id' required>
You can get any element by name attribute by:
$('[name="someName"]')
Use DOM traversal functions to find the related element.
$(".change_group").click(function() {
var light = $(this).closest(".change_group_button").nextAll(".light").first(); // Find the next .light DIV after the button
light.add($(".white_overlay")).fadeIn("slow");
}):

Categories

Resources