hello i have a problem in implementing post operation with jquery ajax in my web api application ,problem is that my controller action method of post operation in working well but in the html page when i am using jquery ajax for calling post method it is not working my html page code is shown below
$("#btnAddSave").click(function () {
alert("hello");
var Fname = document.getElementById("txtAddFName").value;
var Lname = document.getElementById("txtAddLName").value;
var Street = document.getElementById("txtAddStreet").value;
var Landmark = document.getElementById("txtAddLandmark").value;
var City = document.getElementById("txtAddCity").value;
var State = document.getElementById("txtAddState").value;
var Pincode = document.getElementById("txtAddPincode").value;
var Mobile = document.getElementById("txtAddMobile").value;
var AltMobile = document.getElementById("txtAddAltMobile").value;
var Email = document.getElementById("txtAddEmail").value;
alert(City);
var InData = {
"FirstName": Fname, "LastName": Lname, "Street": Street, "Landmark": Landmark, "City": City, "State": State, "Postalcode": Pincode, "Mobile": Mobile, "AltMobile": AltMobile, "UserId": "User102", "AltEmail": "null", "Extra2": "null", "Extra3": "null", "Extra4": "null", "Extra5": "null", "EmailOrMobile": Email, "UserName": "Null","Id":"Null" ,"Status": "Null"
};
alert("aftrJsonobject");
alert(Fname);
$.ajax({
type: "POST",
url: "/api/tblProducts/AddAltAddress",
data: InData,
contentType: "application/json; charset=utf-8",
dataType: "JSON",
processData: true,
success: function (data) {
alert("success...");
}
});
});
and my api controller code which is working well as i tested in fiddler is shown below
[HttpPost]
[Route("api/tblProducts/AddAltAddress", Name = "GetAltAddress")]
public IHttpActionResult InsertAltAddress(tblUserAltAdd AltAdd)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
var AltAddress = db.InsertAltAdd1(AltAdd.FirstName, AltAdd.LastName, AltAdd.Street, AltAdd.Landmark, AltAdd.City, AltAdd.State,AltAdd.PostalCode, AltAdd.Mobile, AltAdd.AltMobile, AltAdd.UserId, AltAdd.AltEmail, AltAdd.Extra2, AltAdd.Extra3, AltAdd.Extra4, AltAdd.Extra5, AltAdd.EmailOrMobile, AltAdd.UserName, AltAdd.Id, AltAdd.Status);
return CreatedAtRoute("GetAltAddress", new { id = AltAdd.UserId }, AltAdd);
}
please help me in implementing it
try this-
$("#btnAddSave").click(function () {
alert("hello");
var Fname = document.getElementById("txtAddFName").value;
var Lname = document.getElementById("txtAddLName").value;
var Street = document.getElementById("txtAddStreet").value;
var Landmark = document.getElementById("txtAddLandmark").value;
var City = document.getElementById("txtAddCity").value;
var State = document.getElementById("txtAddState").value;
var Pincode = document.getElementById("txtAddPincode").value;
var Mobile = document.getElementById("txtAddMobile").value;
var AltMobile = document.getElementById("txtAddAltMobile").value;
var Email = document.getElementById("txtAddEmail").value;
alert(City);
var InData = {
"FirstName": Fname, "LastName": Lname, "Street": Street, "Landmark": Landmark, "City": City, "State": State, "Postalcode": Pincode, "Mobile": Mobile, "AltMobile": AltMobile, "UserId": "User102", "AltEmail": "null", "Extra2": "null", "Extra3": "null", "Extra4": "null", "Extra5": "null", "EmailOrMobile": Email, "UserName": "Null","Id":"Null" ,"Status": "Null"
};
alert("aftrJsonobject");
alert(Fname);
$.ajax({
type: "POST",
url: "/api/tblProducts/AddAltAddress",
data: JSON.stringfy(InData),
contentType: "application/json; charset=utf-8",
dataType: "JSON",
processData: true,
success: function (data) {
alert("success...");
}
});
});
Related
I have this problem when trying to pass a string parameter from DataTable with Ajax to an ASP.NET MVC controller: the parameter is not being sent.
I tried many forms of "data:" options. Please help me, I think I'm missing something important.
When (as a test) I initialize the parameter at the beginning of the controller with ttt="CO" everything goes fine!
$('#tblVacation').DataTable({
"ajax": {
"url": '/Vacation/LoadData2',
"contentType": "application/json;charset=utf-8",
"type": 'GET',
"dataType": 'JSON',
"data" : ' { ttt: "CO" }'
"dataSrc": "",
},
"columns": [
{ "data": "vacationId", width: "5%" },
{ "data": "operatorId", width: "3%" },
{ "data": "operator", width: "10%" },
{ "data": "type", width: "3%" },
]
});
And the controller is:
[HttpGet]
public ActionResult LoadData2(string ttt)
// ttt="CO";
{
List<Vacation> data = null;
try
{
data = DB.Vacations.Include(x => x.Operator).ToList();
var result = data.Select(x => new Vacation_VM
{
VacationId = x.VacationId,
OperatorId = x.OperatorId,
Vacation_doc = x.Vacation_doc,
Operator = x.Operator.Name,
Type = x.Type,
}).Where(m => m.Type == ttt);
return new JsonResult(result);
}
catch (Exception ex)
{
ViewBag.Message = ex.Message;
}
return new JsonResult(null);
}
I also tried with
var entity = {
ttt: "CO"
}
var dataToSend = JSON.stringify(entity);
and
"data": function () {
return dataToSend;
},
but it's still not working. I will need in the future to pass multiple parameters.
Thanks a lot, I will appreciate any advice.
Replace the ajax call part with the followings:
"ajax": {
type: 'GET',
url: '/Vacation/LoadData2',
data: { ttt: "CO" },
dataType: 'JSON',
async: true,
cache: false,
},
I have the following search box for getting data from backend:
<select class="form-control kt-select2" id="megaagent_rainmaker_select" name="param" multiple="multiple" style="width: 100%"></select>
This is my select2 javascript code:
var rainmakerSelect = function () {
// Private functions
var demos = function () {
var CSRF_TOKEN = $('meta[name="csrf-token"]').attr('content');
// multi select
$('#megaagent_rainmaker_select').select2({
language: "es",
placeholder: "Escriba y seleccione",
allowClear: true,
maximumSelectionLength: 1,
ajax: {
url: '/admin/megaagent/getrainmaker',
type: "get",
dataType: 'json',
delay: 150,
data: function (params) {
return {
_token: CSRF_TOKEN,
search: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}
return {
init: function () {
demos();
}
};
}();
jQuery(document).ready(function () {
rainmakerSelect.init();
});
I get results returned and I can select one without problem.
After I select a value, I send update request to backend, this is my payload:
{
"_token": "bPl0hZJQxw5wAxNCqVOOKqrXXwkD5AZZOFPumrpC",
"mc_id": "11",
"megaagent_id": "16",
"megaagent_name": "David Cortada",
"megaagent_business_name": "bsame cambio",
"megaagent_uma_id": "umaid",
"megaagent_api_key": "apikey",
"param": "963",
"megaagent_phone_number": "phone",
"megaagent_email": "email",
"megaagent_address": "address",
"megaagent_facebook": "fb",
"megaagent_instagram": "inst",
"megaagent_twitter": "twi",
"megaagent_linkedin": "link",
"megaagent_image": "image",
"megaagent_status": "Activo"
}
What I want to achieve is to change param name to other on post request (example: "megaagent_rainmaker_id" = "963",.
I changed it in <select name="param"> but that breaks the search, no results are returned when I type in search box.
Does anyone knows the solution for this?
Regards
I am trying to fill the Datatable row content dynamically using Ajax Post. But it loaded the content at first shot correctly but when I try to fill content once again it returns error Can't instantiation Datatable. .
We refereed https://datatables.net/examples/data_sources/js_array.html For datatable row content.
Can Any one please help Us.
$.ajax({
url : SITE_ROOT_DIR+"ajaxFunction.php?Exportedinvoices=1&daterange="+daterange+"&fromDate="+fromDate+"&toDate="+toDate,
type : 'post',
cache : false,
success : function(data){
var message = JSON.parse(data);
var pLen,i;
pLen=message.length;
if(pLen>0){
var carter=[];var carterarr=[];
for(i=0;i<pLen;i++)
{
var company_name=message[i]['company_name'];
var salesOrderID=message[i]['salesOrderID'];
var salesOrderDate=message[i]['salesOrderDate'];
var product_code=message[i]['product_code'];
var quantity=message[i]['quantity'];
var deliveryDate=message[i]['deliveryDate'];
var ponuber=message[i]['ponuber'];
var TermsRefFullname=message[i]['TermsRefFullname'];
var ShipMethodFullName=message[i]['ShipMethodFullName'];
var SalesRepFullName=message[i]['SalesRepFullName'];
var ItemsalesTaxRefFullname=message[i]['ItemsalesTaxRefFullname'];
var CustomerMsgRefFullName=message[i]['CustomerMsgRefFullName'];
var val=company_name+'*'+salesOrderID+'*'+salesOrderDate+'*'+product_code+'*'+quantity+'*'+deliveryDate+'*'+ponuber+'*'+TermsRefFullname+'*'+SalesRepFullName+'*'+ShipMethodFullName+'*'+ItemsalesTaxRefFullname+'*'+CustomerMsgRefFullName;
var carterarr =carterarr+val+'#';
var carter=carterarr.slice(0, -1);
}
var arlene3 = carter.split("#");
var farray=[];var Aarray=[];var myarray=[];
for(var i=0;i<arlene3.length;i++){
var arraynow=arlene3[i];
Aarray=arraynow .split("*");
myarray.push(Aarray);
}
dataSet=myarray;
$('#example1').DataTable( {
destroy: true,
data: dataSet,
columns: [
{ title: "CustomerRefFullName" },
{ title: "InvoiceRefNumber" },
{ title: "TxnDate" },
{ title: "ItemRefFullName" },
{ title: "Quantity" },
{ title: "DueDate" },
{ title: "PoNumber" },
{ title: "TermsRefFullname" },
{ title: "SalesRepFullName" },
{ title: "ShipMethodFullName" },
{ title: "ItemsalesTaxRefFullname" },
{ title: "CustomerMsgRefFullName" },
],
"ordering": false,
"searching": false,
"paging": false,
"info": false,
} );
$('.tabheading').css("display","block");
}
else
{
alert("No datas found");
}
}
});
How to change the snippet and status values of an already uploaded video through YouTube API v3 "https://www.googleapis.com/youtube/v3/videos" using AJAX request?
My UPDATED CODE (NOT Working):
$.ajax({
type: "PUT",
dataType: "jsonp",
url: "https://www.googleapis.com/youtube/v3/videos?part=id,snippet,status&key=<API Key>",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer " + <Access Token>
},
data: $.parseJSON('{"id": "<Video ID>", "snippet": {"title": "New Title", "description": "New Description"}, "status": {"privacyStatus": "unlisted"}}'),
success: function(data, error, completeError) {
alert( JSON.stringify(data));
alert( JSON.stringify(error));
alert( JSON.stringify(completeError));
}
});
Make a PUT request to the videos/update endpoint with the parameter part=id,snippet,status:
HTTP PUT: https://www.googleapis.com/youtube/v3/videos?part=id,snippet,status&key={YOUR_API_KEY}
Body of your request:
{
"id": "VIDEO_ID",
"snippet": { // any snippet fields you want to change
"description": "New Video Description"
},
"status": { // any status fields you want to change
"privacyStatus": "public"
}
}
Here is the code I used when having a play around. It works well though.
It doesn't use JQuery but should point you in the right direction.
function UpdateVideoInfo(video_id){
var resource = {
'snippet':{
'title' : 'test title',
'description' : 'test description',
'categoryId' : 22
},
'status' : {
'privacyStatus' : 'private'
},
'id': video_id
};
post_string = JSON.stringify(resource);
var ajax = new XMLHttpRequest();
ajax.open('PUT', 'https://www.googleapis.com/youtube/v3/videos?part=snippet,status', true);
ajax.setRequestHeader("Authorization", '<?php echo $authorization_header; ?>');
ajax.setRequestHeader("Content-type", "application/json; charset=UTF-8");
ajax.send(post_string);
ajax.onload = function() {
if (ajax.status == 200) {
alert(ajax.responseText);
}
};
}
So here is my code, i've already made the oauth handshake, and that has given me the authentication token which i'm including in my header. I am simply trying to batch insert some features into an existing table. I keep getting a 400 "parseError" - This API does not support parsing form-encoded input.
Here's some of my code. I have no idea where i'm derping any ideas.
$(document).ready(function(){
$('.pickTrip').bind('click', function(){
var pointData = {
"features": [
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
-87.397980,
44.795067
]
},
"properties": {
"gx_id": "1242342",
"name": "Jimmy Choo",
"phone": "(920)555-4242",
"email": "jchoo#aol.com",
"vehicle": "mazda, b2300, 1994"
}
}
]
};
console.log(pointData);
var url = "https://www.googleapis.com/mapsengine/v1/tables/{table id}/features/batchInsert";
jQuery.ajax({
type: "POST",
url: url,
data: pointData,
dataType: 'application/json',
headers: {
'Authorization': 'Bearer ' + authResult.access_token
},
success: function(response) {
// Log the details of the Map.
console.log(response);
},
error: function(response) {
response = JSON.parse(response.responseText);
console.log("Error: ", response);
}
});
});
});
jQuery takes the object provided in the 'data' parameter and turns the key/value pairs into an encoded query string. You will want to send the raw JS object and make sure it's not marked as form encoded. To do that, change the 'dataType' parameter to 'contentType' and update the data value to take the "stringified" version of the JSON object.
Like this:
data: JSON.stringify(pointData),
contentType: 'application/json',