3

PHP newbie here. I want to save a variable (from jQuery) in PHP/MySQL, but this variable is outside the form. The values from the form elements inside the form is being saved fine though. The variable name in this case is 'mode', and I want the 'mode' to be sent to PHP.

Here's code :

HTML form;

<form action="submit.php" method="post" id="myform">
 <textarea id="source1" name="source1"></textarea>
<textarea id="source2" name="source2"></textarea>
 <input type="image" src="images/save.png" name="submit" id="submit" title="Save"  class="save-button"/>    
</form>

jQuery / AJAX:

mode = 1;  // This value needs to be stored/saved

// AJAX form save
$("form#myform").submit( function () {    
$.post(
'submit.php',
$(this).serialize(),
function(data){
....
}
);

PHP:

$submit_time = date('Y/m/d H:i:s');
$content1 = $_POST['source1'];
$content2 = $_POST['source2'];
$mode = $_POST['mode'];  // This value needs to be stored/saved

Is the solution to create a hidden form field inside the form?

1
  • Are you trying to submit the form, or send it with ajax. If you're OK with submitting the form and redirecting the page, a hidden input is the way to go. Commented Nov 23, 2013 at 21:22

3 Answers 3

2

If the variable is not inside the form it doesn't get send to the server.

The solution is to put the variable into hidden field inside the form

Sign up to request clarification or add additional context in comments.

Comments

2

jQuery's serialize() serializes the form into a querystring, so you really just have to add to that string :

mode = 1;

$("form#myform").submit( function (e) {    
    e.preventDefault();
    var data = $(this).serialize() + '&mode=' + mode;
    $.post('submit.php', data, function(data){

    });
});

or to submit the form with a hidden input:

$("form#myform").submit( function (e) {  
    e.preventDefault();
    $(this).append( $('<input />', {type:'hidden', name:'mode', value:mode}) );
    this.submit();
});

Comments

1

Try:

// AJAX form save
$("form#myform").submit( function () {    
    $.post('submit.php', $.extend($(this).serializeArray(), { mode: mode }), function(data){
        ....
    });
});

1 Comment

Why serialize? Maybe serializeArray ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.