Tips for posting images upon clicking a div instead of a submit button

I previously had a code that allowed users to click on the submit button and have the text inside a contenteditable div passed to upload.php using JQuery, inserted into a database, and immediately displayed. Now, I want to modify this code to also handle images - uploading them to upload.php, inserting them into a MySQL database, and displaying them after storage. How can I adjust the code below to achieve this? Most resources I found suggest handling image uploads with form submitting buttons, which is not what I'm looking for.

Here's the HTML and CSS code:

<html>
<head>
  <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
</head>
<body>
  <div id="topic_content_input" contenteditable="true"></div>
  <input multiple class="fileInput" type="file" id="files" name="files[]"/>
  <br>
  <div id="submit" > Click me to upload the photo to upload.php</div>
  <div name="topicreturn"></div>
</body>
</html>

<script>
$(function(){
        $("#submit").click(function(){

            var txtContent = $("#topic_content_input").text();
                if(txtContent){

                    $.post("upload.php", {txtContent:txtContent}, function(result){
                        $("div[name=topicreturn]").prepend(result);
                        $("#topic_content_input").text('');
                    });
                 }
})
})

</script>

<style>
#topic_content_input{
    height: 60px;
    width:350px;
    border:1px solid blue;
}
#submit{
    background-color: #ffcc99;
    display:inline-block;
    padding:5px;
    border-radius: 3px;
    cursor:pointer;
}
</style>

And here's the PHP file (upload.php):

<?php
require('connect.php');


$content=$_POST["txtContent"];

$sql="insert into topics (content) VALUES ('".$content."')";
        $result=mysqli_query($conn,$sql);
        if($result){
            echo $content;
        }
        else{
            echo $content;

        }

?>

Answer №1

Using the submit() Method with Forms

The submit() method is used to trigger the submission of a form, which is equivalent to clicking the Submit button.

document.getElementById("myForm").submit();

Incorporating this into your code, it would look like:

<form id="myForm" action="form_action.asp">
<div id="topic_content_input" contenteditable="true"></div>
  <input multiple class="fileInput" type="file" id="files" name="files[]"/>
  <br>
  <div id="submit" onClick="subForm();"> click me to pass the photo to upload.php</div>
  <div name="topicreturn"></div>
</form>

<script>
function subForm() {
    document.getElementById("myForm").submit();
}
</script>

Answer №2

To enable click tracking in jQuery, you can utilize the div id.


$(".business-bottom-content").click(
function() {
var txtContent = $("#topic_content_input").text();
if(txtContent) {
$.post("upload.php", {txtContent:txtContent}, function(result){
$("div[name=topicreturn]").prepend(result);
$("#topic_content_input").text('');
});
}
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Can I use Javascript to make changes to data stored in my SQL database?

I am delving into the realm of SQL and Javascript, aiming to insert my variable ("Val_Points from javascript") into a table ("Usuarios") associated with a specific user (e.g., Robert). Is it possible to achieve this using JavaScript, or are there alternati ...

Enable divs to be interactively chosen

I have created two selectable divs that function like buttons. By using the left and right arrow keys, I am able to select one of the divs with this code: document.addEventListener("keydown", keyDownDocument, false); function keyDownDocument(e) { var k ...

KnockoutJS is unable to assign a negative value to an input field

Is there a way to assign the value of an <input> as false? It seems to work fine with true. Data Model: function DataModel(){ self = this; self.Flag = ko.observable(false); }; HTML Code: <input type="text" data-bind="value:Flag"/> ...

ReactJS encountered an error: _this3.onDismissID is not defined as a function

My goal is to retrieve the latest news related to a specific search term from a website, showcase them, and provide a dismiss button next to each news item for users to easily remove them if desired. Here's a snippet of the code I'm using: import ...

Using DraftJS to swap text while preserving formatting

Currently, I am implementing Draftjs with draft-js-plugins-editor and utilizing two plugins: draft-js-mathjax-plugin and draft-js-mention-plugin My goal is to replace all mentions with their corresponding values when the user uses '@' to mention ...

Count the number of results in Laravel using the `whereHas` method

I have a specific relationship set up: User->hasMany(Posts) and User->belongsToMany(Following). Now I am trying to accomplish the following task: Retrieve all the users that a user is following, who have a certain type of post. So far, I have managed ...

Building a family tree with JavaScript's Document Object Model

My goal is to use jQuery to construct the following DOM setup: <li> <label> user <input type=radio> </label> </li> Below is the jQuery code I am trying to use. $('<input>') .attr({type:'radio&ap ...

Storing intricate items in a JavaScript database can be tricky. Using JSON.stringify() can sometimes lead to unexpected errors

In my project, I have a class called Player and a list of players named gameData. My goal is to save and retrieve this gameData from a database so that user information remains intact even after the bot restarts or crashes. However, when attempting to use ...

When using jQuery's `text()` function, the `<br>` element is interpreted as a

When trying to retrieve an element from the DOM like this $('#id').content().text(); An issue arises when the element contains: <p>Hello</p> <p><br></p> <p>World</p> In HTML, it would look like: Hell ...

What is the best way to handle identical routes within two separate route groups in Blade?

I have set up two resource controllers within separate route groups - one for users and one for admins. Route::group([ 'prefix' => 'dashboard', "middleware" => 'auth', "namespace" => 'U ...

JavaScript basic calculator app failed to generate an error as anticipated

For my homework assignment, I am developing a basic calculator application using JavaScript. My main task is to ensure that the input numbers are limited to only two and that they are valid numbers; otherwise, an error should be thrown. Initially, concern ...

Caution: React alert for utilizing the UNSAFE_componentWillReceiveProps in strict mode

As a newcomer to React, I encountered a warning that has me stuck. Despite researching extensively online, I still can't resolve it. The warning message is: https://i.stack.imgur.com/4yNsc.png Here are the relevant portions of the code in App.tsx: ...

While scrolling, the menu is being truncated

When I scroll down the page, the top menu is being partially hidden. Take a look here for reference. I want to maintain a consistent width for the header at all times. ...

The issue of Access-Control-Allow-Origin not functioning properly when using Ajax for a POST request

I am encountering an issue with the header "Access-control-allow-origin" when making a request using the following code: <script type='text/javascript'> function save() { $.ajax( { type: 'POST', ur ...

Guide on how to bypass IDM when downloading a PDF file through a GET request

When I try to fetch a PDF by sending a GET request to the server and open it in a new tab, IDM interrupts my request and downloads the file instead. It changes the server response status to 204 and removes the headers. How can I prevent IDM from doing th ...

Setting the value for a HiddenField using jQuery in an ASP.NET application

Is there a way to set a value for a HiddenField control using jQuery? function DisplayContent(obj) { var FareValue = $(obj).closest('tr').find("[id*=lbFare]").text(); $(obj).parent().parent().find('[id*=pnlGrd]').show(); $ ...

Picture fails to load on Ionic app on the device

Currently, I am utilizing Ionic 3 for my project. The location of the images file is \src\assets\img. This pertains to a basic page implementation. export class BasicPage { items = []; constructor(public nav: NavController ,private adm ...

Running a Custom Tab Component in a React Application

I am currently facing an issue with my React app that has multiple tabs. When I click on a specific tab, I want only that tab to render, but currently all tabs are rendering when I click on one. I have used console.log to confirm that all tabs are indeed r ...

Unable to get spacing correct on loading page

My attempt at creating a loading page using CSS and HTML has hit a roadblock. I'm trying to show a loading bar that ranges from 0% to 100%. Despite my use of justify-content: space-between, I can't seem to get it right. I've searched through ...

Navigating through states in AngularJS

My application has three states: app, app.devices, and app.devices.device. While the first two states are functioning properly, the app.devices.device state is not working as expected. Here is the code for reference: http://pastebin.com/r1kYuExp http://pa ...