Ajax不发布数据

[SOLVED]

That was THE most difficult bug ever - all due to copy/paste stuff up.

This:

$('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');

should have been that:

$('#errors'+bUID).append('<ul id="error_list'+bUID+'"></ul>');

The damn '+bUID+' was pasted AFTER the " , not BEFORE!

Of course it couldn't append anything to it... 2 weeks...2 WEEKS wasted!!! )))


Here's the js:

$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    e.preventDefault();
    submitForm(bUID);
    alert(bUID);
});

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();
    alert(bUID);

    // also tried this
    var post_data = {
    'name': $('#name'+bUID).val(),
    'email': $('#email'+bUID).val(),
    'message': $('#message'+bUID).val(),
    'code': $('#code'+bUID).val(),
    'buid': bUID,
    };
    alert(Object.keys(post_data).length);


    // ALSO tried this instead of ajax:
    //$.post($('#contact_form'+bUID).attr('action'), post_data, function(response){
    alert(response);
    $.ajax({
        dataType: "json",
        type: "post",
        data: "name=" + name + "&email=" + email + "&message=" + message + "&code=" + code + "&buid=" + bUID,
        //data: post_data,
        url:   $('#contact_form'+bUID).attr('action'),
        success: function(response) {
            if (typeof response !== 'undefined' && response.length > 0) {
                if (response[0] == "success") {
                    $('#success'+bUID).append('<p>Success</p>');
                }
                else {
                    $('#errors'+bUID).append('<p>' + js_errors + '</p>');
                    $('#errors'+bUID).append('<ul id="error_list"'+bUID+'></ul>');
                    $.each(response, function(i, v){
                        if (i > 0) {
                            $('#error_list'+bUID).append('<li>' + v + '</li>');
                        }
                    });
                }
            }
        }
    });
}

here's the action in view.php:

<?php
$bUID = $controller->getBlockUID($b);
$form = Loader::helper('form');
$formAction = $view->action('submit', Core::make('token')->generate('contact_form'.$bUID));
?>

<form id="contact_form<?php echo $bUID; ?>" 
    class="contact-form" 
    enctype="multipart/form-data" 
    action="<?php echo $formAction?>" 
    method="post" 
    accept-charset="utf-8">

    <?php echo $bUID; ?><br />
    <input type="hidden" name="bUID" data-buid="<?php echo $bUID; ?>" data-popup="<?php echo $popup; ?>">

   ...etc.

and here's the controller.php:

public function action_submit($token = false, $bID = false) 
{
    $this->form_errors = array();
    array_push($this->form_errors, "error");
    array_push($this->form_errors, $_POST['name']);
    array_push($this->form_errors, $_POST['email']);
    array_push($this->form_errors, $_POST['message']);
    array_push($this->form_errors, $_POST['code']);
    array_push($this->form_errors, $_POST['buid']);
    echo Core::make('helper/json')->encode($this->form_errors, JSON_UNESCAPED_UNICODE);
    exit;
}

it gets all data and shows it in alert but then trows the following error in the console:

Uncaught TypeError: Cannot use 'in' operator to search for 'length' in ["error","gggg","gggg@gmail.commm","gggggggggggggggggggggggg","gggg","171"]
    at r (jquery.js:2)
    at Function.each (jquery.js:2)
    at Object.success (view.js:132)
    at j (jquery.js:2)
    at Object.fireWith [as resolveWith] (jquery.js:2)
    at x (jquery.js:5)
    at XMLHttpRequest.b (jquery.js:5)

Line 132 of the js file is this: $.each(response, function(i, v){

I can't figure out what's wrong. The alert works and returns entered data: "error,gggg,gggg@gmail.commm,gggggggggggggggggggggg,gggg,171‌", but php retruns null objects: "["error",null,null,null,null,null]" - $_POST is empty!

What's wrong here? Why doesn't the form get posted?

Thank you very much.

Have you tried adding return false; to prevent your form from submitting to its desired action?

$('form').submit(function(e){
    bUID = $(this).find('input[name=bUID]').data("buid");
    //e.preventDefault();
    //e.stopPropagation();
    submitForm(bUID);
    alert(bUID);
    return false;
});

Try this way,

function submitForm(bUID) {
    var name = $('#name'+bUID).val();
    var email = $('#email'+bUID).val();
    var message = $('#message'+bUID).val();
    var code = $('#code'+bUID).val();

    $.post($('#contact_form'+bUID).attr('action'), {name:name, email:email, message:message, code:code, buid:bUID}, function(result){
        alert(result);
    });
}

Your post_data variable was correct. As it is now your data attribute in your ajax is wrong - it's in GET format (a string), not POST. The correct way (json) is;

$.ajax({
   dataType: "json",
   type: "post",
   data: {
       name: nameVar,
       email: emailVar,
       message: messageVar
   },
   url: ...,
   success: function(data) {
       ...
   }
});

I "renamed" your variables to try and avoid variables with the same names as keys (e.g. you want to post "name", setting a variable "name" might conflict).

Just use

    data: form.serializeArray() 

Like this:

$.ajax({
url: 'url to post data',
dataType: "json",
method: "post",
data: form.serializeArray(),
 success: function(data) {
   // another staff here, you can write console.log(data) to see what server responded
 },
 fail: function(data) {
     console.log(data) // if any error happens it will show in browsers console
  }
});

Another tips: in server side you can use http_response_code(200) for success, http_response_code(400) for errors, http_response_code(403) if authorisation is required