简体   繁体   中英

jQuery: loop through comment div and get fields values

I'm trying to submit users comments via ajax so I'm trying to loop through <div class="comments-fields"> to get the value of the 2 fields I need.

So far all I'm getting is this error, as if I am not filling the comments textarea which I am.

SQLSTATE[23000]: Integrity constraint violation: 1048 Column 'comment' cannot be null (SQL: insert into comments ( user_id , comment , parent_id , parents , updated_at , created_at ) values (1, , , 0, 2015-10-17 00:57:59, 2015-10-17 00:57:59))

and console.log(formData) gives something like this.

formData {}
__proto__: FormData
append: append()
constructor: FormData()
__proto__: Object

How can I achieve this? if there is a better way please suggest.

HTML

 <div class="comment-fields">
     <div class="commenter-comment">
        <div class="form-group col-md-12">
            <textarea id="commenter_comment" name="commenter_comment" class="form-control comment-field" title="User's comment" placeholder="Comment Text"></textarea>

         </div>
     </div>

     <div class="commenter-name-email">
         <input type="hidden" id="commenter_parent" name="commenter_parent" class="commenter-parent" value="0">
      </div>

      <div class="commenter-captcha">
          <div class="col-md-3 text-right">
              <a href="javascript:void(0)" class="btn btn-info post-this-comment">Comment</a>
           </div>
       </div>

 </div>

The Javascript

function commenter_fields(){
    return [
        'commenter_parent',
        'commenter_user_id',
        'commenter_comment'
    ];
}

$(document).on('click', 'a.post-this-comment', function(){
    var formData = new FormData();
    var arrayelem = commenter_fields();
    var elem;
    for(var i=0, size = arrayelem.length; i<size; i++){
        elem = arrayelem[i];
        formData.append(elem, $('#'+elem).val());
    }
    formData.append('per_page', $('.comments_per_page').val());
    var request = $.ajax({ // push question data to server
        type        : 'POST', // define the type of HTTP verb we want to use (POST for our form)
        url         : 'post_this_comment', // the url where we want to POST
        data        : formData, // our data object
        dataType    : 'json',
        processData : false,
        contentType : false
    });
    request.done(comment_done_handler);
    request.fail(comment_fail_handler); // fail promise callback
});

I am using PhpStrom, clicking on FormData() leads to this file

C:\\Program Files (x86)\\JetBrains\\PhpStorm 9.0\\plugins\\JavaScriptLanguage\\lib\\JavaScriptLanguage.jar!\\com\\intellij\\lang\\javascript\\index\\predefined\\HTML5.js

And this is FormData

FormData.prototype.append = function(name,value) {};
FormData = {};

I would suggest using regular objects because they are much easier to work with over formData (in my opinion).

The jQuery documents state Type: PlainObject or String or Array for the data setting in an ajax post which makes me think they like objects too.

So, instead, your click handler could go:

var form_data = {
    'per_page': $('.comments_per_page').val()
};

var arr = [
    'commenter_parent',
    'commenter_user_id',
    'commenter_comment'
];

for (var i in arr; i < arr.length; i++) {
    var elem = arr[i];
    form_data[elem] = $('#' + elem).val();
}

// console.log(form_data); // something like => Object {per_page: "some_value", commenter_parent: "some_value", commenter_user_id: "some_value", commenter_comment: "some_value"}

var request = $.ajax({
    type: 'POST',
    url: 'your_url_here',
    data: form_data,
    dataType: 'json'
});

request.done(comment_done_handler);
request.fail(comment_fail_handler);

A simpler approach would be to use data attributes on the elements and just build a data string from your values like this:

 $(document).on('click', 'a.post-this-comment', function () { var dataArray=[]; // array to temporarilly store our data $('#comment-fields').find('.commenter-field').each(function(i,e){ //loop through all of the fields we need values from, I gave them all the class `commenter-field` var $element =$(e); // cache the element var type=$element.data('comment-field-type'); // get the name of the data, stored as a data attribute var value=encodeURIComponent($element.val()); // get the value, you MUST encode the value, otherwise, you WILL run into issues at some point with illegal chars dataArray.push(type+'='+value); // combine the type and value separated by `=` }); var dataString=dataArray.join('&'); // join the array with `&` between each name/value pair var request = $.ajax({ // push question data to server type: 'POST', // define the type of HTTP verb we want to use (POST for our form) url: 'post_this_comment.php', // the url where we want to POST, missing file extension here? data: dataString, // our data string dataType: 'json', // only if your code expects a json response from `post_this_comment.php` }); request.done(comment_done_handler); request.fail(comment_fail_handler); // fail promise callback }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="comment-fields"> <div class="commenter-comment"> <div class="form-group col-md-12"> <textarea data-comment-field-type="commenter_comment" class="form-control commenter-field" title="User's comment" placeholder="Comment Text">Some comment...</textarea> </div> </div> <div class="commenter-name-email"> <input type="hidden" data-comment-field-type="commenter_parent" class="commenter-field" value="some parrent"> <input type="hidden" data-comment-field-type="commenter_user_id" class="commenter-field" value="some UserId"> <input type="hidden" data-comment-field-type="per_page" class="commenter-field" value="some number of comments"> </div> <div class="commenter-captcha"> <div class="col-md-3 text-right"> <a href="javascript:void(0)" class="btn btn-info post-this-comment">Comment</a> </div> </div> </div> 

Inspecting the request headers in dev tools shows the below data being sent:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM