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

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.

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');
}
})
}
}
});
});

Collecting multiple data and send by ajax in laravel

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>

adding jquery html constructor to another

I am trying to build dynamically accordion from ajax(JSON) data.
I need to generate the following html tags, but i can't find convenient way.
<h3></h3>
<div>
<p> </p>
</div>
The accordion works with the < li > tag I've used to append to, but it's dirty solution and I don't like it. There should be a way to do it in more beautiful way.
Please help to a noob, thank you!
$.ajax({
url: '/getCar',
type: 'GET',
success: function(res) {
var delCarPost = $('<form>').attr('method', 'post').append($('<input>').attr({
type: "hidden",
name: "carid",
id: "carid"
}),
$('<input>').attr({
type: "submit",
value: "delete"})
);
// var div = $('<h4>').before($('<div>').append($('<p>')));
var div = $('<div>').append($('<p>'))
div = $("<li>").append($('<h4>'),$(div))
// var div = $("<li>").append($('<h4>'),$('<div>').append($('<p>')));
var carObj = JSON.parse(res);
var car = '';
$.each(carObj,function(index, value){
car = $(div).clone();
$(car).find('h4').text(value.make + " from " + value.year + " at price " + value.price);
$(car).find('p').text(value.info);
$('#accordion').append(car);
$("#accordion").accordion("refresh");
console.log(div);
});
$('#accordion').on( 'click', 'button', function () {
post('/delCar', {postMake: value.make}, "post");
});
},
error: function(error) {
console.log(error);
}
});
Here is an answer that may help you. I left some comments inside:
$.ajax({
url: '/getCar',
type: 'GET',
"dataType": "json", //no need to JSON.parse
success: function(cars) {
//you should specify where you append those nodes ...
var delCarPost = $('<form>').attr('method', 'post').append(
$('<input>').attr({
type: "hidden",
name: "carid",
id: "carid"
}),
$('<input>').attr({
type: "submit",
value: "delete"
})
);
//bellow a simplified version
var html = '';
$.each(cars,function(index, car){
html += [
'<li>',
'<h3>' + car.make + ' from ' + car.year + ' at price ' + car.price + '</h3>',
'<div>',
'<p>' + car.info + '</p>',
'</div>',
'<li>'
].join('');
});
//cache your access to jQuery
var accordion = $('#accordion');
accordion.html(html);//innerHTML everything above in one time (only one DOM access)
accordion.accordion("refresh");
accordion.on( 'click', 'button', function () {
post('/delCar', {postMake: value.make}, "post");
});
},
error: function(error) {
console.log(error);
}
});
I've found better solution using Mustache.js templates.
Since I use Jinja templates + Mustache the template looks like this:
{% raw %}
<script id="CarAccTemplate" type="x-tmpl-mustache">
<h3 id='{{ id }}'> {{ make }} from {{ year }} at price {{ price }}
<div class="pull-right action-buttons">
<a id='delcar-{{ id }}' onclick="ConfirmDelete(this)">
<span class="glyphicon glyphicon-trash"></span>
</a>
</div>
</h3>
<div>
<p>{{info}}</p>
</div>
</script>
{% endraw %}
and in js
$.ajax({
url: '/getCar',
type: 'GET',
"dataType": "json", //no need to JSON.parse
success: function(cars) {
//bellow a simplified version
var html = '';
$.each(cars,function(index, car){
var template = $('#CarAccTemplate').html();
Mustache.parse(template)
var rendered = Mustache.render(template, car);
html += rendered;
});
//cache your access to jQuery
var accordion = $('#accordion');
accordion.html(html);//innerHTML everything above in one time (only one DOM access)
$( "#accordion" ).accordion({heightStyle: "content"});
accordion.accordion("refresh");
//feed the form on click event
$('#accordion h3').on("click select focus", function(e){
//parse the text
carid = $(this).attr('id');
text = $(this).text();
make = text.split("from",1)[0].trim();
year = text.match(/from (.*)/)[1].match(/^\d+/)[0].trim();
price = text.match(/price (.*)/)[1].trim();
info = $('div[aria-labelledby=' + carid + "]").children('p').text();
// console.log($('form[id="addCar"] fieldset div'));
// feed form with values from accordion
$('.form-group #inputYear:text').val(year);
$('.form-group #inputMake:text').val(make);
$('.form-group #inputPrice:text').val(price);
$('.form-group #inputInfo').val(info);
$('.form-group #carId').val(carid);
});
// accordion.on( 'click', 'button', function () {
// post('/delCar', {postMake: value.make}, "post");
// });
},
error: function(error) {
console.log(error);
}
});

Adding table rows based on JSON

I'm new with JSON. I have a select box and JavaScript change() trigger on it. I execute MySQL query with Ajax based on selected value. Query results will be printed as a new row in HTML table.
But the new row isn't appending. What am I doing wrong?
HTML
<select id="orderAddProduct">
<option value=""></option>
<option value="0001">Product 1</option>
<option value="0002">Product 2</option>
</select>
<table id="orderTable">
<tr><th>ID</th><th>Name</th></tr>
</table>
JavaScript
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "POST",
url: "orderAddProduct.php",
data: {option: selectedValue},
datatype: "json",
success: function (data) {
alert("OK");
orderAddRow(data);
},
error: function () {
alert("ERROR");
}
});
});
function orderAddRow($item) {
$.each($item,function(index,value) {
var row = '<tr><td>'+value.id+'</td>'
+'<td>'+value.name+'</td></tr>';
$('#orderTable').append(row);
)};
}
PHP
try {
$pdo = new PDO(DB_TYPE . ':host=' . DB_HOST . '; dbname=' . DB_NAME, DB_USER, DB_PASS);
} catch (PDOException $e) {
die("ERROR: " . $e->getMessage());
}
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->exec("SET NAMES utf8");
$productId = $_REQUEST['option'];
$sql = $pdo->prepare("SELECT * FROM products_view WHERE id = ?");
$sql->execute(array($productId));
$row = $sql->fetch(PDO::FETCH_ASSOC);
$json_array = array("ID" => $row['id'], "name" => $row['name']);
echo json_encode($json_array);
Variable names?
function orderAddRow($item) {
^^^^^^----
var row = '<tr><td>'+value.id+'</td>'
^^^^^----
You define a $item parameter, but never use it in the function. Instead there's this mysterious/undefined value.
Ok, the master problem is that I didn't have JSON.parse() function in my code. Below is my finally working code.
$("#orderAddProduct").change(function () {
var element = $(this);
var selectedValue = $(this).val();
$.ajax({
type: "GET",
url: "orderAddProduct.php",
data: {option : selectedValue},
datatype: "json",
success: function (response) {
response = JSON.parse(response);
if(response === undefined) {
alert("undefined");
} else {
orderAddRow(response);
}
},
error: function () {
alert("ERROR");
}
});
return false;
});
function orderAddRow($data) {
$.each($data,function(index,value) {
var row = '<tr><td>' + value.ID + '</td>'
+ '<td>' + value.name + '</td></tr>';
$('#orderTable').append(row);
});
}
success: function (data) {
alert("OK");
orderAddRow(data);
},
You are missing out the returned value.

database connectivity not working in ajax call- laravel

My javascript is:
$( "#exerciseFetch" ).change(function( event ) { //alert("super");
// var _token = $( this ).find( 'input[name=_token]' ).val()
var mytoken = $('#mytoken').attr('value');
ajaxContent = [
{"_token": mytoken},
{"val" : $( "#exerciseFetch" ).val()}
]
$.ajax({
type: "POST",
url: 'exerciseFetchAjaxCall',
data: { ajaxContent }
// data: { "_token": mytoken }
}).done(function( msg ) {
alert( msg );
var reqContent = msg;
$("#dynamic").html(reqContent);
});
});
my route:
Route::group(array('prefix' => 'admin', 'namespace' => 'App\Controllers\Admin'), function()
{
Route::post('exerciseFetchAjaxCall', 'ExerciseController#exerciseAjaxCall');
});
my controller code:
public function exerciseAjaxCall(){
$row = $_POST['ajaxContent'];
// $row[1]['val']
$muscles = Muscular::whereIn('Status',array(1))->orderBy('id', 'desc')->paginate(10);
// return $this->content = View::make('admin.exercise.displayMusclarGroupAjax',array('row' => $row ));
return $this->content = View::make('admin.exercise.displayMusclarGroupAjax',array('muscles' => $muscles ));
}
my view code:
#if($muscles && count($muscles) > 0)
#foreach($muscles as $muscular)
<?php
$icons = ["fa-icon-user", "fa-icon-user", "fa-icon-user inactive"];
$typeArray = [
'1'=> 'Resistance',
'2'=> 'Cardio'
];
$typeArray[3] = 'Resistance & Cardio';
?>
<tr>
<td data-title="muscular_name">{{ ucfirst($muscular->muscular_name) }}</td>
<td data-title="muscular_type">{{ $typeArray[$muscular->type]}}</td>
</tr>
<?php
$i++;
?>
#endforeach
#endif
#if(isset($row) && count($row) > 0)
<?print_r($row);?>
#endif
If I comment out the row contents and comment the muscles content in controller the code returns the values passed but the contents of the muscles are not displayed if uncommented.
I have displayed the muscle contents with the same code in its listing page (but without ajax call) dont know why its not working as I am new to laravel.
Any suggestions would be helpful...
You have syntax error in ajax script, Try this simple $.post() api to make ajax call
$( "#exerciseFetch" ).change(function( event ) { //alert("super");
// var _token = $( this ).find( 'input[name=_token]' ).val()
var mytoken = $('#mytoken').attr('value'),
ajaxContent = {
"_token" : mytoken,
"val" : $( "#exerciseFetch" ).val()
};
//make ajax call
$.post( "exerciseFetchAjaxCall", ajaxContent ).done(
function( msg ) {
alert( msg );
var reqContent = msg;
$("#dynamic").html(reqContent);
}
);
});
Above should do, If nothing is returning from DB please try dd() in controller to see the returned result
//are you sure `Status` is not in small case
$muscles = Muscular::whereIn('Status',array(1))->orderBy('id', 'desc')->paginate(10);
dd($muscles);

Categories

Resources