I m using tinyMCE for textareas and POSTing form through AJAX.
But when I m trying to save textarea value, it is taking old values on first click, but it takes updated values on second click.
I have tried using tinyMCE.triggerSave() but it didn't work.
I have also tried tinyMCE.get('myid').getContent(), still it takes old values.
My code is as follows.
$(".submit").live("click", function () {
tinyMCE.triggerSave();
var f = $(this).parents("form");
var action = f.attr("action");
var serializedForm = f.serialize();
//tinyMCE.triggerSave(); also tried putting here
$.ajax({
type: 'POST',
url: action,
data: serializedForm,
async: false,
success: function (data, textStatus, request) {
$(".divform").html(data);
},
error: function (req, status, error) {
alert&("Error occurred!");
}
});
return false;
});
Please help, any help would be appreciated
You can configure TinyMCE as follows to keep the values of hidden textareas in sync as changes are made via TinyMCE editors:
tinymce.init({
selector: "textarea",
setup: function (editor) {
editor.on('change', function () {
tinymce.triggerSave();
});
}
});
With this in place, you can access up-to-date values directly from the textarea elements at any time.
This has been tested on TinyMCE 4.0
Demo running at: http://jsfiddle.net/9euk9/
Use this instead of tinymce.triggerSave();
$('#' + 'your_editor_id').html( tinymce.get('your_editor_id').getContent() );
An alternative implementation to the one posted by Dan Malcolm, for TinyMCE 3.x, would be as follows:
tinymce.init({
selector: "textarea",
setup: function (editor) {
editor.onChange.add(function() {
editor.save();
});
}
});
As well as working on 3.x, this version uses editor.save instead of tinymce.triggerSave, which means it only updates the current editor rather than all editors in the page.
user this script before posting data by using Ajax. This is javascript code before use please load tiny mce js file and user it.
tinymce.triggerSave();
$.ajax({
type: 'post',
url: 'autoSaveReport.php',
data: $('form').serialize(),
success: function (result) {
var redirectURL = window.location.pathname;
var redirectURL1 = redirectURL+"?incid="+result;
window.location = window.location+"?incid="+result;
}
});
For me works fine with
tinymce.triggerSave();
Put it before the ajax post
I know time passed but i found this solution today.
Before serialize the form you must save the editor just using the method:
tinymce.activeEditor.save();
var serializedForm = f.serialize();
Maybe this helps some comrade.
For multiple instances:
tinymce.init({
mode : "specific_textareas"
,body_class: 'tinymceclass'
,setup: function (editor) {
editor.onChange.add(function() {
$('#' + this.id).html( tinymce.get(this.id).getContent() );
});
}
});
Related
I need to send form data over AJAX so I can access it easily in Laravel (or using standard PHP methods). It's actually a form using Stripe Checkout that I'm stopping from being auto submitted so I can send over AJAX. Currently I have the code below but suspect variable "formdata" is not formatted correctly before being referenced in $.ajax.
What do I need to do to it to make it formatted correctly?
Ideally I want to access the separate form elements on the backend as regular POST vars (or actually I'm using Laravel, so via Request->input() method), will this do that?
Thanks
$('#booking-form').get(0).submit = function() {
var formdata = $(this).serializeArray();
$.ajax({
type: 'POST',
url: 'book',
data: { formdata },
success: function (data)
{
// Form submitted and processed correctly, success returned
},
error: function (data)
{
// console.log('Error:', data.responseText);
}
});
Backend (Laravel 5.4, but I could use raw PHP if I had to):
public function book(Request $request)
{
$formfield1 = $request->input('formfield1');
$formfield2 = $request->input('formfield2');
[etc.]
}
Try this:
$(document).ready( function() {
$('#booking-form').submit( function( e ) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'book',
data: $('#booking-form').serialize(),
success: function (data) {
// Form submitted and processed correctly, success returned
},
error: function (data) {
// console.log('Error:', data.responseText);
}
});
});
});
Not really familiar with Laravel, but certainly accessing the form fields via native PHP (i.e. $_POST['formfield1']) should work perfectly.
So I have this ajax request. When the user clicks an edit link, I fetch the ID of the entry and refresh the page with the data of that entry loaded into a form.
Here's my problem: This only works with the alert showing before the ajax call. When I leave out the alert, I get an ajax error (though the id is being posted) and the PHP page just reloads. Moreover, it only works when I put the newDoc stuff as a success callback. The exact same lines as a complete callback and the page reloads. Moreover, this occurs in Firefox only.
jQuery('a.edit').on('mousedown', function (e) {
e.preventDefault();
var id = jQuery(this).attr('data-title');
alert('test');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
});
What can I do?
EDIT: This must be a timing issue. I just noticed that when I click and hold the edit link for a second or so, everything works fine. When I do a short click, it doesn't. So I tried wrapping the ajax in setTimeout(), but that didn't help. Any other ideas?
Try to use location.href in place of document.location,
jQuery.ajax({
url: location.href,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
},
error: function () {
alert('error');
}
});
location is a structured object, with properties corresponding to the parts of the URL. location.href is the whole URL in a single string.
Got it!
The problem is the way Firefox handles the mousedown event. It seems to abort the ajax call as soon as you relase the mouse button. I changed the event to click and everything is fine now.
jQuery('a.edit').on('click', function () {
var id = jQuery(this).attr('data-title');
jQuery.ajax({
url: document.location,
data: {
id: id
},
success: function (data) {
var newDoc = document.open("text/html", "replace");
newDoc.write(data);
newDoc.close();
}
});
});
I recently asked a question about triggering dynamically created divs, and was introduced to the .on() function.
'keyup' works great, 'mouseover' works, a few others I've tested work but 'click' just will not fire.
I created added information to a div via ajax and .php which holds some data like this:
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html);
}
});
}
I wanted to trigger on keyup for an element within that created div and this code works for that:
$("#notebox").on('keyup', '.note-field', function(event){
var thisString = $(this).val();
$keyLength = thisString.length;
$rowCount = Math.ceil($keyLength/40);
$currentRow = $(this).attr("rows");
if($currentRow < $rowCount){
$(this).animate({rows:$rowCount},50);
}
});
This code however does NOT work:
$("#notebox").on('click', '.note-field', function() {
alert("clicked");
});
dynamic DOM and jQuery is a pain. I know its deprecated but I have used in the past with great results: http://api.jquery.com/live/
FWIW - you could also try using bind() - http://api.jquery.com/bind/
I had an .stopPropagation(); somewhere else in the code in the encompassing div, I commented it out for now and it works, thanks.
Is it possible to attach click event after html is appended.
function loadNewcomment(divID) {
$.ajax({
url: templateUrl+"/enternote.php",
cache: false,
success: function(html){
$("#"+divID).append(html).bind('click', function() { /* Click event code here */ }); // id divID is #notebox
}
});
}
You can just use click like this:
$("#notebox").click( function() {
alert("clicked");
});
http://jsfiddle.net/7MBw4/
UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.
this is an ajax method that inserts the data into a db and should supposedly display the new content.
<script type = "text/javascript">
$(document).ready(function() {
$('#submit').live('click', function(eve) {
eve.preventDefault() ;
var form_data = {
title: $('#title').val()
};
$.ajax({
url: "http://localhost/ci/index.php/chat/comment",
type: 'POST',
data: form_data,
success: function(msg) {
alert(msg);
}
});
});
});
</script>
However in my /chat/comment, i am loading the view again, i.e, user submits a comment, load the view again and the comment should be there. My response from server is the view's HTML. However the view comes with all the divs and there are many of them. I need to retrieve only part of the div, say, #commentspace from the ajax on success.
Look at the jQuery $.load() function?
Example
Inside "firstpage.html"
$('#content').load('secondpage.html #content');