Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When I use jQuery AJAX to submit tinyMCE forms on my page, it takes two clicks to actually submit to database

I've been trying different options for over a week now and nothing seems to work. What makes this slightly more complicated is that I have multiple forms on the page that all need to be tied to this same submit function. They all have different IDs.

The following is a simplified version of my jQuery:

$('form').on('submit', function(form){
    var data = $(this).serialize();
    $.ajax({
        type:       'POST',
        cache:      false,
        url:        'inc/process.php',
        data:       data,
        success:    function(){
                        // The following fires on first AND second submit
                        console.log("Updates have successfully been ajaxed");
        }
    });
    return false;
});

I have also tried using $('form').submit() with the same results.

Relevant sections of process.php:

$query =    'UPDATE     pop_contents
            SET     ';
$id = $_POST['content_id'];
/* to avoid including in MySQL query later */
unset($_POST['content_id']);

$length = count($_POST);
$count = 0;
foreach($_POST as $col => $value){
    $value = trim($value);
    $query .= $col."='".escapeString($value);
    // don't add comma after last value to update
    if(++$count != $length){ $query .= "', "; }
    // add space before WHERE clause
    else{ $query .= "'  "; }
}
$query .= 'WHERE        id='.$id;

$update_result = $mysqli->query($query);
like image 917
Dan Avatar asked Jul 18 '12 18:07

Dan


1 Answers

After much hair pulling and swearing, I've solved the problem.

TinyMCE editor instances do not directly edit textareas, so in order to submit the form, I needed to first call tinyMCE.triggerSave() from the TinyMCE API. So, the working code looks like this:

$('form').on('submit', function(form){
    // save TinyMCE instances before serialize
    tinyMCE.triggerSave();

    var data = $(this).serialize();
    $.ajax({
        type:       'POST',
        cache:      false,
        url:        'inc/process.php',
        data:       data,
        success:    function(){
                        console.log("Updates have successfully been ajaxed");
        }
    });
    return false;
});
like image 118
Dan Avatar answered Sep 28 '22 19:09

Dan