I have a link when pressed it requests a page from a controller via render ajax, Previously i used to pass only the id but now i would like to pass an extra parameter to the controller, how do i achieve this,
This is what i have tried
This is the link' which only passes a single parameter to the controller
Html::a('click me', ['#'],
['value' => Url::to('checktruck?id='.$model->id), //this is where the param is passed
'id' => 'perform']);
This is the controller code expecting 2 parameters:
public function actionChecktruck($id,$category) //it expects 2 parameters from above link
{
$truckdetails = Truck::find()->where(['id' =>$id])->one();
if (Yii::$app->request->post()) {
$checklistperform = new TodoTruckChecklist();
$truck = Truck::find()->where(['id'=>$id])->one();
$checklistperform->truck_id=$id;
$checklistperform->registered_by=Yii::$app->user->identity->id;
$checklistperform->save();
$truck->update();
var_dump($checklistperform->getErrors());
//var_dump($truck->getErrors());
}
else {
$truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all();
return $this->renderAjax('truckyard/_checklistform', [
'truckcategory' => $truckcategory,'truckvalue'=>$id,
]);
}
}
This is my jquery code of another button that depends on the above controller during post request
$("#postbutn").click(function(e) {
$.post("checktruck?id="+truckid, //here i would like to pass 2 params
{checked:checked,unchecked:unchecked,truckid:truckid}
)
}
This is the jquery code when there is no post
How can i pass an extra parameter in the link or even the $.post request for the controller
First of all, as you are using JQuery ajax to submit the form, there is no need to set value for the link
Html::a('click me', ['#'],['id' => 'perform']);
using this id you can submit the request as follows
$this->registerJs("$('#perform').click(function(event){
event.preventDefault(); // to avoid default click event of anchor tag
$.ajax({
url: '".yii\helpers\Url::to(["your url here","id"=>$id,"param2"=>param2])."',
success: function (data) {
// you response here
},
});
});");
There is no need to mention method attribute as 'POST', you want to send through GET method
And finally in your controller, you need to accept parameters as follows
public function actionChecktruck() //it expects 2 parameters from above link
{
$id = Yii::$app->request->queryParams['id'];
$param2 = Yii::$app->request->queryParams['param2'];
$truckdetails = Truck::find()->where(['id' =>$id])->one();
if (Yii::$app->request->post()) {
$checklistperform = new TodoTruckChecklist();
$truck = Truck::find()->where(['id'=>$id])->one();
$checklistperform->truck_id=$id;
$checklistperform->registered_by=Yii::$app->user->identity->id;
$checklistperform->save();
$truck->update();
var_dump($checklistperform->getErrors());
//var_dump($truck->getErrors());
}
else {
$truckcategory = Checklist::find()->where(['truck_category'=>$truckdetails->truck_category])->andWhere(['checklist_category'=>$category])->all();
return $this->renderAjax('truckyard/_checklistform', [
'truckcategory' => $truckcategory,'truckvalue'=>$id,
]);
}
}
Try this one,
In View file
$this->registerJs("$('#postbutn').click(function(){
$.ajax({
url: '".yii\helpers\Url::to(["u r URL"])."',
method: 'POST',
data: {id:id, truckid:truckid },
success: function (data) {
},
});
});");
Related
I have a partial view that I load in a page passing in a parameter. When the page loads, I setup two parameters helpMember and helpAnonymous.
{
var helpMember = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(0);
var helpAnonymous = Model.Content.Children.Where(c => c.DocumentTypeAlias.Equals("contextualHelp", StringComparison.CurrentCultureIgnoreCase)).ElementAt(1);
}
<div id="contextual-help-partial" >
#Html.Partial("ContextualHelp", helpMember)
</div>
With jQuery, how can I reload the Partial and pass helpAnonymous to it?
You have to create one method in controller and call that action using this. Suppose created action as loadhtml. return partialview from that action.
Controller action as
public ActionResult loadhtml(string helpMember){
ViewBag.helpMember = helpMember;
return PartialView("ContextualHelp");
}
jquery code as
$.ajax({
type: 'GET',
url: "/loadhtml?helpMember=#helpMember",
datatype:"html",
success: function (data) {
$("#contextual-help-partial").empty().html(data);
},
error: function (err) {
}
});
I have a form with a submit button. When clicked, it adds listed elements to an array.
$("#submitButton").click(function(){
var selection = $("#selectedList li");
var families_selection = [];
selection.each(function() {
families_selection.push($(this).text().replace(/Remove/,''));
});
});
I want to use the array "families_selection" in the controller "Provider", so I can use the following function and instert the values in a database.
$this->Proveedormodel->add_uk_proveedor_familia($idProveedor, $families_selection);
EDIT: I get the value for $idProveedor in the controller, not in the view, using another function in the same "Proveedor" model.
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
This is how I insert the values in the database in my model.
function add_uk_proveedor_familia($id, $params){
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
How can I use ajax to pass this array to the controller and use the function I need?
Edited code using Dragan Valjak's response. Now it works!
View add.php
$("#botonGuardar").click(function(){
var seleccion = $("#listaSeleccion li");
var familias_seleccion = [];
seleccion.each(function() {
familias_seleccion.push($(this).text().replace(/Quitar/,''));
});
$.ajax({
url: 'Proveedor/crearRelacion',
method: 'POST',
data: {familias_seleccion: familias_seleccion}
});
});
Controller Proveedor.php
function crearRelacion(){
$this->load->model('Proveedormodel');
$familias_seleccion = $this->input->post($data);
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
$this->Proveedormodel->add_uk_proveedor_familia($idProveedor, $familias_seleccion);
}
Model Proveedormodel.php
function add_uk_proveedor_familia($id, $params){
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
$.ajax({
url: 'Provider/functionName',
method: 'POST',
data:
{
families_selection: families_selection
}
});
In Controller
function functionName($data){
$families_selection = $this->input->post($data);
$idProveedor = $this->Proveedormodel->get_idConsecutivo();
$this->Proveedormodel->
add_uk_proveedor_familia($idProveedor,$families_selection);
}
You create your route to handle the ajax, something like '/family_selection' then you can pass your data that you have stored in a post method such as:
$.ajax({
url: '/family_selection',
method: 'POST',
data: {family_data: variable_of_data_you_stored}
});
I'm not familiar with codeigniter but I think you would need to set up a route "something like" $route['family_selection']['post'] = '/family_selection';
In python I would set it up in my controller like so:
Maybe you can use it as an example and implement something similar in codeigniter
#root_resource.route('/family_selection', methods=['POST'])
def family_selection():
family_details = request.form['family_data']
#then I would do whatever it is I want to do with the data...
#then I may or may not want to return an empty response.
return Response(status=http.HTTPStatus.NO_CONTENT)
concentrate on your requirement id and family_data
$.ajax({
url: "Proveedormodel/add_uk_proveedor_familia",
type: 'POST',
data:
{
family_data: variable_of_data_you_stored, //the data that you want to pass..
},
success: function(response)
{
console.log(response);
}
});
In model file: Proveedormodel and function add_uk_proveedor_familia() this changed ur params with family_data
function add_uk_proveedor_familia($id, $params){
$params=$_POST['family_data'];
foreach($params as $clave){
$this->db->select('id')->from('familia')->where('clave', $clave);
$valor = $this->db->get();
$vl = $valor->row_array();
$familia = $vl['id'];
$this->db->insert('relacionproveedorfamilia', array(
'idProveedor' => $id,
'idFamilia' => $familia
));
}
}
here in family_data your passing with large data if your params is the same as family_data then use use post value of family_Data into it.
So, I have a view with a chosen search box, a button "Add" (btn-default) and a button "Edit" (breadcrumb) . When I click the Add button, the ajax sent me a table with the values (in this case, funcionaries) selected in the chosen text box.
I want that, when I click on the Edit button, send the chosen values (can be one, or hundreds of values) to another controller to return another view.
Don't want to use ajax because I want to use a new view on totally.
On the controller side, when I send the data with javascript, I always get null. Why?
View
<script>
$(document).ready(function () {
$(".btn-default").on("click", function (event, params) {
$.ajax({
url: '#Url.Action("EditarPonderacoesEspecial", "Sorteios")',
type: 'POST',
dataType: 'html',
cache: false,
traditional: true,
data: { bdoIds: $(".chosen-select").val() },
success: function (responseText, textStatus, XMLHttpRequest) {
$("#MyDiv").empty();
$("#MyDiv").html(responseText);
},
error: function () { }
})
});
$(".breadcrumb").on("click",function (event, params) {
bdoIds = $(".chosen-select").val();
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", bdoIds);
});
});
Controller
public ActionResult EditarPonderacoesEspecialSecond(string[] bdoIds)
{
//do whatever I want with the bdoIds
return View();
}
I had tried many different ways, but the controller always receive the parameter as null. What I am doing wrong? Thanks!
Your controller action is expecting an array of strings.
Assuming .chosen-select is a select list as that part is missing from the question.
First read the selected values into an object as follows:
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
Then send them as follows:
$(".breadcrumb").on("click",function (event, params) {
var selectedValues = [];
$(".chosen-select :selected").each(function() {
selectedValues.push($(this).attr('value'));
});
$.post("/Sorteios/EditarPonderacoesEspecialSecond/", { bdoIds: selectedValues });
});
Declare Global array like
var SelectedArray = new Array();
When you select multiple selectlist item each time push value in SelectedArray
$('#ChosenId').chosen().change(function () {
SelectedArray = $('#ChosenId').chosen().val();
});
Then your ajax data is like
data: { bdoIds: SelectedArray },
Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.
I have sample code like this:
<div class="cart">
<a onclick="addToCart('#Model.productId');" class="button"><span>Add to Cart</span></a>
</div>
<div class="wishlist">
<a onclick="addToWishList('#Model.productId');">Add to Wish List</a>
</div>
<div class="compare">
<a onclick="addToCompare('#Model.productId');">Add to Compare</a>
</div>
How can I write JavaScript code to call the controller action method?
Use jQuery ajax:
function AddToCart(id)
{
$.ajax({
url: 'urlToController',
data: { id: id }
}).done(function() {
alert('Added');
});
}
http://api.jquery.com/jQuery.ajax/
Simply call your Action Method by using Javascript as shown below:
var id = model.Id; //if you want to pass an Id parameter
window.location.href = '#Url.Action("Action", "Controller")/' + id;
You are calling the addToCart method and passing the product id. Now you may use jQuery ajax to pass that data to your server side action method.d
jQuery post is the short version of jQuery ajax.
function addToCart(id)
{
$.post('#Url.Action("Add","Cart")',{id:id } function(data) {
//do whatever with the result.
});
}
If you want more options like success callbacks and error handling, use jQuery ajax,
function addToCart(id)
{
$.ajax({
url: '#Url.Action("Add","Cart")',
data: { id: id },
success: function(data){
//call is successfully completed and we got result in data
},
error:function (xhr, ajaxOptions, thrownError){
//some errror, some show err msg to user and log the error
alert(xhr.responseText);
}
});
}
When making ajax calls, I strongly recommend using the Html helper method such as Url.Action to generate the path to your action methods.
This will work if your code is in a razor view because Url.Action will be executed by razor at server side and that c# expression will be replaced with the correct relative path. But if you are using your jQuery code in your external js file, You may consider the approach mentioned in this answer.
If you do not need much customization and seek for simpleness, you can do it with built-in way - AjaxExtensions.ActionLink method.
<div class="cart">
#Ajax.ActionLink("Add To Cart", "AddToCart", new { productId = Model.productId }, new AjaxOptions() { HttpMethod = "Post" });
</div>
That MSDN link is must-read for all the possible overloads of this method and parameters of AjaxOptions class. Actually, you can use confirmation, change http method, set OnSuccess and OnFailure clients scripts and so on
If you want to call an action from your JavaScript, one way is to embed your JavaScript code, inside your view (.cshtml file for example), and then, use Razor, to create a URL of that action:
$(function(){
$('#sampleDiv').click(function(){
/*
While this code is JavaScript, but because it's embedded inside
a cshtml file, we can use Razor, and create the URL of the action
Don't forget to add '' around the url because it has to become a
valid string in the final webpage
*/
var url = '#Url.Action("ActionName", "Controller")';
});
});
Javascript Function
function AddToCart(id) {
$.ajax({
url: '#Url.Action("AddToCart", "ControllerName")',
type: 'GET',
dataType: 'json',
cache: false,
data: { 'id': id },
success: function (results) {
alert(results)
},
error: function () {
alert('Error occured');
}
});
}
Controller Method to call
[HttpGet]
public JsonResult AddToCart(string id)
{
string newId = id;
return Json(newId, JsonRequestBehavior.AllowGet);
}
You can simply add this when you are using same controller to redirect
var url = "YourActionName?parameterName=" + parameterValue;
window.location.href = url;
You can set up your element with
value="#model.productId"
and
onclick= addToWishList(this.value);
I am using this way, and worked perfectly:
//call controller funcntion from js
function insertDB(username,phone,email,code,filename) {
var formdata = new FormData(); //FormData object
//Iterating through each files selected in fileInput
formdata.append("username", username);
formdata.append("phone", phone);
formdata.append("email", email);
formdata.append("code", code);
formdata.append("filename", filename);
//Creating an XMLHttpRequest and sending
var xhr = new XMLHttpRequest();
xhr.open('POST', '/Home/InsertToDB');//controller/action
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
//if success
}
}
}
in Controller:
public void InsertToDB(string username, string phone, string email, string code, string filename)
{
//this.resumeRepository.Entity.Create(
// new Resume
// {
// }
// );
var resume_results = Request.Form.Keys;
resume_results.Add("");
}
you can find the keys (Request.Form.Keys), or use it directly from parameters.
You can easily make a <a> link in your view.
<a hidden asp-controller="Home" asp-action="Privacy" id="link"></a>
then in you javascript code use this:
location.href = document.getElementById('link').href;