Tinymce plugin not getting textarea value to upload in database - php

I am trying to upload data in database.
I using tinymce plugin to textarea editor. When I submit my data, textarea value uploads empty text. Please find below the frontend and backend code.
Frontend Code:
<form id="upload" enctype="multipart/form-data" method="post">
<textarea class="tinymce" name="product_tip" id="product_tip" placeholder="" col="5"></textarea>
<input type="button" name="submit" value="Submit" class="upload-btn"/>
</form>
Backend Code:
<?php
$product_tip=$_POST["product_tip"];
if(empty($product_tip)) {
echo "<div class='alert alert-danger'>Please enter Product tips.</div>";
}
else{
$result=mysqli_query($conn, "INSERT INTO product(tip) VALUES ('$product_tip')")or die("Could not retrieve image: " .mysqli_error($conn));
echo 1;
}
?>
and this my connection code for frontend and backend file.
$(document).ready(function(){
$('.upload-btn').click(function(){
var formdata=new FormData($('#upload')[0]);
$.ajax({
url:'includes/backend_product_upload.php',
method: "POST",
async: false,
cache: false,
contentType: false,
processData: false,
data : formdata,
success:function(answer_from_actionpage){
if(answer_from_actionpage == 1){
$('.error').html("<div class='alert alert-success'>Successfully Product Upload</div>");
//$('.form-control').val("");
}else{
$('.error').html(answer_from_actionpage);
}
}
})
});
});

Add tinyMCE.triggerSave(); in connection file like this-
$('.upload-btn').click(function(){
tinyMCE.triggerSave();
var formdata=new FormData($('#upload')[0]);
$.ajax({
url:'includes/backend_product_upload.php',
method: "POST",
async: false,
cache: false,
contentType: false,
processData: false,
data : formdata,
success:function(answer_from_actionpage){
if(answer_from_actionpage == 1){
$('.error').html("<div class='alert alert-success'>Successfully Product Upload</div>");
//$('.form-control').val("");
}else{
$('.error').html(answer_from_actionpage);
}
}
})
});

By default, TinyMCE will automatically update the underlying <textarea> when the form is submitted via standard HTML form submission. This is built-in behavior in TinyMCE as the overhead of keeping the <textarea> constantly in sync is not needed for most applications.
If you are not relying on a standard HTML form submission event you have a couple of options...
When you start the AJAX form submission process:
TinyMCE has a triggerSave() method that forces the editor to sync with the <textarea> immediately.
https://www.tinymce.com/docs/api/tinymce/root_tinymce/#triggersave
You can call the triggerSave() first thing when your user wants to submit the form and then perform your validation.
TinyMCE Events:
As your response to your own question shows you can certainly rely on various editor events to sync the editor to the <textarea> via the triggerSave() method. There is no technical issue with this just know that you will likely trigger a large number of these events if you rely on something like the change event. If you have large/complex HTML content or many editors on one page constantly syncing with the underlying <textarea> may impact the browser's performance.
Which is better?
If you DON'T need real time validation of the content... just calling triggerSave() at the start of the AJAX submission process is probably easier (no TinyMCE configuration code tied to an event needed) and creates less overhead for the browser.
If you DO need real time validation of the content... using an event like the change event to sync the <textarea> is the better solution. It might look like this:
tinymce.init({
selector: "#myTextarea",
...
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
}
});

Related

Jquery Preview Video In Div After PHP Validation Not Working While An Image Does

I use the following code successfully (with different IDs, etc.) to preview a banner image in a div after PHP validates the upload, using AJAX. This works just fine. No issues.
I am having a problem doing the same with a video. The code below works well, except the video doesn't preview. Just echos back the alt tag value. I am passing the uploaded video ID to a hidden input for some back end PHP validation via ajax function. After validation, the video is moved to the folder I want it to move to without a problem. I also echo back an error if the video doesn't meet requirements. This is all good. The video just doesn't show on the page. Any help is appreciated.
<div>Upload Video</div>
<div><input type="file" id="banner-video"></div>
<div id="loading"></div>
<div class="padding-top-1" id="show-video"></div>
<script>
$(document).ready(function() {
$("#banner-video").change(function() {
var data = new FormData();
data.append("file", $("#banner-video")[0].files[0]);
$.ajax({
url: "create-promotions/video-banner-promotions/create-promotion.video.process-banner-video.php",
method: "POST",
data: data,
contentType: false,
processData: false,
cache: false,
beforeSend: function() {
$("#loading").load("../loading.php");
},
success: function(data) {
$('#loading').hide()
$('#show-video').html(data); // ********** This line seems to be the problem
if ($('#show-video').find('img').length) {
bannerVideo = $('#show-video').html(data);
document.getElementById("the-banner-video").value =
bannerVideo
}
}
});
});
});
</script>
<input type="hidden" id="the-banner-video" value="">
Nevermind. After 3 days of working on it, it was just using the wrong tag on my back end php echo. The code works. Feel free to use it if you ever come across it. Let me know if you would like the other pieces.

Ajax, JQuery Validation, and MVC

I have an issue I can't seem to solve. First some context that may be relevant.
I am building a MVC-like (I say "like" because I'm still learning how MVC works) php framework for my software. I want all the input forms to submit data via ajax to a backend controller that routes the data and inputs it into the appropriate database. All the HTML code is generated through php classes and the JavaScript in included through php classes.
The problem I'm having is with the ajax function. It keeps trying to submit the post request normally while I want it to submit asynchronously. I've had it working properly at various points in time but it seems to break when I change aspects of the framework. I've tried various combinations of "form.preventDefault()" and "return false" but it doesn't seem to matter. The validation part works (it won't submit with invalid entries. Using this plugin). I discovered that JavaScript caches itself and I've worked through that by appending version numbers to the file name.
Here is the ajax code. It returns a message to the user about the status of the request. Any idea why it refuses to submit asynchronously?
$(document).ready(function() {
// Initialize form validation
***old code
$("form[name='ajaxform']").validate({ ***
// Specify validation rules
***Updated code
$('#ajaxsubmit').on('click', function() {
$("#ajaxform").valid();
});
// Initialize form validation
$('#ajaxform').validate({ ***
....[omitting the validation rules for brevity]
errorElement : 'div',
errorLabelContainer: '#usermessage',
submitHandler: function(form) {
$.ajax({
cache : false,
url : $(form).attr('action'),
type : 'POST',
dataType: 'text',
data : $(form).serialize(),
success : function(data) {
var response = $.parseJSON(data);
if(response['error']){
$('#usermessage').html(response['error']);
}else{
if(response['success']){
$('#usermessage').css({"color":"#00b300","font-weight":"bold"});
$('#usermessage').html(response['success']);
}
}
},
error : function(err) {
alert(err);
}
});
return false;
}
});
});
Here's how I've handled having problems with forms trying to submit even when I'm trying to preventDefault().
I haven't seen your HTML markup so I can't be certain.
If you have a
<button type='submit'>Submit</button>
Change it to
<button type='button'>Submit</button>
and then listen for the click on the button with javascript rather than a form submission
You can change the handler:
submitHandler: function(form) {
To handle the events as well:
submitHandler: function(form, event) {
event.preventDefault();

Upload image using AJAX in Joomla 3.0 MVC

I am trying to upload a image using AJAX jquery in a Joomla MVC framework.
Below is the default.php which adds the below javascript script code
$('#icon-submit').on('click',(function(e) {
$.ajax({
url: "index.php?option=com_jsmdownload&task=imageUpload",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
alert(data);
},
error: function(){
}
});
}));
Below is the HTML code which contains a simple file box and a button
<form action="<?php echo JRoute::_('index.php'); ?>" method="POST" name="adminForm" id="adminForm" enctype="multipart/form-data">
<input type="file" id="and_36x36" name="and_36x36">
<input id='icon-submit' type='button' value='Next ->' />
</form>
Below is the PHP code in controller.php for the imageUpload task.
function imageUpload(){
JFactory::getDocument()->setMimeEncoding( 'application/json' );
print_r($_FILES);
JFactory::getApplication()->close();
}
Once I select the file and click on the button the ajax function called and the PHP function also called but the form data is not available inside.
The print_r command always prints an empty array. I don't know what I am doing wrong. I want to get the selected file and upload them into the server and return back to the browser.
I referred multiple posts and cant able to find an answer. Can someone please advice.
UPDATE 1
If I set a independent PHP file as URL then it works. For example
url: "http://localhost/test/indextest.php",
But If I set the Joomla component path with controller it doesn't work.
You have to pass the form to the FormData object, what you have is the button.
in the button click event handler this refers to the button not the form.
Select the form and pass it to the FormData constructor
new FormData($(this).closest('form')[0]),

Ajax & Jquery form submission

I'm about to pull the hair out of my head with this one.
I'm sure the problem is simple, I'm new to Ajax with Jquery and I'm just overlooking something. But Man this is annoying. Every time the form is submitted, the page refreshes and .ajax throws error:. What could be causing this? I know I'm getting my form values to the Jquery for sure. And newcomment.php is working. I can post regular forms to it, but not with jquery.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
EDIT: Here's my html form:
<form>
<textarea id="comment" placeholder="Post Comment..."></textarea>
<input id="album" type="hidden" value="<?php echo "$a"?>"/>
<input id="photo" type="hidden" value="<?php echo "$p.$ext"?>"/><br/>
<button id="photo-comment-submit" onclick="postPhotoComment()">Post</button>
</form>
I also noticed that if I give the inputs names, Chrome puts them into the url bar like GET variables. And after every page refresh, it adds the ? at the end of the url. So, it seems like its trying to submit the form regularly.
Are you returning false to stop the browsers default action?
$('form').submit(function(){
var dataString = $(this).serialize(); // shortcut
$.ajax({
type: "POST",
url: "/includes/actions/photo-gallery/newcomment.php",
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
});
return false;// cancels the default action
});
If the function where you're calling the AJAX form submission code is the onSubmit method of the form, you'll need to stop the default action from happening -- that is, you want to stop normal submission.
To accomplish this, use the preventDefault method of the event object:
function postPhotoComment(evnt) {
evnt.preventDefault();
// existing code continues...
}
You may also return false from your event, but be aware that doing so has different effects in different browsers, and that it is not as explicit or reliable as calling preventDefault or stopPropagation directly.
Edit
Also, the error handler is probably getting called because your code initiates the XHR request, but when the browser starts the default action (submitting the form), it cancels any pending XHR requests. This is causing the error handler to be triggered.
Edit 2 I have created a jsFiddle with a working demonstration: http://jsfiddle.net/wXrAU/
Documentation
event.preventDefault method on MDN - https://developer.mozilla.org/en/DOM/event.preventDefault
Make sure that you return false; to the form when submitting, otherwise it will still submit as a "normal" form without using Ajax and reload the page.
EDIT: After reading the comments I think that this would be most appropriate for you:
<form action="url.php" onsubmit="return false;"></form>
jsFiddle with appropriate code: http://jsfiddle.net/SO_AMK/ZVgNv/
The PHP messes things up a little, but it works.
I actually fixed this by simply removing the <form> tags. I didn't need them anyways. But everything seems to work now.
Make sure you write a valid, HTTP-accessible url instead of just a path to a script, e.g.
function postPhotoComment() {
var comment = $("#comment").val();
var album = $("#album").val();
var photo = $("#photo").val();
var dataString = "comment="+comment+"&album="+album+"&photo="+photo;
$.ajax({
type: "POST",
url: "http://yoursite.com/whatever/newcomment.php", // here
data: dataString,
success: function(res) {
alert("Posted!");
}
error: function(res) {
alert("Error!");
}
})
}
Because JavaScript is a client-side language. It knows nothing about your filesystem structure or anything of that kind. And AJAX request is based on HTTP protocol.

ajax jquery search form in PHP

This is my form:
<form id="submitsearch" action="Classes/system/main/searchresult.php" method="POST">
Search by <span style="font-size:15px;">(developer, specialization, profession,major)</span>
<input type="text" name="searchbox" id="searchbox" />
in
<select style="text-align:center;" name="countrysearch" id="countrylist">
<option selected="selected" value="0">None</option>
<option value="1">USA</option>
</select>
<input style="margin-left:25px;" id="submitSearch" type="submit" value="Search"/>
</form>
and this is the Ajax jquery code:
$("#submitSearch").click(function(){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#submitsearch').find('#pagePanel').html(response);
});
Why isn't it working ? The php file is returning the correct result normaly.
But i want it to load inside another div with an id "pagePanel" without reloading, using ajax.
Any help ? I'm new to Ajax.
Edit:
$("#submitbutton").click(function(){
$.ajax({type:'POST', url: 'Classes/system/main/searchresult.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
}})});
This worked out with me.
Thanks for all your help.
If you have a input of type submit, it will, guess what :), submit the form, and therefore reload the page. Turn it into:
<input style="margin-left:25px;" id="submitSearch" type="button" value="Search"/>
Then make sure you actually have a pagePanel element in your html.
And now a couple of suggestions:
don't id your form #submitsearch and the button as #submitSearch... confusion may arise
you can use AJAX's .load() instead of .ajax() to get directly the result in the DIV:
So:
$("#pagePanel").load('Classes/requests/search.php', {$('#submitsearch').serialize()});
If you want to use ajax in the form submition you'll need to cancel it.
$("#submitSearch").click(function(event){
$.ajax({type:'POST', url: 'Classes/requests/search.php', data:$('#submitsearch').serialize(), cache: false, success: function(response) {
$('#pagePanel').html(response);
});
event.preventDefault();//prevents submitting of the form
}
First you need to stop the default form submittal. return false in the submit handler to stop default. Just use the ID of the element without using find() to insert data into. The elemnt you are trying to find doesn't appear in your html though within the form where your code suggests it should be
$("#submitSearch").click(function(){
$.ajax({type:'POST',
url: 'Classes/requests/search.php',
data:$('#submitsearch').serialize(),
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
})
return false;
});
After pushing the submit button, the default behaviour is to submit the form and indeed go to the action URL you provided to your form. Now, you want to prevent that behaviour. This means, you'll have to look at the onsubmit event of the form, and prevent the actual submission. jQuery has a preventDefault() method to do this.
In your case, all you'll have to do is add the following code:
$(document).ready(function() {
$("#submitsearch").on("submit", function (e) {
e.preventDefault();
});
});
And here is a jsFiddle to demonstrate it.
You can obviously do the same thing to your submit button, just add the e variable as the argument to your click event and use e.preventDefault() to cancel the actual submit (but you can still perfectly do the AJAX request).
First of all, you are missing a few closing parenthesis and curly brackets. Be sure to run your dev tools in your browser to check console for errors like that. I normally don't use $.ajax...I usually use $.post, but using what you have so far, I would rewrite to something closer to:
$("#submitsearch").submit(function(){
var submitData = $(this).serialize();
$.ajax(
{
type:'POST',
url: 'Classes/requests/search.php',
data: submitData,
cache: false,
success: function(response) {
$('#pagePanel').html(response);
}
}
);
return false;
});​
Instead of sending back loads of HTML to the page, you could just send results in form of a set of JSON objects and then dynamically create the HTML based on the results, this means a lot less data being sent back to the browser which is quicker and more efficient.

Categories