How I can post a JavaScript array , and to write him to the session I opened in the Controller
This is my view where I save the id`s in an array
<script type="text/javascript">
$(document).ready(function () {
var data = [];
s = 0;
$('.custombtn').click(function () {
var id = $(this).attr("value");
data.push(id);
console.log(data);
});
});
And This is my Controller where I open a session , but cant figure out how I can post the array to be stored in the session
public function actionShop() {
if (!Yii::$app->session->isActive) {
Yii::$app->session->open();
$query = Stock::find();
$pagination = new Pagination([
'defaultPageSize' => 6,
'totalCount' => $query->count(),
]);
$stock = $query->orderBy('id')
->offset($pagination->offset)
->limit($pagination->limit)
->all();
}
return $this->render('shop', [
'stock' => $stock,
'pagination' => $pagination,
]);
}
worked with inserting Ajax
$(document).ready(function () {
var data = [];
$('.custombtn').click(function () {
var id = $(this).attr("value");
data.push(id);
console.log(data);
$.ajax({
type: 'POST',
url: 'controllers/StockController.php',
data: {data: data},
dataType: 'json'
});
});
});
Related
I have a dynamic table and i want to send in controller by ajax. I have code ajax like this :
$(".save").click(function(e){
var items = new Array();
$("#list-item tr.item").each(function () {
$this = $(this)
var ref_item_id = $this.find("#ref_item_id").val();
var ref_pic_id = $this.find("#ref_pic_id").val();
var price= $this.find("#price").val();
var qty= $this.find("#qty").val();
items.push({ ref_item_id : ref_item_id, ref_pic_id : ref_pic_id, price: price, qty : qty});
});
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: '<?php echo base_url("transac/save")?>',
dataType: "json",
data: JSON.stringify({'items': items }),
success: function (data) {
var obj = $.parseJSON(data);
alert(obj.lenth);
},
error: function (result) { alert(result); }
});
})
now, how get data in controller and save in table database. My Controller like this :
public function penjualan_save(){
$items = $this->input->post("items");
// next code ???
}
I hope you can help me. Thanks
first thing, your don't need JSON.stringify({'items': items }), just use:
data: {'items': items },
and in your controller, just create a model and pass your post data into it, for example:
public function penjualan_save(){
$items = $this->input->post("items");
$this->load->model('model_name');
$this->model_name->insert($items);
}
then you need to define a function for your model, like this:
public function insert($data)
{
// if you didn't call database library in autoload.php
$this->load->database();
$this->db->insert_batch('mytable', $data);
}
Hi I am trying to make an save / create an item using ajax.
I am not that familiar with ajax and wanted to ask which steps I have to do next to make the save / create function make work.
How do I get the data and save it in my database.
So far my ajax code looks like this:
$(document).ready(function() {
$("#save-item").click(function(e) {
e.preventDefault();
var id = $('#item-id').data('item-id');
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'),
}
});
$.ajax({
url: 'joke/create',
type: 'post',
data: {
id: id,
content: $('#item').val()
},
success: function(data) {
console.log("Success with data " + data);
},
error: function(data) {
console.log("Error with data " + data);
}
});
});
});
And my Controller looks like this:
public function create(Request $request)
{
$item = new Item;
if($data->save())
{
return response()->json(["response" => 200, "joke" => $item]);
}
else
{
return response()->json(["response" => 400, "joke" => $item]);
}
}
try this inside your controller:
$item = new Item;
$data = $request->all();
$item->create($data);
$item = new Item;
$data = $request->all();
if($item->create($data))
{
return response()->json(["response" => 200, "joke" => $item]);
}
else
{
return response()->json(["response" => 400, "joke" => $item]);
}
Although I manage to send the grid's selected row id to the controller, the url for opening action view cannot be built up (it is created /Controller/Action instead of /Controller/Action/id. So, when I try to open the view with /Controller/Action/id it is open, but it cannot be opened by button click as below.
View:
<input type="button" id="btn" name="name" value="send to Server!" />
<script>
$('#btn').click(function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "POST",
data: item.ID, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")',
success: function (result) {
//console.log(result);
}
})
})
</script>
Controller:
// GET: /Training/CreateParticipant/5
public ActionResult CreateParticipant(int? id)
{
Training training = repository.Trainings.FirstOrDefault(m => m.ID == id);
if (training == null)
{
return HttpNotFound();
}
var trainingParticipantViewModel = new TrainingParticipantViewModel(training);
return View(trainingParticipantViewModel);
}
Route.config:
public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
//defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
defaults: new { controller = "Multiplier", action = "Index", id = UrlParameter.Optional }
);
}
}
Is there another example as above to pass the parameters or is there any mistake on the code above? Thanks in advance.
Javascript
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "GET",
data: item.ID, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")/'+item.ID,
datatype:'html',
success: function (result) {
alert(result)
}
})
})
Or use
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
window.location.href= '#Url.Action("CreateParticipant", "Training")/'+item.ID;
});
Hope this helps.
.ToolBar(toolbar =>
{
toolbar.Template(#<text>
<div class="toolbar">
#(Html.Kendo().Button()
.Name("addbtn")
.Content("Add New")
.HtmlAttributes(new { type = "button", #class = "k-primary k-button k-button-icontext js-myKendoButton", #data_id = #Model.YourID, onclick = "onClick()" })
)
</div>
</text>);
})
And then you will grab the data-attribute with jQuery.
$('.js-myKendoButton').attr('data-id');
More here: How to use dashes in HTML-5 data-* attributes in ASP.NET MVC
<script>
$('#btn').on("click",function () {
var items = {};
var grid = $('#Grid').data('kendoGrid');
var selectedElements = grid.select();
var item = grid.dataItem(selectedElements[0]);
$.ajax({
type: "POST",
data: {ID : item.ID}, //I obtained the id properly
url: '#Url.Action("CreateParticipant", "Training")',
success: function (result) {
//console.log(result);
}
})
})
</script>
use this ,i hope this will be help you
I'm using ajax to get the corresponding row values in modal popup for edit in MVC 4 razor..
for username textbox i get like this...
#Html.TextBoxFor(u => u.useredit.userName,new { #class = "input-xlarge focused", id="Edituname", type = "text" })
if i use same method for checkbox..
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting plain checkbox.where i gone wrong..or is there any other way for check box,,
Controller:
for getting values through ajax
[HttpPost]
public ActionResult getUserState(int userid)
{
TBLAppUser user = new TBLAppUser();
user = _repository.GetUserByID(userid);
string[] data = new string[10];
data[0] = user.userName;
data[1] = user.firstName;
data[2] = user.lastName;
data[3] = user.email;
data[4] = user.userID.ToString();
data[5] = user.statusID.ToString();
data[6] = user.isdelete.ToString();
data[7] = user.userName;
data[8] = user.password;
data[9] = user.isActive.ToString();
return Json(data);
}
javascript:
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
$('#Edituname').val(data[0]);
$('#Editfname').val(data[1]);
$('#Editlname').val(data[2]);
$('#Editemail').val(data[3]);
$('#Editid').val(data[4]);
$('#state').val(data[5]);
$('#isdelete').val(data[6]);
$('#Editname1').val(data[7]);
$('#Editpsd').val(data[8]);
$('#EditActiv').val(data[9]);
},
error: function (response) {
alert("error:" + response);
}
});
}
view.cshtml:
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
i'm getting the unchecked checkbox in edit popup..pls smeone help me..thnks in advance...
For your view
#Html.CheckBoxFor(u => u.useredit.isActive, new {id="EditActiv"})
Make the below changes and see if it working
[HttpPost]
public ActionResult getUserState(int userid)
{
data[9] = user.isActive.ToString()
return Json(data);
}
Try use prop() method
<script type="text/javascript">
function Getuser(_StateId) {
var url = "/admin/getUserState/";
$.ajax({
url: url,
data: { userid: _StateId },
cache: false,
type: "POST",
success: function (data) {
var editCheck=(data[9]=== 'true')?true:false;
$('#EditActiv').prop('checked',editCheck); //use prop()
}
});
The following code works great with a hardcoded array (initialData1), however I need to use jquery .ajax (initialData) to initialize the model and when I do the model shows empty:
$(function () {
function wiTemplateInit(winame, description) {
this.WIName = winame
this.WIDescription = description
}
var initialData = new Array;
var initialData1 = [
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
{ WIName: "WI1", WIDescription: "WIDescription1" },
];
console.log('gridrows:', initialData1);
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data) {
for (var i = 0; i < data.d.length; i++) {
initialData.push(new wiTemplateInit(data.d[i].WiName,data.d[i].Description));
}
//console.log('gridrows:', initialData);
console.log('gridrows:', initialData);
}
});
var viewModel = function (iData) {
this.wiTemplates = ko.observableArray(iData);
};
ko.applyBindings(new viewModel(initialData));
});
I have been trying to work from the examples on the knockoutjs website, however most all the examples show hardcoded data being passed to the view model.
make sure your "WIWeb.asmx/GetTemplates" returns json array of objects with exact structure {WIName : '',WIDescription :''}
and try using something like this
function wiTemplateInit(winame, description)
{
var self = this;
self.WIName = winame;
self.WIDescription = description;
}
function ViewModel()
{
var self = this;
self.wiTemplates = ko.observableArray();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{UserKey: '10'}",
url: "WIWeb.asmx/GetTemplates",
success: function (data)
{
var mappedTemplates = $.map(allData, function (item) { return new wiTemplateInit(item.WiName, item.Description) });
self.wiTemplates(mappedTemplates);
}
});
}
var vm = new ViewModel();
ko.applyBindings(vm);
If you show us your browser log we can say more about your problem ( Especially post and response ). I prepared you a simple example to show how you can load data with ajax , bind template , manipulate them with actions and save it.
Hope this'll help to fix your issue : http://jsfiddle.net/gurkavcu/KbrHX/
Summary :
// This is our item model
function Item(id, name) {
this.id = ko.observable(id);
this.name = ko.observable(name);
}
// Initial Data . This will send to server and echo back us again
var data = [new Item(1, 'One'),
new Item(2, 'Two'),
new Item(3, 'Three'),
new Item(4, 'Four'),
new Item(5, 'Five')]
// This is a sub model. You can encapsulate your items in this and write actions in it
var ListModel = function() {
var self = this;
this.items = ko.observableArray();
this.remove = function(data, parent) {
self.items.remove(data);
};
this.add = function() {
self.items.push(new Item(6, "Six"));
};
this.test = function(data, e) {
console.log(data);
console.log(data.name());
};
this.save = function() {
console.log(ko.mapping.toJSON(self.items));
};
}
// Here our viewModel only contains an empty listModel
function ViewModel() {
this.listModel = new ListModel();
};
var viewModel = new ViewModel();
$(function() {
$.post("/echo/json/", {
// Data send to server and echo back
json: $.toJSON(ko.mapping.toJS(data))
}, function(data) {
// Used mapping plugin to bind server result into listModel
// I suspect that your server result may contain JSON string then
// just change your code into this
// viewModel.listModel.items = ko.mapping.fromJSON(data);
viewModel.listModel.items = ko.mapping.fromJS(data);
ko.applyBindings(viewModel);
});
})