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.
Related
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 an older JAX-RS application that I'm running on IBM Liberty profile 16.0.0.4 with the jaxrs-2.0 feature. I'm getting some weird behavior that I can't explain, and need some help.
JAX-RS service code:
#Path("/loadData")
#POST
#Produces("text/plain")
public String loadData(#Context HttpServletRequest request) {
String id = request.getParameter("id");
String email = request.getParameter("email");
// add'l request processing code
}
JQuery code:
$(document).ready(function() {
var reqData = {id:"123456", email:"user#email.com"};
$.ajax({
type: "POST",
cache: false,
url: "http://localhost:9080/jaxrs/loadData",
data: reqData,
contentType: "application/json",
dataType: "json",
timeout: "30",
beforeSend: function() { ... },
success: function(data) { .... },
complete: function(data) { .... }
});
});
JQuery (in IE) Results:
request.getParameter("id") or ("email") = null;
request.toString() = org.apache.cxf.jaxrs.impl.HttpServletRequestFilter#f272c8dc
IOUtils.toString(request.getInputStream) = "id=123456&email=user1%40email.com"
SoapUI Results:
request.getParameter("id") = 123456 and ("email") = user#email.com;
request.toString() = org.apache.cxf.jaxrs.impl.HttpServletRequestFilter#de62638a
IOUtils.toString(request.getInputStream) = ""
I compared the RAW HTTP request in SoapUI and in IE's console, they both appears to be the same, as far as I can tell. So that's really got me confused, both JQuery and SoapUI are performing POST, but seems in IE's case the query stream is not being parsed into parameters, rather just maintained as a string. I've tried to mess around with the contentType and request declaration with no effects. I was originally using JQuery 1.7.1, but I tried on 3.1.1 with no effects. Has anyone seen this before. Any help or insights would be really great, thanks!
Try using "JSON.strigify" for params
$(document).ready(function() {
var reqData = {id:"123456", email:"user#email.com"};
$.ajax({
type: "POST",
cache: false,
url: "http://localhost:9080/jaxrs/loadData",
data: JSON.stringify(reqData),
contentType: "application/json",
dataType: "json",
timeout: "30",
beforeSend: function() { ... },
success: function(data) { .... },
complete: function(data) { .... }
});
});
The script is as below:
<script type="text/javascript">
var myEl = document.getElementById('markAsRead');
myEl.addEventListener('click', function() {
var bloop = $('#markAsRead').val();
alert(bloop);
$.ajax({
type: 'POST',
url: '/url/to/post',
data: {"bloop": bloop},
success: function(data) { alert('data: ' + data); },
contentType: "application/json",
dataType: 'json'
});
}, false);
</script>
I am posting this to a URL that wants to take the value of bloop and do something with it, but I am having trouble figuring out how to retrieve it to do so. Are there any obvious errors here? How can I access the value of bloop?
Something like --- For MVC
public IActionResult Post (string blob)
{
-- here you can get the value
return JsonResult ("Success");
}
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");
I'm sending from view using jQuery to MVC post action
function DoSomething(passedId) {
$.ajax({
method: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
//
});
}
And inside MyController
[HttpPost]
public ActionResult SomeAction(int id)
{
...
}
In Firebug console I'm getting 404 error.
You didn't said which version of jquery you are using. Please check jquery version and in case that this version is < 1.9.0 you should instead of
method: "POST"
use
type: "POST"
this is an alias for method, and according to jquery official documentation you should use type if you're using versions of jQuery prior to 1.9.0.
function DoSomething(passedId) {
$.ajax({
type: "POST",
dataType: 'text',
url: '/MyController/SomeAction/',
data: { id: passedId}
}).done(function (data) {
...
});
}
Tested above code and it works (each request enter inside mvc controller http post SomeAction action).
In the RFC 2616 the code 404 indicates that the server has not found anything matching the Request-URI.
So you need to look at your URL parameter.
Try the MVC conventional call using :
url: '#Url.Action("SomeAction", "MyController")',
To resolve the 404 issue:
There are a few options to resolve this. You controller/action cannot be find the way it is describe.
-If you are in a view that is in the controller for which the action your are trying to call is located, then:
url: 'SomeAction',
-If you are trying to call an action from another controller, OtherController, for example, then:
url: 'Other/SomeAction',
-To add to another answer, if you are calling your ajax inside the view (and NOT in a javascript file) then you can also use (for a controller called SomeController):
url: '#Url.Action("SomeAction", "Some")',
Additional Items Of Note:
You do not specify a content type for json (contentType indicates what you are sending):
contentType: "application/json; charset=utf-8",
I can't tell, based on your action if you are expecting 'text' or something else. However, unless expecting 'json', I would remove the data part.
You need to stringify your data
JSON.stringify(data: { id: passedId}),
In the end, I would expect it to look something like:
function DoSomething(passedId) {
var url = "SomeAction"; //if action is in OtherController then: "Other/SomeAction"
$.ajax({
method: "POST",
url: url,
data: JSON.stringify({ id: passedId}),
contentType: "application/json; charset=utf-8"
}).done(function (data) {
//
});
}
The slash at the beginning of this designates an absolute path, not a relative one.
/MyController/SomeAction/
You should include a URL or relative path.. maybe
'MyController/SomeAction/ajax.php'
or the full URL
'http://example.com/myajaxcontroller/someaction/ajax.php'
or stolen from the other guys answer
url: '#Url.Action("SomeAction", "MyController")',
To address others on here, I don't think the datatype is the
problem... OP says "I'm getting 404 error."
contentType is the type of data you're sending, so
application/json; charset=utf-8 is a common one, as is
application/x-www-form-urlencoded; charset=UTF-8, which is the
default.
dataType is what you're expecting back from the server: json, html,
text, etc. jQuery will use this to figure out how to populate the success function's parameter.
Write the code this way:
function DoSomething(passedId) {
$.ajax({
url: 'yourController/SomeAction',
type: 'POST',
data: { id: passedId},
dataType: 'json',
error: function (ex) {alert(ex.responseText)},
success: function (data)
{
if (data.Results != null) {
//use the return values
});
}
}
});
}
and the controller
public JsonResult SomeAction(int id)
{
try
{
return Json(new { Results = "Text To return or send some object or an list, etc"}, JsonRequestBehavior.AllowGet);
}
catch (Exception)
{
throw;
}
}
Finally, check that the controller has its respective view. :)
and and the library of "jQuery" updated.
just in case.
use the following ajax call
var datum = { id: passedId };
$.ajax({
url: url, // your url
type: 'POST',
data: JSON.stringify(datum),
contentType: 'application/json; charset=utf-8',
beforeSend: function () {
},
complete: function () {
},
success: function (user, status, XHR) {
},
error: function (req, status, error) {
}
});
UpDated
public ActionResult SomeAction(int id){} should accept string parameter instead of int