Passing reference number to data controller - javascript

I am trying to pass my reference data to controller via ajax. The controller didnt receive the data that's why it cannot return query.
This is my button upon click:
$('#inquire_t tbody').on('click', '#mensahe', function () {
var refNumber = $(this).attr('value');
// console.log(refNumber);
getMessageThread(refNumber);
});//btn-message
this is my function:
function getMessageThread(refNumber) {
console.log('This is the reference number: ' + refNumber);
$.ajax({
url: "/getMessageThread",
type: "POST",
headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') },
data: refNumber,
dataType: "TEXT",
success: function (msg) {
}//each
});
}// getMessageThread
and this is my controller:
public function getAllMessage(Request $request) {
$refNumber = $request -> get('refNumber');
$messageThread = DB:: table('i_di_thread')
-> select('message')
-> where('refNumber', $refNumber)
-> get();
return view('showInquiries', ['messageThread'=> $messageThread]);
}
I wanted to get the refNumber value controller to use to my where query

Instead of using $(this).attr('value'), use $(this).val().
Link to API for .val()

Related

Resource can not be found in Asp.NET although path is correct?

I am passing values to the action method using the ajax call. My action method name is TagTargets and this method has three parameters. I am also giving the exact path also but getting the error The resource cannot be found.
//Ajax Call to get targets Data
function TargetsData() {
var realTags = $('#Raw_Tag_List').val();
var calculatedTags = $('#Calculated_Tag_List').val();
var manulTags = $('#Manual_Tag_List').val();
$.ajax({
url: 'TagTargets',
type: 'Post',
contentType: 'application/json',
dataType: 'json',
data: { 'RealTags': realTags, 'CalculatedTags': calculatedTags, 'ManulTags':manulTags},
success: function (data) {
if (data.success) {
alert('Ok')
}
else {
alert('Not ok');
}
}
});
debugger;
}
//Action Method
[HttpPost]
public JsonResult TagTargets(List<string> RealTags, List<string> CalculatedTags, List<string> ManulTags)
{
return Json(true);
}
change your url to a valid url.
url: "#Url.Action("TagTargets","ControllerName");",

How to return parameter route from Laravel to Ajax

I am trying to return the parameter of a laravel route to an ajax response. This is my
public function getPermissions(Request $request)
{
//$v = request()->route()->parameters('profile');
$v = request()->route()->parameters();
return var_dump($v);
}
JS:
function getPermissions() {
let data_permissions = '';
$.post({
url: '/permisos',
async: false,
success: (res) => {
console.log(res)
}
});
}
This is my route:
http://base-laravel.test/profiles/1/edit
In the console returns an empty array.
I intend to obtain the 1 that they see on the route. Suggestions?
You have not added the data to send from Laravel to Ajax Controller. You can pass the data inside the object of the data like
$.post({
url: '/permisos',
type: "POST",
data: {
id: '{{$user->id}}' // Suppose you need to pass the user id to the controller
},
async: false,
success: (res) => {
console.log(res)
}
});
When retrieving the id in the AjaxController, you can simply use the Request $request variable.
public function getPermissions(Request $request)
{
//dd($request->all())
//dd can be use to die and dump the all variable values
return $request->id;
}
Viewing in the console, it will display the Ajax Request Id.
You can use this way
$data = $this->route('parameter_to_access');
return $data

Passing A Single Objects Into An MVC Controller Method Using jQuery Ajax

I'm trying to post a single object data to an MVC Controler using JQuery, Below are my codes.
//declare of type Object of GroupData
var GroupData = {};
//pass each data into the object
GroupData.groupName = $('#groupName').val();
GroupData.narration = $('#narration').val();
GroupData.investmentCode = $('#investmentCode').val();
GroupData.isNew = isNewItem;
//send to server
$.ajax({
url: "/Admin/SaveContributionInvestGroup",
type: "POST",
contentType: "application/json;charset=utf-8",
dataType: "json",
data: JSON.stringify({ GroupData: JSON.stringify(GroupData) }),
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
Below is my controller.
[HttpPost]
public JsonResult SaveContributionInvestGroup(ContributionInvestmentGroup GroupData)
{
ClsResponse response = new ClsResponse();
ClsContributionInvestmentGroup clsClsContributionInvestmentGroup = new ClsContributionInvestmentGroup();
var userID = (int)Session["userID"];
var sessionID = (Session["sessionID"]).ToString();
if (contributionGroupData != null)
{
//get the data from the cient that was passed
ContributionInvestmentGroup objData = new ContributionInvestmentGroup()
{
contributionInvestmentGroupID = 0,
groupName = GroupData.groupName,
narration = GroupData.narration,
investmentCode = GroupData.investmentCode,
isNew = GroupData.isNew
};
response = clsClsContributionInvestmentGroup.initiateNewContributionInvestmentGroup(sessionID, objData);
}
else
{
response.IsException = true;
response.IsSucess = false;
response.Message = "A system exception occurred kindly contact your Administrator.";
}
return Json(new
{
response.IsSucess,
response.Message
});
}
The issue is, the data is not been posted to the controller, the controller receives a null object.
Kindly assist, would really appreciate your effort, thanks.
Try Like this:
//send to server
$.ajax({
type: "POST",
url: "/Admin/SaveContributionInvestGroup",
dataType: "json",
data: GroupData,
success: function (res) {
alertSuccess("Success", res.Message);
//hide modal
$('#product-options').modal('hide');
hide_waiting();
},
error: function (res) {
alertError("Error", res.Message);
}
});
in your controller your dont have custom binding to bind JSON to your model thats why you get null in you parameter.
instead just post it as query, try simply changes your ajax option like so:
{
...
contentType: "application/x-www-form-urlencoded", //default:
...,
data: $.param(GroupData),
...
}
and perhaps property names are case sensitive so you will need to change your javascript model's name

Pass an array as parameter to a controller from an ajax call in JavaScript

I'm working on an ASP.NET MVC 4 website and I've got some troubles with a functionality. I explain, I've to select entities displayed in a table with their linked checkbox :
Screenshot of my table where each row has a checkbox with the same Id as the entity
Console showing updates in the array
Inside my script I have been abled to store each checked Id's checkbox in an array and remove those if the checkbox is unchecked. But I can't pass the array to my controller's function to delete each selected entity in the database.
I used $.ajax() from jquery to send through a POST request the array (as JSON) but I always get 500 error :
JSON primitive invalid
Null reference
Here's my function in my script (I don't know if my array's format is valid) :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Then, the POST call the following function in my controller :
[Authorize]
[WebMethod]
public void DeleteDocuments(string docsToDelete)
{
int id;
string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
}
Update 2
[Authorize]
public ActionResult DeleteDocuments(int[] docsToDelete)
{
try{
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json("Success");
}
catch
{
return Json("Error");
}
}
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: docsArray,
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ' + result.d);
},
error: function (result) {
alert('Fail ' + result.d);
}
});
}
Any ideas about this issue ? I hoped I was clear enough. Do not hesitate if you need more details.
If you are passing an integer array properly from $.ajax (i.e. your docsArray should be having value like [15,18,25,30,42,49]) then you should try :
[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
//int id;
//string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
try {
foreach (int docId in docsArray)
{
//int.TryParse(docId, out id);
dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return "Success ";
}
catch {
return "Error";
}
}
Update :
Your javascript code should be :
var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ');
},
error: function (result) {
alert('Fail ');
}
});
}
Maybe the datatype in the JSON array is not a string? (This could happen if you have an array in the form of [45,64,34,6], or a mixed one like [345,"wef4"]).
To make sure something is a string in Javascript you can do this: var string = "".concat(otherVar);
Try changing your ajax data to something like this..
data : JSON.stringify({'docsToDelete':docsArray}),
Make these changes to your code.
In Jquery
data: docsArray, no need to stringify the array
In Controller
[Authorize] //remove [WebMethod]
public ActionResult DeleteDocuments(string[] docsToDelete) //Add ActionResult, Change parameter to accept array
{
int id;
string[] arrayDocs = docsToDelete; //no need of deserilization
foreach (string docId in arrayDocs)
{
int.TryParse(docId, out id);
dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return Json(id); //return id back to ajax call...
}

in MVC 5 how to pass selected value to html action in jquery ajax function

I am using JQuery ajax to load some data when user selects something from the list. How do i pass value of selected option in action parameters?
I tried by creating variable selectedValue but it says name "selectedValue" does not exists.
<script>
$(document).ready(function () {
$("#students").change(function () {
var selectedValue = $("#students").val();
$.ajax({
url: '#Url.Action("GetData", "Sample", new { table = "Students", id = selected })',
type: "GET",
success: function (result) {
$("#information").html(result);
}
});
});
})
</script>
Are you using the correct variable ? It looks like you are reading the value to selectedValue but not using that. Try this
var selectedValue = $("#students").val();
$.ajax({
url: '#Url.Action("GetData","Sample")?table=Students&id ='+selectedValue,
type: "GET",
success: function (result) {
$("#information").html(result);
}
});
This should work assuming your GetData action method has 2 parameters named table and id
public ActionResult GetData(string table,string id)
{
//to do : return something useful
}
the code that will work for you depends on how you route is setup, but regardless of how you have it setup you will have to append that selected value on the client side.
Assuming this style of route:
/Sample/GetData?table=Students&id=3
This should work for you:
<script>
$(document).ready(function () {
$("#students").change(function () {
var selectedValue = $("#students").val();
$.ajax({
url: '#Url.Action("GetData", "Sample", new { table = "Students" })' + '&id=' + selectedValue,
type: "GET",
success: function (result) {
$("#information").html(result);
}
});
});
})

Categories