How to get value to the controller from view - javascript

I am struggling hard to get value to my controller. Please can some one suggest a way to get value to controller from view. Application is in .Net3.5 and MVC 2 for .Net3.5
The view with jquery and controller is:
The jquery and the html is:
<tr>
<td style ="width: 313px">
<label for="Product Code"> Product
Code
</label>
<select id ="prodList" style = "width:150px">
<option value ="GL ">GL </option>
<option value ="Property" selected="selected">Property </option>
<option value ="Package" >Package </option>
<option value ="Island" >Island </option>
</select>
</td>
<td style="width: 313px"><input type ="button" id="addProd" value ="Add Product" /></td>
</tr>
<script src="/Scripts/jquery-1.4.1.min.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1.min-vsdoc.js" type="text/javascript"></script>
<script src="/Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$("#addProd").click(function() {
//alert("here");
var selectedID = $("#prodList").val();
alert("me 1" + selectedID);
$.ajax({
url: "/WorkFlowTest/ProductSubmission/",
type: 'POST',
data: { productID: $("#prodList").val() },
contentType: 'application/json; charset=utf-8',
success: function(data) {
//alert(data.success);
alert("success");
},
error: function() {
alert("error");
}
});
});
});
</script>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ProductSubmission(string productID, ViewModels.WorkFlowTestViewModel SubmissionModelView)
{
SubmissionModelView.selectedProd = prodSelected ;
return View("Submission", SubmissionModelView);
}
In the jquery function the alert has the selected value, but
for the SubmissionModelView has all properties null and the productId is null too.
Though in browser console I get Source {"productId":"Property"} , but I can not understand why my post does not get any value in the Action ProductSubmission.
Can any one help , I just need the controller to get the selected option value on Post or even a text value on Post. I am not able to get any value from view to controller and my model has also all properties null in POST. Please help

You should convert the object to JSON string by using the JSON.stringify function.
$.ajax({
url: "/WorkFlowTest/ProductSubmission/",
type: 'POST',
data: JSON.stringify({ productID: $("#prodList").val() }),
contentType: 'application/json; charset=utf-8',
success: function(data) {
//alert(data.success);
alert("success");
},
error: function() {
alert("error");
}
});

Related

ajax jQuery auto reload data when browser page refresh

how can i use ajax jquery to autoreload data from selected field related data to input field? it's only working when i am using $("#id_books").change(function()! but i want to load data when browser page refresh or on page load....
create-form.html
<select name="books" class="form-control" id="id_books">
<option value="1" selected="">haxer</option>
<option value="2">django</option>
<option value="3">HCV</option>
<option value="4">python</option>
<option value="5">CBC</option>
</select>
<div class="form-group col-sm-2 text-center">
<input class="form-control" type="text" name="price" id="priceData" readonly>
</div>
<script>
$("#id_books").load(function () {
var id = $(this).val();
$.ajax({
url: `http://localhost:8000/report/${id}`,
data: { 'id': id },
dataType: 'json',
success: function (response) {
if (response != null) {
$('#priceData').val(response.price);
}
}
});
});
</script>
Try using $(document).ready(), which will fire on page load. e.g:
$(document).ready(function() {
alert("Page has loaded!");
});
You'll most likely need to refactor your code as $(this).val(); won't work (as 'this' is no longer '#id_books')
I've not tested the following (but it should give you an idea), try the following:
<script>
$(document).ready(function() {
loadData()
});
$("#id_books").change(function () {
loadData()
});
function loadData()
{
var id = $("#id_books").val();
$.ajax({
url: `http://localhost:8000/report/${id}`,
data: { 'id': id },
dataType: 'json',
success: function (response) {
if (response != null) {
$('#priceData').val(response.price);
}
}
});
}
</script>

How to prevent from data looping in jQuery Ajax?

This is regarding assigning multiple user using Select2 plugin, Ajax and API. The situation, I have a function that contain of 2 Ajax with different pointed URL. Currently, I have pre-selected user that stored in DB. The selection is using Select2 in a Modal. So what is happen now when Modal is opened, 1st Ajax will load URL /all_user to display all user in DB. After that 2nd Ajax will load URL /activity to get and load information for other fields in the same Modal. Both URLs are running in parallel.
URL /all_user successful to display all user. URL /activity also successful to display pre-selected user. However, when I close the Modal and re-open back the same Modal without refresh page, it will definitely load the same function that contain 2 Ajax as mentioned above.
FYI, in /activity I have doing a function to convert from String to Array since I received in String from DB, so need to convert before displaying in Select.
So the problem is both are the data will be duplicate 2x, when I close and re-open, it will duplicate 3x. How to prevent from the duplication?
Below are the pre-selected Select2 in /activity.
Below are the /all_user that successfully display all user
So when Modal is close and re-open back, duplication happen.
HTML
<select type="text" class="form-control mySelect" id="editOwner" name="editOwner" multiple="multiple"></select>
SELECT2 INIT
var mySelect = $('.mySelect').select2({
allowClear: true,
placeholder: "Search Owner...",
minimumResultsForSearch: -1,
width: 600,
});
JS
<span onclick='editOwner(""+value3.l3_id+"")'></span>
function editOwner(id){
activity_id = id;
$.ajax ({
url: '/all_user',
crossDomain: true,
type: "POST",
dataType : 'json',
cache: false,
processData: true,
data: 'data',
success: function(response){
for (var i = 0; i < response.data.length; i++) {
$("#editOwner").append($("<option>", {
response: response.data[i].fullname,
text: response.data[i].fullname
}));
}
}
});
$.ajax({
url : '/activity',
crossDomain: true,
type: "POST",
dataType : 'json',
cache: false,
processData: true,
data: {task_id: activity_id}},
success: function(response){
if (response.status == "Success"){
$("#editOwner").val(response.data[0]["task_owner"]).attr("readonly",false);
$(response.data).each(function(key,value){
var owners = value.task_owner.split(',');
$(owners).each(function(k,v){
$("#editOwner").append($("<option selected>", {
response: v,
text: v
}));
});
$("#editOwner").val(owners).trigger("change");
});
}
else {}
},
error: function(e){}
});
$('#editOwnerModal').modal('show');
}
This is because you are calling:
editOwner(id);
on the click event of your your span that contains your select with the ID of #editOwner.
Like this:
<body>
<select id="cars" style="display: block">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function addCar ()
{
$("#cars").append
(
$("<option>", { response: "Ford", text: "Ford" })
);
}
$("#cars").on
(
"click",
addCar
);
</script>
</body>
Every time you open and close the select element with the ID of #editOwner your appending a new option to the select element. You can easily fix this by adding:
$("#editOwner").unbind();
Like this:
<body>
<select id="cars" style="display: block">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function addCar ()
{
$("#cars").append
(
$("<option>", { response: "Ford", text: "Ford" })
);
// Add this to remove the onclick events for #cars so it will only run one time.
$("#cars").unbind();
}
$("#cars").on
(
"click",
addCar
);
</script>
</body>
Or better yet you could only have the function run one time by not calling it with a onclick event at all like this:
<body>
<select id="cars" style="display: block">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<script type="text/javascript" src="jquery-3.4.1.min.js"></script>
<script type="text/javascript">
function addCar ()
{
$("#cars").append
(
$("<option>", { response: "Ford", text: "Ford" })
);
}
</script>
<script type="text/javascript">
addCar();
</script>
</body>
Unless there is a reason you need to call your ajax with a onclick event you really shouldn't, but if you need to you should call $("#editOwner").unbind(); at the end of editOwner(id); like this:
Edit: Saw that you were calling editOwner(id) with a span that had a onclick event. Just add an ID to that and call $("#mySpan").prop("onclick", null).off("click");
<span id="#mySpan" onclick='editOwner(""+value3.l3_id+"")'></span>
function editOwner(id){
activity_id = id;
$.ajax ({
url: '/all_user',
crossDomain: true,
type: "POST",
dataType : 'json',
cache: false,
processData: true,
data: 'data',
success: function(response){
for (var i = 0; i < response.data.length; i++) {
$("#editOwner").append($("<option>", {
response: response.data[i].fullname,
text: response.data[i].fullname
}));
}
}
});
$.ajax({
url : '/activity',
crossDomain: true,
type: "POST",
dataType : 'json',
cache: false,
processData: true,
data: {task_id: activity_id}},
success: function(response){
if (response.status == "Success"){
$("#editOwner").val(response.data[0]["task_owner"]).attr("readonly",false);
$(response.data).each(function(key,value){
var owners = value.task_owner.split(',');
$(owners).each(function(k,v){
$("#editOwner").append($("<option selected>", {
response: v,
text: v
}));
});
$("#editOwner").val(owners).trigger("change");
});
}
else {}
},
error: function(e){}
});
$('#editOwnerModal').modal('show');
// Try adding this.
//$("#editOwner").unbind();
// Or this if you want to use onclick as an attribute.
$("#mySpan").prop("onclick", null).off("click");
}

When sending multi select value jquery/ajax data is incorrect?

I have multi select drop down menu. When user selects values jquery/ajax request should be sent to the server. Here is example of my code:
$("#send").on("click", function() {
var elem$ = $("#cars"),
elemVal = elem$.val();
console.log(elemVal);
if (elemVal) {
$.ajax({
type: 'POST',
url: 'requestTest.html?fn=saveCar',
data: {'cars': elemVal},
dataType: 'json'
}).done(function(obj) {
console.log(obj);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("An error has occured.");
});
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<select name="cars" id="cars" multiple>
<option value="">--Select Car--</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="opel">Opel</option>
<option value="audi">Audi</option>
</select>
<button type="button" name="send" id="send">Send</button>
The code ajax call returned an error. It was telling me that cars element is required in my function but it's not passed in. I checked my developer tools and here is what I found under Params:
{"cars[]":["volvo","saab"]}
It looks that data is not structured properly. I'm wondering what is causing cars to get an array in front? What is the best way to fix this issue? Thank you.
With this code is going to work better:
<script type="text/javascript">
$("#send").on("click", function() {
var elem$ = $("#cars").val();
//elemVal = elem$.val();
console.log(elem$);
if (elem$) {
$.ajax({
type: 'POST',
url: 'requestTest.html?fn=saveCar',
data: {'cars': elem$},
dataType: 'json'
}).done(function(obj) {
console.log(obj);
}).fail(function(jqXHR, textStatus, errorThrown) {
alert("An error has occured.");
});
}
});
</script>
This give you an array, this array you can manage it from php:
Image of my console with this code

how to return a php value from controller to view, route requested via AJAX?

This is my ajax function in view calling the controller.
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "get",
url: '/rooms/{{ $roomtype->type_id }}',
data: "",
success: function(data) {
console.log(data);
//var str = "<option value="+data+">"+data+"</option>";
//console.log(str);
//$( "select" ).append( str );
//$( ".inner" ).append( str );
}
})
});
</script>
This is my controller function being called by my ajax from view
public function numberOfRooms($type_id, Request $request) {
$room_model = new room;
// $request->session()->forget('no_rooms');
//$request->session()->regenerate();
$no_rooms = $room_model - > where('type_id', '=', $type_id) - > get() - > count();
//$request->session()->put('no_rooms', $no_rooms);
return back() - > with($no_rooms);
}
I want the variable to be returned here inside a drop down :
<select class="inner right-align">
<option value="" disabled selected>Choose your option</option>
<option>{{ $no_rooms }}</option>
</select>
Check your code, there are several things you have to keep in mind
In controller, return a array with the information
public function numberOfRooms(Request $request, $type_id)
{
$room_model = new room;
$no_rooms = $room_model->where('type_id', '=', $type_id)->get()->count();
return [ 'rooms' => $no_rooms];
}
in HTML,
add csrf token
<html>
<head>
...
<meta name="csrf-token" content="{{ csrf_token() }}" />
...
define a selector:
<select id="your-selector" class="inner right-align">
<option value="" disabled selected>Choose your option</option>
</select>
in JS
$(document).ready(function(){
$.ajaxSetup({
headers : {
'X-CSRF-TOKEN' : $('meta[name="csrf-token"]').attr('content')
},
});
function loadRoom(){
$.ajax({
type: "get",
url: '/rooms/{{ $roomtype->type_id }}',
data: "",
success: function(data) {
for (room in data.rooms) {
$('#your-selector').append($('<option>', {
value: room.id,
text: room.name
}));
}
}
})
}
loadRoom();
});
I hope it works good luck
use {{url('/rooms/'.$roomtype->type_id)}} and add data : {"_token": "{{ csrf_token() }}"}
in your ajax url.
and change return statement in your controller like this
return Response::json($no_rooms);
In your controller
return array(
'rooms' => $rooms
);
In your ajax
add this dataType: "json" after type: "GET" or anywhere like this
$ajax({
type: "get",
dataType: "json"
And in your ajax success parse the data
success:function(data){
console.log(data.rooms)
}

Angular js Button click

I have created a button which on click gives an ajax call and the server response obtained through ajax is binded to table using angular js. The issue is according to me on first click of the button itself the data must appear on the webpage.But this happens on second click of the button.I am able to sort and filter data properly but the problem is i need to click button two times separately before it fetches the table
<script>
var fooddata = angular.module("fooddata", []);
fooddata.controller("myCtrl", function ($scope) {
$scope.binddata = function () {
$.ajax({
type: "POST",
url: "ASSIGN.aspx/OnDataFetch",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
);
</script>
<body>
<div id="id001"></div>
<div ng-app="fooddata" ng-controller="myCtrl">
// enter code here
<button ng-click="binddata()">Data Fetch</button>
<div>Sort by:
<select ng-model="sortExpression">
<option value="food_id">Food id</option>
<option value="type">Type</option>
<option value="priority">Priority</option>
</select>
</div>
Filter By Any:
<div><input type="text" ng-model="search" /></div>
<table border="1" cellpadding="10">
<tr><td>Food id</td><td>Type</td><td>priority</td></tr>
<tr ng-repeat="items in foods.d | orderBy:sortExpression | filter:search">
<!-- <td ng-repeat="cell in items">{{cell}}</td> -->
<td>{{items.food_id}}</td>
<td>{{items.type}}</td>
<td>{{items.priority}}</td>
</tr>
</table>
</div>
</body>
You problem is, you are using $.ajax. which won't running digest cycle resultant the binding will not update on html/scope. You must use $http instead of $.ajax, If you use $http angular will run digest cycle when the ajax completed.
Code
$http({ //<-- make sure you have added $http dependency on controller
method: "POST",
url: "ASSIGN.aspx/OnDataFetch",
headers: {
'Content-Type': "application/json; charset=utf-8"
}
}).
success(function(response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
}).
error(function(response) {
alert(response.d);
})
Use jQuery ajax while angular provided you $http is problematic
and considered as bad practice.
Define you controller like this:
fooddata.controller("myCtrl", function ($scope, $http) {
And then do this do run ajax
$scope.binddata = function(){
var request = $http({
method: "post",
url: "yourAjaxFile.php",
data: {
//data
},
//contentType,
headers: {
'Content-Type': "application/json; charset=utf-8"
}
});
/* Check whether the HTTP Request is successful or not. */
request.success(function (data) {
$scope.foods = data;
});
}
In case of Async calls like $.ajax(), the angular scope is no longer updated on inside events. So you need to do $apply manually to apply the updates or you can go forward with any of the other solutions provided by others. They too work well.
<html><head><script>
var fooddata = angular.module("fooddata", []);
fooddata.controller("myCtrl", function ($scope) {
$scope.binddata = function () {
$.ajax({
type: "POST",
url: "ASSIGN.aspx/OnDataFetch",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
response.d = $.parseJSON(response.d);
$scope.foods = response;
if(!$scope.$$phase)
$scope.$apply();
},
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
}
}
);
</script>
<body>
<div id="id001"></div>
<div ng-app="fooddata" ng-controller="myCtrl">
enter code here
<button ng-click="binddata()">Data Fetch</button>
<div>Sort by:
<select ng-model="sortExpression">
<option value="food_id">Food id</option>
<option value="type">Type</option>
<option value="priority">Priority</option>
</select>
</div> Filter By Any:
<div><input type="text" ng-model="search" /></div>
<table border="1" cellpadding="10">
<tr><td>Food id</td><td>Type</td><td>priority</td></tr>
<tr ng-repeat="items in foods.d | orderBy:sortExpression | filter:search">
<!-- <td ng-repeat="cell in items">{{cell}}</td> -->
<td>{{items.food_id}}</td>
<td>{{items.type}}</td>
<td>{{items.priority}}</td>
</tr>
</table>
</div>
</body>
</html>

Categories