Reputation: 181
I want to add repeat data post to ajax,
but, I don't know where a problem,
Please help me, very thank you~!
If input class is employ click,so add active class.
and click finish_sumbit get input employ.active.val() my console.log
but repeat is trouble~!
this is my HTML
<input type="button" class="btn ahr-button_2 employ" value="bruce">
<input type="button" class="btn ahr-button_2 employ" value="peter">
<input type="button" class="btn ahr-button_2 employ" value="abcd">
<input type="button" class="btn ahr-button_2 employ" value="efgh">
<a href="#" class="finish_sumbit">完了</a>
this is my Javascript
$('.employ').click(function(){
$(this).toggleClass('active');
});
$(".finish_sumbit").click(function(){
var rows = $('.employ.active');
var employ = $('.employ.active').val();
for(var i = 0; i < rows.length; i++)
{
var data = {'employ':employ[i],'test_id':'1'};
}
console.log(data);
$.ajax({
type: "POST",
url: "business_a",
async:false,
data: {bruce:data,_token:token},
success: function (data) {
alert(JSON.stringify(data));
},
error: function (data) {
alert('error');
}
});
Upvotes: 1
Views: 258
Reputation: 388316
There are multiple issues in your code. The .val()
will return only the value of the first element in the calling set so employ
will always be a single value. Also in the loop you are always overriding the value of data
Since you can have multiple object, data
should be an array
$('.employ').click(function() {
$(this).toggleClass('active');
});
$(".finish_sumbit").click(function(e) {
e.preventDefault();
var data = $('.employ.active').map(function() {
return {
'employ': this.value,
'test_id': '1'
}
}).get();
console.log(data);
$('pre').text(JSON.stringify(data, null, 2));
});
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" class="btn ahr-button_2 employ" value="bruce">
<input type="button" class="btn ahr-button_2 employ" value="peter">
<input type="button" class="btn ahr-button_2 employ" value="abcd">
<input type="button" class="btn ahr-button_2 employ" value="efgh">
<a href="#" class="finish_sumbit">完了</a>
<br />
<pre></pre>
Upvotes: 1
Reputation: 430
In your for cycle, you are initializing new data variable every loop! Put var data; on the start of script, in for cycle will be without var
Use jQuery extend. https://api.jquery.com/jquery.extend/
Upvotes: 0