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);
Related
i want to assign javascript variable value to php variable to loop products
here is my php code:
$products = wc_get_products( array(
'include' => $products_ids // `**i want to pass value from javascript here**`
) );
foreach ( $products as $product ) {
// fetching my product details
}
here is my js code:
(function($){
$(document).ready(function(){
$(document).on('change', '#myform', function(e) {
e.preventDefault();
data = $(this).serialize();
var settings = {
"url": "<?php echo WC_AJAX::get_endpoint( 'myajaxfunction' ) ?>",
"method": "POST",
"data": data,
}
$.ajax(settings).done(function (result) {
// i want to make $products_ids = result
// result value is array(1,2);
});
});
});
})(jQuery);
**
i want to make $products_ids = result so i can pass it in my php
code,
result value is array(1,2);
**
I need to send array to my mysql database.
I've created a JSON array and dont know how to post it to php to transfer to db.
$( function () {
$( '#orderForm' ).on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
} );
} );
I need to post it item->item, qty->qty, price->price to the db.
I've tried :
$.ajax( {
url: 'tc_menu',
type: 'POST',
data: JSON.stringify( myData ),
success: function ( data ) {
console.log( "success:", data );
},
failure: function ( errMsg ) {
console.error( "error:", errMsg );
}
} );
Data stores whole page, but not (stringified myData). And I still cant get it at php code by $_POST and json_decode
Data stores whole page, but not stringified myData and I can't get it at php code by $_POST and json_decode
php code
`if(isset($_POST['submitted_m'])){
$myData = serialize($_POST['data']);
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
if (mysqli_query($db, $sqli)) {
$msg = "New Order added!";
echo "<script>
alert(\"$msg\");
window.location.replace('tc_menu.php');
</script>";}
else {echo "Error:".$sql."<br>".mysqli_error($db);}}`
Try this one for js
$(function () {
$('#orderForm').on( 'submit', function ( event ) {
event.preventDefault();
var myData = [],
keys = ['item', 'qty', 'price'],
url = this.action;
$( '#orderTable' ).find( 'tr:gt(0)' ).each( function ( i, row ){
var oRow = {};
$( row ).find( 'td' ).each( function ( j, cell ) {
oRow[keys[j]] = $( cell ).text();
} );
myData.push( oRow );
} );
console.log( myData );
console.log( JSON.stringify( myData ) );
data_to_server = JSON.stringify(myData);
});
$.post("*your_php_file*", {
data: data_to_server;
}).done(function (data_returned) {
// any your code
});
});
And seems you have mismatch in PHP code - trying to serialize() instead of json_decode()
Remove nested click event and closure.
e.g.
$( '#orderForm' ).on( 'submit', function ( event ) {
$( '#orderForm' ).on( 'submit', function ( event ) {
} );
} );
Than try again.
And your MySQL insert statement in php
$sqli = "INSERT INTO tc_cafe_orders SET item='".$myData."' ";
is not ok.
Learn more about MySQL insert statement here https://www.w3schools.com/php/php_mysql_insert.asp
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.
i'm making an app to track different craft beers i've tasted. part of that is making an AJAX call to set a cookie in the uder's browser -- i'm json_encoding the list.beerList array and trying to store it in a cookie. for some reason, the cookie is getting set, but Firebug isn't registering an AJAX call being made. and even when i send something back, the success condition of the jquery AJAX function isn't firing. code below:
angular.module( 'beerList', [] ).controller( 'beerListController', function($scope) {
var list = this;
list.beerList = [];
angular.element(document).ready( function() {
list.getCookie();
})
list.addBeer = function() {
var beerEntered = $( '#beer' ).val();
var breweryEntered = $( '#brewery' ).val();
var abvEntered = $( '#abv' ).val();
var notesEntered = $( '#notes' ).val();
list.beerList.push( { beer: beerEntered, brewery: breweryEntered, abv: abvEntered, notes: notesEntered } );
list.setCookie();
}
list.setCookie = function() {
var string = JSON.stringify(list.beerList);
$.ajax({
url: 'ABSOLUTE/PATH/TO/setCookie.php',
dataType: 'jsonp',
data: {
string: string
},
success: function(data) {
alert('success!');
}
})
}
list.getCookie = function() {}
})
thanks so much for your help!
i am using zf2. i want to load my second drop down by using the ajax call. i have tried with following code. i can get hard coded values. but i dont know how to add database values to a array and load that values to the drop down using ajax.
Ajax in phtml :
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
//code to load data to the dropdown
},
error:function(){alert("Failure!!");}
});
});
});
</script>
Controller Action:
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$projectusers[] = $this->getRoleTable()->fetchRoles($projectid);
// eturn a Json object containing the data
$result = new JsonModel ( array (
'projectusers' => $projectusers
) );
return $result;
}
DB query :
public function fetchRoles($id) {
$resultSet = $this->tableGateway->select ( array (
'projectid' => $id
) );
return $resultSet;
}
your json object new JsonModel ( array (
'projectusers' => $projectusers
) json object become like this format Click here for Demo
var projectkey = [];
projectkey = projectname.split(" - ");
var projectname = { "textData" : "+projectkey[1]+" };
$.ajax({
type:"POST",
url : "url.action",
data : projectname,
success : function(data){
$.each(data.projectusers,function(key,value){
$('#divid').append("<option value="+key+">"+value+"</option>");
});
});
});
<select id="divid"></select>
This is what i did in my controller. finaly done with the coding.
public function answerAction() {
// ead the data sent from the site
$key = $_POST ['textData'];
// o something with the data
$data= $this->getProjectTable ()->getkeyproject( $key );
$projectid = $data->id;
$i=0;
$text[0] = $data->id. "successfully processed";
$projectusers = $this->getRoleTable()->fetchRoles($projectid);
foreach ($projectusers as $projectusers) :
$users[$i][0] = $projectusers->username;
$users[$i][1] = $projectusers->id;
$i++;
// eturn a Json object containing the data
endforeach;
$result = new JsonModel ( array (
'users' => $users,'count'=>$i
) );
return $result;
}
and the ajax is like this
<script type="text/javascript">
$(document).ready(function () {
$("#projectname").change(function (event) {
var projectname = $(this).val();
var projectkey = projectname.split(" - ");
var projectname = {textData:projectkey[1]};
//The post using ajax
$.ajax({
type:"POST",
// URL : / name of the controller for the site / name of the action to be
// executed
url:'<?php echo $this->url('userstory', array('action'=>'answer')); ?>',
data:projectname,
success: function(data){
// alert(data.users[0][0]+" - " + data.users[0][1] );
var count= data.count;
alert(count);
$('#myDropDown').empty();
for(var i=0;i<count;i++){
$('#myDropDown').append($('<option></option>').attr('value', data.users[i][1]).text(data.users[i][0]));
}
},
error:function(){alert("Failure!!");}
});
});
});
</script>
used the same zf2 query to access the database. thanks for the help everyone :)