pass header value in jQuery AJAX POST firefox - c#

I called a Rest service in jQuery AJAX POST method. I need to pass two values in header.
Firefox neither pass the header value to the service nor calls the REST service. My Jquery code
var postCall = function () {
$.support.cors = true;
var HFAssoRefId = document.getElementById('MainContent_HFAssoRefId').value;
var Input = {
AssoRefId: HFAssoRefId
};
alert(JSON.stringify(Input));
var url = document.URL;
var name = "samuel";
$.ajax({
type: "POST",
beforeSend: function (xhr) {
xhr.setRequestHeader("PartnerName", name);
xhr.setRequestHeader("URL", url);
},
url: "http://localhost:40680/Service.svc/TokenInsertion",
data: JSON.stringify(Input),
contentType: "application/json",
dataType: "json",
success: function (response) {
alert(response);
},
error: function (xhr, status, error) {
alert(status);
}
});
}
Is there any other methods to pass the header values in jQuery AJAX. It works fine with Internet Explorer 8. How to make it work compatible with Firefox browser also ?
I tried the other methods for posting like this.
Method 1 :
$(document).ready(function () {
$("#button").click(function(){
var name1 = "samuel";
var url1 = document.URL;
$.post('http://localhost:41855/IntegrationCheck/Default.aspx', {
name : name1,
url : url1
},function (data) {
alert(data);
});
});
});
and MEthod 2 in AJAX jQuery:
function setHeader() {
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.setRequestHeader('Accept', '');
xhr.setRequestHeader("Content-Type", "application/json");
xhr.setRequestHeader("Accept", "text/xml;application/json");
xhr.setRequestHeader("PartnerName", name);
xhr.setRequestHeader("URL", url);
}
But the header values are not passed and the service is not called in Firefox.
Any suggestions..

I used to follow the below approach to set request header. Please try it if works for you.
[Script]
$("#element").ajaxSuccess(function (evt, request, settings) {
$('.Status').html(request.getResponseHeader("Status"));
});
[View]
<h2>Status:</h2><h2 class="Status" style="color:Red;">
[Controller]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Save(Order orders)
{
string status = string.Empty;
if (orders != null)
{
OrderRepository.Update(orders);
status = "Updated";
}
Response.AddHeader("Status", status);
return data.GridActions<EditableOrder>();
}

Read about headers at jQuery.ajax.
Pass request headers in a jQuery AJAX GET call

Related

Why does my ajax call not returning my data from controller?

I'm having a hard time getting the data from client but my code on visual studio when I'm on a breakpoint it gets the data but I cant receive it on my browser.
Here's my AJAX call
function GetRecord() {
var elemEmployee = 55;
var startDT = $('#searchFilterStartDate').val();
var endDT = $('#searchFilterEndDate').val();
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data);
}
});
}
here's my controller:
[HttpGet]
public List<DTRRecordList.Entity> GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
return entity.GetDTR(data);
}
As you can see below I got 38 records but I can't receive it on my js even that console.log('Data Success') is not shown on my console.
You need to return JSON from your Controller method. You can change your method to:
[HttpGet]
public JsonResult GetDTRRecord(DTRRecordList.Entity data)
{
var entity = new DTRRecordList();
var getDTR= entity.GetDTR(data);
return Json(new {dtrData= getDTR});
}
And in your Ajax call:
$.ajax({
url: "/Modules/GetDTRRecord",
type: "GET",
data: {
EmployeeID: elemEmployee,
DateFrom: endDT,
DateTo: startDT,
},
dataType: "json",
success: function(data) {
console.log('Data Success ');
console.log(data.dtrData);
},
error: function(error) {
console.log(error)
}
});
After a discussion with O.P and seeing the code, it was found that the issue was happening because the form submit was happening which was causing the page to reload twice. After removing the form event and adding the click event in:
$(document).ready(function () {
//On Clink "Search Button"
$("#searchbtn").click(
function () { GetRecord(); });
});
The data seems to be coming as expected.

Ajax Posting twice ASP NET CORE MVC

Controller
[HttpPost]
public IActionResult Index(string mainFin, string actNumber, int actTypeId)
{
int userId = Int16.Parse(User.FindFirstValue(ClaimTypes.NameIdentifier));
Act act = new Act()
{
ActTypeId = actTypeId,
CreateDate = DateTime.Now,
ApproveDate = null,
UserId = userId,
StatusId = 1,
};
_unitOfWork.ActRepository.Add(act);
_notyf.Success("Arayış əlavə edilid !");
_unitOfWork.Complete();
return RedirectToAction("Marriage");
}
AJAX
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
},
error: function () {
console.log("------");
}
});
e.preventDefault();
$("#questForm1").submit();
});
});
Problem : When I click submit button data inserts twice to database (AJAX makes 2 request at same time )
If you want to submit the form via AJAX then you need to remove the last line of the click event handler.
$("#questForm1").submit();
This line is submitting the form and essentially negating the e.preventDefault() above.
You are submitting your data twice: at first using ajax and after that using using the form submit.
You have to remove one of them, I would guess the form submit.
Also, since ajax is called async, if you want to do something after ajax has been called and returned successfully, you have to put the code in success section.
So the code should look like:
$(function () {
var actTypeId = $("#questList option:selected").val();
console.log("QuestList ishledi !");
$('#formSubmit').click(function (e) {
e.preventDefault();
var mainFin = $("#FinInput").val();
var actNumber = $("#actNumber").val();
console.log(mainFin);
$.ajax({
url: "/Home/Index",
type: "POST",
data: { mainFin: mainFin, actNumber: actNumber },
success: function (data) {
console.log("+++++");
// do your thing here, once the ajax requst has returned successfully
},
error: function () {
console.log("------");
}
});
// NOTICE: form submit removed
});
});

XMLHttpRequest cannot load URL. Invalid HTTP status code 400 (WebApi with angularJs on Chrome)

I have WebApi Application and a simple consuming web client. I am sending requests to webApi using angularJS from web client. And cors is already enabled of course.
I have had problems with Post on chrome but I fixed it using param to the object sent, I thought it would be the same for Put but I got 'XMLHttpRequest cannot load URL. Invalid HTTP status code 400' on chrome whereas it's working okay on IE.
C# code :
public void UpdateLampe(int Id, Lampe lampe)
{
var context = new eDomDataContext();
var found = context.Lampes.SingleOrDefault(p => p.Id == Id);
if (found != null)
{
found.Etat = lampe.Etat;
found.Date = DateTime.Now;
context.Lampes.Attach(found);
context.Entry(found).State = EntityState.Modified;
context.SaveChanges();
}
}
//Post request (works ok)
var lampe = $.param({'TypeObject': typeObject, 'SalleId': salleId});
$http({
method: "POST",
url: "http://localhost:1770/api/Lampe",
data: lampe,
headers: {'Content-Type': 'application/x-www-form-urlencoded',}
}).success(function (data) {
alert("it works");
}).error(function () {
console.log(Error);
alert('Error reading JSON file.');
})
.then(function (response) {
return response;
});
//Put request <= still have problem
var etat = $.param({'Etat' : false});
$http({
method: "PUT",
url: "http://localhost:1770/api/Lampe/1" ,
data: etat,
headers: {'Content-Type': 'application/x-www-form-urlencoded',}
}).success(function (data) {
alert("it works");
}).error(function () {
console.log(Error);
alert('Error reading JSON file. - ');
})
.then(function (response) {
return response;
});
Is there anything with what I did?
Thank you for your help.
I found a solution here : http://ask.webatall.com/iis/18460_asp-net-web-api-put-delete-verbs-not-allowed-iis-8.html
It was all about allowing the PUT & DELETE in the web.config
It might help someone.

How to pass argument to ASMX in angularjs

I need to pass an id and get the related questions.
Error message - POST http://localhost:51949/API.asmx/GetAllQuestions/0 - 500 (Internal Server Error)
The web service works fine as I have checked in other part of C# code. Now, trying to access it from angularjs. Is this the right way?
app.js:
var app = angular.module('virtualApp', []);
controller.js:
app.controller("virtualController", function ($scope, DataFactory) {
$scope.categories=[];
$scope.GetAllQuestions = function (categoryId) {
DataFactory.GetAllQuestions(categoryId)
.success(function (data) {
$scope.categories = data;
})
.error(function (error) {
alert(error.message);
});
}
$scope.GetAllQuestions(0); //to fire at page load
});
services.js:
EDIT
app.factory("DataFactory",function ($http) {
var urlBase = "http://localhost:51949/API.asmx/";
var dataFactory = {};
dataFactory.GetAllQuestionCategories = function (categoryId) {
return $http.post(urlBase + "GetAllQuestions", { categoryId: categoryId })
.success(function (data, status, headers, config) {
})
.error(function (data, status, headers, config) {
});
return dataFactory;
});
I think problem with you code is you are passing id as part of url instead of it pass id in data of ajax request
Dont pass data in url like as below
//do not attach categoryId
urlBase + "GetAllQuestions/" + categoryId
instead of it pass data in data parameter of request like as below code
data: { test: 'test' }
and url will be urlBase + "GetAllQuestions
var req = {
method: 'POST',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' },
}
$http(req).success(function(){...}).error(function(){...});
one more thing you are calling function to get data than make use of Get method instead of Post method.

How to get the data from json to MVC4 c#?

I have a MVC4 single page website with a form. The loading of the contents is achieve with ajax. I do not know how to get the data out from JSON in C#? Here is my code:
JavaScript:
$("#subnt").click(function (event) {
event.preventDefault();
var url = "/Home/Submit";
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
})
});
});
C#:
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Please check below working code -
I have used exactly your working code -
[HttpPost]
public JsonResult Submit()
{
return Json(new { Success = true, SomeOtherData = "testing" });
}
Then I used following JQuery to hit the above action -
<script src="~/Scripts/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$('#click').click(function (e) {
$.ajax({
url: "#Url.Action("Submit")",
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
error: function (response) {
alert(response);
},
success: function (data) {
if (data.Success == true)
alert(data.SomeOtherData);
}
});
});
});
</script>
<input type="submit" value="click" id="click" />
And as the output I was able to get an alert as shown below -
Easiest thing to do is use the superior json.net
[HttpPost]
public string Submit()
{
var result = new { success = true, someOtherDate = "testing"};
var json = JsonConvert.SerializeObject(result);
return json;
}
Your code is ok bu you can add debugger.and open developer tools check your data .
$.post(url, $('form[name="cnt_us-frm"]').serialize(), function (data) {
debugger;
if (data.Success === true) {
$("#min-content").hide().load("/Home/PartialSubmit").fadeIn('normal'); // loads the page into 'min-content' section
}
else {
// display error message
}
No, the other way around. How to retrieve the data from the form (json).

Categories

Resources