i came across with a minor conflict while i am reading the html image value and passing value data in java script method works fine, and in ajax POST to pass the value towards controller, and unforunelty ajax point the controller over break point but the string Country parameter is null (passing a null value =), may i know the reason why please ! Thank you !
public ActionResult Prayer_Schedule(string Country){
}
<img src="~/images/flags/india.jpg" value="india" onclick="choose(this);">
<script type="text/javascript">
function choose(element) {
var Country = element.getAttribute("value");
$.ajax({
type: 'POST',
url: '../Home/Prayer_Schedule',
data: {
Country: Country,
},
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
cache: false,
timeout: 100000,
success: function (response) {
alert('ajax success: ' + response);
//location.href = "/thankyou.html";
}
});
You have to use jQuery.param for post
data: jQuery.param({ Country: Country}),
Or use $.post
$.post('../Home/Prayer_Schedule', { Country: Country },
You have set contentType: 'application/json; charset=utf-8' so you need to send json object or you can simply remove this to get value in controller.
$.ajax({
type: 'POST',
url: '../Home/Prayer_Schedule',
data: {
Country: Country,
},
dataType: 'json',
async: false,
cache: false,
timeout: 100000,
success: function (response) {
alert('ajax success: ' + response);
//location.href = "/thankyou.html";
}
});
Also if you have not decorated your method with HttpPost you will need this too.
[HttpPost]
public ActionResult Prayer_Schedule(string Country){
}
It may be your javascript on the getAttribute() function. You are using value, which isn't a valid attribute for an img tag. Try this instead, using data-* attributes:
<img src="~/images/flags/india.jpg" data-value="india" onclick="choose(this);">
then in your javascript:
element.getAttribute("data-value");
Related
I tried to start new view via parameter, but ajax post method couldn't pass parameter to the controller. Controller parameter always seen Null.
Index.schtml: I triggered in element in html also passing controller and action via Url.Action inside the element. Then run the script:
function getPList(target)
{
var Pdata = JSON.stringify({
'sNo': "88888888"
});
$ajax({
type: "POST",
dataType: 'json',
contentType: 'application/json',
url: target,
data: Pdata,
success: function (data) {
console.log("Response Data ↓");
console.log(data);
}
});
}
Controller:
public ActionResult PListIndex(String sNo)
{
return View(sNo);
}
How to pass controller parameter ?
Your controller variable is called sNo, but you are passing a variable in js called pNo. They should have the same name.
Also try to pass data like this:
$ajax({
type: "POST",
dataType: 'json',
contentType: 'application/json',
url: target,
data: { sNo: "888888" },
success: function (data) {
console.log("Response Data ↓");
console.log(data);
}
});
I have a web api controller that is called by ajax query from my page. All works fine when the async value is set to true. When is set to false the ajax query does not fires. See below my code
C# web api controller
using System;
using Microsoft.Xrm.Sdk;
using CRM_WebApp.Models;
using System.Web.Http;
using System.Web.Http.Cors;
using Microsoft.Xrm.Sdk.Query;
using CRM_WebApp.Services;
using System.Text.RegularExpressions;
namespace CRM_WebApp.Controllers
{
[EnableCors(origins: "*", headers: "*", methods: "*")]
public class CallBackFormController : ApiController
{
[System.Web.Http.HttpPost]
public System.Web.Http.IHttpActionResult Post([System.Web.Http.FromBody] CallBackFormModel CallBackFormModel)
{
ConnectiontoCrm connectiontoCrm = new ConnectiontoCrm();
connectiontoCrm.GetConnectiontoCrmCopy();
//Create Lead
Entity lead = new Entity("lead");
lead["firstname"] = CallBackFormModel.FirstName;
return Json(new { result = "ok" });
}
}
}
Below is my ajax query
<script>
$("input[name='crm']").click(function(){
var Data = {FirstName : $("input[name='user_name']").val()};
makeAjaxCall(Data);
});
function makeAjaxCall(Data){
$.ajax({
url: "http://localhost:54360///api/CallBackForm",
type: "POST",
dataType: "json",
async: false,
contentType: 'application/json',
data: JSON.stringify(Data),
success: function(data){
alert("DONESUCCESS");
},
error: function(data){
alert("DONEERROR");
}
});
}
</script>
I'm not sure how can i change my code to get the error
Async:false is not a good practice. Setting async:false means you are making the process synchronous, so the browser will hang on it until it is finished -- it can't move on to your other method. Removing that option will make the call asynchronous (by default, as it should be).
if you still want to go with async:false then read the link-
http://api.jquery.com/jQuery.ajax/
It seems to be working properly, I used Fake Online REST API from github
(function CallTheServer() {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
type: "POST",
dataType: "json",
async: false, /* change it to true or false see the effect of alert('Check me out too'), following the ajax*/
contentType: 'application/json',
data: JSON.stringify({
title: 'foo',
body: 'bar',
userId: 1
}),
success: function(data){
alert("DONESUCCESS " + JSON.stringify(data));
},
error: function(data){
alert("DONEERROR");
}
});
alert('Check me out too');
})()
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
I have a dropdown that has a list of ID's in it. The customer will select one and it will reflect a price total on the page. Im creating an ajax call that will update the total when a different ID is pulled from the Dropdown.
$("#BrandId").on('focus', function () {
// Store the current value on focus and on change
previous = this.value;
}).change(function () {
alert("Previous: " +previous);
sel = this.value;
alert("Selected: " +sel);
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("GetBrandCost", "Shocks")',
data: JSON.stringify({ idp: previous, id: sel }),
dataType: "json",
aysnc: false,
success: function (data1) {
alert(data1);
//ShockTotal = $("#ShockTotal").html();
//ShockTotal = ShockTotal / 1;
////ShockTotal = ShockTotal - data1;
//$("#ShockTotal").html(data1);
}
});
});
The alerts are working perfectly but the ajax isnt passing those ID's into the controller, the controller is just receiving nulls.
public decimal GetBrandCost(string idp, string id)
{
decimal costp = 0;
decimal cost = 0;
if (id == "" || id == null || idp == "" || idp == null)
{
return 0;
}
ShockBrand brandp = db.ShockBrands.Find(idp);
costp = brandp.Cost;
ShockBrand brand = db.ShockBrands.Find(id);
cost = brand.Cost;
cost = cost - costp;
return cost;
}
Since they are null I am hitting my if statement and just returning zero inside the success. Most of the things I read were to add the content type but that didnt seem to help in my case, Im sure it is something little.
From browser console, this
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: JSON.stringify({ idp: 1, id: 2 }),
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns request to http://google.com/?{%22idp%22:1,%22id%22:2}&_=1440696352799, which is incorrect
and without stringify
$.ajax({
cache: false,
type: "get",
contentType: "application/json; charset=utf-8",
url: 'http://google.com',
data: { idp: 1, id: 2 },
dataType: "json",
aysnc: false,
success: function (data1) {
console.log(data1)
}
});
returns http://google.com/?idp=1&id=2&_=1440696381239 (see Network tab)
So don't use JSON.stringify
Why it's gonna work - your asp.net controller action receives simple typed parameters (string, numbers, etc) and jquery is fairly enought smart to determine what are going to send, if it was object inside object it will send it as POST data for POST, and string represenation of object for GET (you have GET request, but for purpose of knowledge, just stick with 2 types of data that can be send, params & data) So when jquery configures url, asp.net understands conventions, and matches request to approciated action
But Don't believe me, check it yourself
chrome dev console is your friend
By removing the
contentType: "application/json; charset=utf-8
and
dataType: "json"
it worked for me. Otherwise, I was always getting value = null in the controller action.
My code for calling ajax with data is now:
$(function () {
$.noConflict();
$.ajax({
type: "POST",
url: "../Case/AjaxMethodForUpdate",
data: {typ: $('#typeID').val()},
success: OnSuccess,
failure: function (response) {
alert(response.d);
},
error: function (response) {
alert(response.d);
}
});
You can just put it like
var dataReq={ idp: previous, id: sel };
data: dataReq
And no need to use dataType and contentType.
I am calling javascript function on #Html.ActionLink clicked event. The Javascript function calls the jquery function in which I have written the $.ajax method for calling the json controller method. But it is not calling the controller method.......
Here is my code:
View
#Html.ActionLink("Submit", "AdminEvaluate", "Application", new { onclick = "Show('" + Model.applicationList.ApplicationId + "','statusList')" })|
Here, ApplicationId is coming from database and statusList is Radio Button group name from where I need to find the selected radio button.
Javascipt and jQuery code
function Show(appId, appStatus) {
$.fn.gotof(appId,appStatus);
}
Getting parameter from view and passing to jQuery function
jQuery function
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/Application/UpdateApplicantStatus',
data: { id: appId , status: selectedItem},
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
Controller Method
public JsonResult UpdateApplicantStatus(int id, string status){
return Json("Correct", JsonRequestBehavior.AllowGet);
}
I have put break point on controller method but it is not coming at a break point.
Thanks in Advance.
May be this sample help you :) let me know
ajax call with type :
$.ajax({
type: "GET",
url: '#Url.Action("UpdateApplicantStatus", "Application")',
contentType: "application/json; charset=utf-8",
data: { id: appId , status: selectedItem },
dataType: "json",
success: function() { alert('Success'); }
});
controller :
public ActionResult UpdateApplicantStatus(int id, string status){
return Json(// blah blah blah ...
}
This should work else let me know
Your ajax call is wrong.
If your controller method signature is
public JsonResult UpdateApplicantStatus(int id, string appStatus)
Then you MUST have parameter names matching with your parameters of your ajax call.
So, instead of
data: { id: appId , status: selectedItem}
Just write
data: { id: appId , appStatus: selectedItem}
If you have any other problem, just post the error(s) you should have in your browser's console.
Maybe parameter names of controller function and ajax calling function should match.
you can try this
data: { id: appId , appStatus: selectedItem},
Do that way actually 3 mistakes 1 was notify by #Mr Code the type is missing 2nd your parameters not match as your function takes one you send the data in wrong format..
$(document).ready(function () {
$.fn.gotof = function (appId, appStatus) {
var selectedItem = $("input[name='" + appStatus + "']:checked").val();
$.ajax({
url: '/ApplicationController/UpdateApplicantStatus',
data:"{'id':'" + appId + "', 'appStatus': '" + selectedItem+ "'}",//here you format is wrong i correct it
traditional: true,
dataType: "json",
contentType: "application/json",
success: function (data) {
alert(data);
}
});
});
sat on this for hours:
When using ajax - json in a js.script file:
the url is written with its real path e.g. - url: '/contoller/Action',
$.ajax({
url: '/NextPage/GetSpDropDown',
data: {'segInputVal': segInputVal},
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;.....
If the script is written in your HTML page then you must use
#(Url.Action(Action,controller))
$.ajax({
url: "#(Url.Action("GetSpDropDown", "NextPage"))",
data: { 'segInputVal': segInputVal },
cache: false,
type: "GET",
dataType: "json",
success: function (result) {
if (result.Success) {
var resultArray = result.Result;....
And dont forget not to include the word controller in your controller name.
I have had SO MUCH help from stackoverflow- hope to pay a little back
Im having trouble trying to post data correctly using jQuery/AJAX
I have the following...
<script type="text/javascript">
function notifyPPAComplete() {
$.ajax(
{
type: "POST",
url: "PsychometricTest.aspx/UpdateDB",
data: {'3'},
dataType: json,
success: success,
contentType: application/json
});
}
$.post('PsychometricTest.aspx/UpdateDB', function(data) {
alert ('success');
});
</script>
I dont seem to receive my alert after the post neither, can anybody see an obvious problem?
data: {'3'}
That's an invalid javascript literal. You may try like this:
data: JSON.stringify({ model: { foo: '3' } })
Notice the usage of the JSON.stringify method which serializes a javascript literal into a JSON string. It's natively built into modern browsers. And if you need to support legacy browsers you vould include the json2.js script.
Also contentType: application/json is pretty invalid javascript. Should be:
contentType: 'application/json'
Also: dataType: json is invalid. Should be dataType: 'json'.
So at the end of the day:
<script type="text/javascript">
function notifyPPAComplete() {
$.ajax({
type: "POST",
url: "PsychometricTest.aspx/UpdateDB",
data: JSON.stringify({ model: { foo: '3' } }),
dataType: 'json',
success: function(result) {
},
contentType: 'application/json'
});
}
</script>
would successfully post to:
[WebMethod]
public static void UpdateDB(MyModel model)
{
...
}
where MyModel:
public class MyModel
{
public string Foo { get; set; }
}
<script type="text/javascript">
function notifyPPAComplete() {
$.ajax(
{
type: "POST",
url: PsychometricTest.aspx/UpdateDB,
data: {'3'},
dataType: json,
success: function(success){a = success},<-- here use the function()
contentType: application/json
});
}
$.post('PsychometricTest.aspx/UpdateDB', function(data) {
alert (data); <-- here use the variable not the literal string
});
</script>
and by the way you have $.post and $.ajax ??? is this a homework ?
In your snippet notifyPPAComplete() never gets called and $.post('PsychometricTest.aspx/UpdateDB doesn't post any data.
Also try using Firebug in Firefox for better AJAX debugging.
It should be:
$.post('PsychometricTest.aspx/UpdateDB', { name: "John", time: "2pm" }, function(data) {
alert ('success');
});
where { name: "John", time: "2pm" } is the data you want to post.