Collecting multiple data and send by ajax in laravel - javascript

I'm using ajax to send my data to controller and save it in database, before my code was working then I needed to sort my data when they append in blade after sorting them it stop working by %50.
Good to know
Here is my old code and solution of sorting my data (which caused
this issue that i have now)
Logic
I select set
Set childs will append in blade (sorted by custom column)
I choose single or multiple options and hit save button
Data saves to database
More to know
My appended data (based on selected set) are include 2 types of data
Custom inputs (text field & text-area field) which i can manually fill and save (still working with no issue)
Dynamic select option which returns from database and i can select and save their id's (this is the issue dynamics)
Code
Script of appending data
<script defer>
$(document).ready(function() {
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
$('div#dataaamsg').empty();
$('div#dataaamsg').append('Use <kbd>CTRL</kbd> or <kbd>SHIFT</kbd> button to select multiple options');
result.sort(function(a,b) {
return (a.position > b.position) ? 1 : ((b.position > a.position) ? -1 : 0);
});
$.each(result, function(key1, value1) {
var vvvid = value1.id;
if(value1['type'] == 'textfield'){
var my_row = $('<div class="row mt-20 ccin">');
$('div#dataaa').append(my_row);
}else if(value1['type'] == 'textareafield'){
var my_row = $('<div class="row mt-20 ccin">');
$('div#dataaa').append(my_row);
}else{
var my_row = $('<div class="row mt-20">');
$('div#dataaa').append(my_row);
}
// second data
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
// Check result isnt empty
var helpers = '';
$.each(data, function(key, value) {
helpers += '<option value="'+value.id+'">'+value.title+'</option>';
});
if(value1['type'] == 'textfield'){
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><input id="text_dec" name="text_dec[]" placeholder="text field" class="text_dec form-control"></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}else if(value1['type'] == 'textareafield'){
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_id" id="specification_id" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><textarea id="longtext_dec" name="longtext_dec[]" placeholder="text area field" class="longtext_dec form-control"></textarea></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsavee" class="custmodalsavee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}else{
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><select class="subspecifications form-control tagsselector" id="subspecifications" name="subspecifications[]" multiple="multiple">'+helpers+'</select></div>';
my_html += '<div class="col-md-2"><button type="button" id="savedynspecto" class="savedynspecto btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}
}
});
// second data
});
}
});
}else{
$('div#dataaa').empty();
}
});
});
</script>
script of saving data (issue part)
<script defer>
$(document).ready(function() {
$("body").on("click", ".savedynspecto", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': $(this).closest('form').find('select.subspecifications').val()
},
success: function (data) {
alert('Specifications added successfully.');
console.log($(this));
},
error: function (data) {
console.log(data);
}
});
});
});
</script>
Issue
When I try to save my dynamic values i cannot get id of selected option/options
//returned data in network params
_token g1GnKZvzXDztR1lqgDdjI5QOg67SfmmBhjm80fKu
product_id 18
subspecifications
Ps1
I've tried to change val() to serialize() and I got
_token g1GnKZvzXDztR1lqgDdjI5QOg67SfmmBhjm80fKu
product_id 18
subspecifications subspecifications%5B%5D=20&subspecifications%5B%5D=21&subspecifications%5B%5D=23&subspecifications%5B%5D=32"
All I needed was 21,23,32 instead i got subspecifications%5B%5D= before each of them.
Ps2
I've tried to change $("body").on("click", ".savedynspecto", function(e){ that would not send any data to back-end (nothing prints in network not even error codes)
Any idea?

Hi change this line in your code
'subspecifications':
$(this).closest('form').find('select.subspecifications').val()
to
'subspecifications':
$(this).closest('form').find('select.subspecifications
option:selected').map(function(){ return this.value }).get()
It should help

After the button... in the string to append, you have {{Form::close()}}</div>.
I think the </div> should come before the {{Form::close()}}.
A messed-up HTML structure can lead to strangenesses quickly.
I'm not 100% sure that is the issue... But it could.

You have MANY select with class subspecifications... So you have to loop through them to get their values.
<script defer>
$(document).ready(function() {
$("body").on("click", ".savedynspecto", function(e){
var form = $(this).closest('form');
var id = form.find('input[name="product_id"]').val();
// An array to store the subspecifications values.
var spec_array = [];
// A loop to go through all them.
form.find('select.subspecifications').each(function(){
spec_array.push($(this).val());
});
// e.preventDefault();
$.ajax({
type: "post",
url: '{{ url('admin/spacssendto') }}',
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'subspecifications': spec_array // The array containing each SELECT values
},
success: function (data) {
alert('Specifications added successfully.');
console.log($(this));
},
error: function (data) {
console.log(data);
}
});
});
});
</script>

Related

How to append the response result on the specific class using laravel and Ajax

I have problem regarding on real time count of likes using ajax and laravel, so once the response success the result of response will append to the specific class, however it happen when i click the like button. each class added the result. to understand more well. please see the attached images below.
w
Problem: How to append the result on the specific like button.
illustration:
Html Loop Data:
echo '<a class="nav-link btn_like_each_content" data-attri-like-content="'.$latest_news_data->content_id.'" style="color:#757a91; font-size:13px;"><i class="far fa-thumbs-up" style="color:#757a91; font-size:13px;" ></i> <label class="total_count_of_like_each_content" >0</label> Likes</a>';
Front End:
$('a.btn_like_each_content').on('click',function(){
var content_id = $(this).attr("data-attri-like-content");
var data = content_id;
$.ajax({
url: "/total_count_like_each_comment",
type:'post',
data:{like_id:data},
success: function( response ) {
if(response == 'Clicked') {
$.ajax({
url:"/retrive_like_count_each_content",
type:'get',
data:{content_id: data},
dataType:'JSON',
success:function(res) {
var total_count_of_specific_content = res[0]['count_like'];
var parseTotalLike = parseInt(total_count_of_specific_content);
$('.total_count_of_like_each_content').text( parseTotalLike );
},
error:function(err) {
alert('Failed To Insert');
}
})
}
}
});
});
Thank you..
Give a unique id to each class
echo '<a class="nav-link btn_like_each_content" id="content_'.$latest_news_data->content_id.'" data-attri-like-content="'.$latest_news_data->content_id.'" style="color:#757a91; font-size:13px;"><i class="far fa-thumbs-up" style="color:#757a91; font-size:13px;" ></i> <label class="total_count_of_like_each_content" >0</label> Likes</a>';
Now Track which content was clicked by defining a variable
$('a.btn_like_each_content').on('click',function(){
var content_id = $(this).attr("data-attri-like-content");
var actual_content_id = $(this).attr("id");
var data = content_id;
$.ajax({
url: "/total_count_like_each_comment",
type:'post',
data:{like_id:data},
success: function( response ) {
if(response == 'Clicked') {
$.ajax({
url:"/retrive_like_count_each_content",
type:'get',
data:{content_id: data},
dataType:'JSON',
success:function(res) {
var total_count_of_specific_content = res[0]['count_like'];
var parseTotalLike = parseInt(total_count_of_specific_content);
$('#' + actual_content_id).text( parseTotalLike ); //Pass actual content ID here
},
error:function(err) {
alert('Failed To Insert');
}
})
}
}
});
});

How to send array of data to controller with ajax in laravel

I want send arrays of data to back-end at once but i can't.
issue
1.
this is what i send currently
array:5 [
"_token" => "S5s5ZTTnnP93MyXgCql0l9vhHsiqt5VWaFyEedXj"
"product_id" => "21"
"specification_id" => "6"
"text_dec" => "1"
"longtext_dec" => null
]
It should be like:
Array [
0 = [
data
]
1 = [
data
]
2 = [
data
]
]
I always get same ID as specification_id while each row in my blade has different ID
Code
appending script
<script defer>
$(document).ready(function() {
//select the category
$('select[name="selectset"]').on('change', function() {
var id = $(this).val();
if(id) {
$.ajax({
url: '{{ url('admin/selectset') }}/'+encodeURI(id),
type: "GET",
dataType: "json",
success:function(result) {
//sort the results
result.sort(function(a,b) {
return (a.position > b.position) ? 1 : ((b.position > a.position) ? -1 : 0);
});
$.each(result, function(key1, value1) {
var vvvid = value1.id;
//textfield and textareafield are part of my issue (appended rows)
if(value1['type'] == 'textfield'){
var my_row = $('<div class="row mt-20 ccin">');
$('div#dataaa').append(my_row);
}else{
var my_row = $('<div class="row mt-20 ccin">');
$('div#dataaa').append(my_row);
}
// second data (get values)
$.ajax({
url: '{{ url('admin/findsubspecification') }}/'+value1['id'],
type: "GET",
dataType: "json",
success:function(data) {
// Check result isnt empty
var helpers = '';
$.each(data, function(key, value) {
helpers += '<option value="'+value.id+'">'+value.title+'</option>';
});
//this is the part of my issue
if(value1['type'] == 'textfield'){
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><input id="text_decc" name="text_decc" placeholder="text field" class="text_decc form-control"></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}else{ //second part of my issue
var my_html = '{{ Form::open() }}<input name="product_id" id="product_id" type="hidden" value="{{$product->id}}"><input name="specification_idd" class="specification_idd" id="specification_idd" type="hidden" value="'+vvvid+'"><div class="col-md-4">'+value1.title+'</div>';
my_html += '<div class="col-md-6"><textarea id="longtext_decc" name="longtext_decc" placeholder="text area field" class="longtext_decc form-control"></textarea></div>';
my_html += '<div class="col-md-2"><button type="button" id="custmodalsaveee" class="custmodalsaveee btn btn-xs btn-success">Save</button>{{Form::close()}}</div>';
my_row.html(my_html);
}
}
});
// second data
});
}
});
}
});
});
</script>
result of code above is like:
saving script the part that should be fixed
<script>
$(document).ready(function() {
$("body").on("click", ".custmodalsaveee", function(e){
var id = $('input[name="product_id"]').val();
$.ajax({
type: "post",
url: "{{ url('admin/addnewcustomsubspecifications') }}",
data: {
'_token': $('input[name=_token]').val(),
'product_id': id,
'specification_id': $('.specification_idd').val(),
'text_dec': $('.text_decc').val(),
'longtext_dec': $('.longtext_decc').val(),
},
success: function (data) {
alert('Specification added successfully in your product!');
},
error: function (data) {
console.log('Error!', data);
}
});
});
});
</script>
controller
public function addnewcustomsubspecifications(Request $reqss){
dd($reqss->all());
// $this->validate($reqss, array(
// 'product_id' => 'required',
// 'specification_id' => 'required',
// 'text_dec' => 'nullable',
// 'longtext_dec' => 'nullable',
// ));
// $add = CustomProductSpecification::create([
// 'product_id' => $reqss->product_id,
// 'specification_id' => $reqss->specification_id,
// 'text_dec' => $reqss->text_dec,
// 'longtext_dec' => $reqss->longtext_dec,
// ]);
// $parent = Specification::where('id', '=', $reqss->specification_id)->first();
// return response()->json(array('data'=>$add,'parent'=>$parent));
}
Any idea?
Update
html output
Update2
So based on suggestions i've used .map() here is my code and the results
script
$(document).ready(function() {
$("body").on("click", ".custmodalsaveee", function(e){
var id = $('input[name="product_id"]').val();
var specification_idd = $( ".ccin" ).map(function() {
return $( this ).find('.specification_idd').val();
return $( this ).find('.text_decc').val();
return $( this ).find('.longtext_decc').val();
}).get();
var text_decc = $( ".ccin" ).map(function() {
return $( this ).find('.text_decc').val();
}).get();
var longtext_decc = $( ".ccin" ).map(function() {
return $( this ).find('.longtext_decc').val();
}).get();
console.log(specification_idd);
console.log(text_decc);
console.log(longtext_decc);
$.ajax({
//rest of it as it was...
and the console results
Question
How do i get related results together? specification_id and text fields as 1 array
how I avoid of empty values? if text_dec and longtext_dec are empty for each specification_id doesn't need to be send example specification 40 doesn't have any value in longtext_dec or text_dec no need to be send
Robert, you should directly return view from your Ajax call in your laravel method and just bind html response from the view with your new data.
That is pretty easy way of doing it.

ajax get wrong value

I used ajax for my current project with laravel and i try to pass value of textbox using ajax but it pass R every time, even if i pass the wrong variable with ajax. my code is as below
<div class="form-group">
<label for="">Total Amount</label>
<input type="text" class="form-control" id="total_amount" value="123" name="total">
</div>
javascript code
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: {
lists: list, total: total, "_token": "{{ csrf_token() }}"
},
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});
laravel method
public function getTotal(Request $request)
{
$list = #$request['lists'];
$total = #request['total'];
return $total;
}
varibale list work fine but total always return value R, when it print first time log that time it print correct value in console, but second time in success function of ajax it print always R. where i made mistake??
Change this:
$total = #request['total'];
to this:
$total = #$request['total'];
^
Try like below:
$("#id_label_multiple").on('change', function () {
var list = $("#id_label_multiple").val();
var total = $("#total_amount").val();
console.log()
$.ajax({
url: "{{ action('hkcontroller#getTotal') }}",
data: "lists="+list+"&total="+total+"&_token={{ csrf_token()}}",
type: "POST",
success: function (data) {
$('#msg').html('Received ' + data + ' stones form exporter successfully!')
console.log(data);
}
});
});

How to use ajax in PHP foreach?

I have a form with two select html tags and an input submit. To populate the value of option tags and to display the equivalent values of selected option tag, I use PHP, please see snippet below.
Now, I want to use AJAX using JS to avoid the reloading of the browser when the user clicked the button. But I don't know how. Please help me
Here's the link
Snippet:
if(isset($_POST['mall_list'])){
$mall_list= $_POST['mall_list'];
$malls= $wpdb->get_results($wpdb->prepare("SELECT stores FROM tablename WHERE malls = '" . $mall_list. "' GROUP BY stores ORDER BY stores", OBJECT));
echo '<div class="\record\">';
foreach ($malls as $record){
echo '<div>' . $record->stores . '</div>';
}
echo '</div>';
} elseif(isset($_POST['store_list'])){
$store_list= $_POST['store_list'];
$stores= $wpdb->get_results($wpdb->prepare("SELECT malls FROM tablename WHERE stores= '" . $store_list. "' GROUP BY malls ORDER BY malls", OBJECT));
echo '<div class="\record\">';
foreach ($stores as $record){
echo '<div>' . $record->malls. '</div>';
}
echo '</div>';
}
HTML
<form name="ajaxform" id="ajaxform" action="ajax-form-submit.php" method="POST">
First Name: <input type="text" name="fname" value =""/> <br/>
Last Name: <input type="text" name="lname" value ="" /> <br/>
Email : <input type="text" name="email" value=""/> <br/>
</form>
JAVASCRIPT
//callback handler for form submit
$("#ajaxform").submit(function(e)
{
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url : formURL,
type: "POST",
data : postData,
success:function(data, textStatus, jqXHR)
{
//data: return data from server
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
}
});
e.preventDefault(); //STOP default action
e.unbind(); //unbind. to stop multiple form submit.
});
$("#ajaxform").submit(); //Submit the FORM
if you want to post data through ajax jquery. this code work for you.
$( "form" ).submit(function( event ) {
event.preventDefault();
$.ajax({
type: "POST",
url: "your post url",
data: $('#yourformname').serialize(),
success: function (data)
{
}
});
});
javascript
$("#form").submit(function(e){
var data = $(this).serialize();
var url = $(this).attr("action");
$.post({
url,
data,
function(res)
{
if(res.code == 0)
{
//success
//code somthing when the server response
alert(res.message);
}
}
});
})
server
if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest')
{
#is ajax request
# code your business logic
#response data
$response = [
'code' => 0,
'message' => 'success',
'data' => []
];
echo json_encode($response);exit;
} else {
#is normal request
}

Why doesn't jquery submit work properly?

This code works fine in its current state where im using a click event on a button. But if i use a form tag around the input tags in my html code and use jquery's submit method it doesnt give any results. why is that happening? i have to use the form element because i want to be able to search with an enter key insted of clicking on a button
Html:
<body>
Title: <input type="text" id="title"><br/>
<input type="submit" value="Submit" id="btn">
<p id="results"></p>
<body>
jQuery:
$(document).ready(function(){
$("#btn").on("click", function(){
var textval = $('#title').val();
var playListURL = 'https://en.wikipedia.org/w/api.php?action=query&list=search&srsearch=' + textval + '&format=json&callback=?';
$.ajax({
type: "GET",
url: playListURL,
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
for (var i = 0; i < 10; i++)
{
var url = "https://en.wikipedia.org/wiki/" + data.query.search[i].title;
$("#results").append("<b> <a href='" + url + "' > " + data.query.search[i].title + "</a></b></br> ");
//console.log(url);
}
},
error: function (errorMessage) {
}
});
//alert($('#title').val());
});
});
Try to change this line
$("#btn").on("click", function(){
to this:
$("#btn").on("click", function(e){
e.preventDefault();
Then the form will not submit default way on click

Categories

Resources