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) { .... }
});
});
Related
I'm sending a POST request to a Razor page handler using jQuery .ajax(). The network tab shows that this data is being sent as expected:
My breakpoints confirm that I'm hitting the handler, though the invitationId is not coming over (or at the very least, not deserializing correctly):
The JavaScript is as follows:
class GenericService {
constructor(controller) {
this.controller = controller;
}
async post(data, handler = "") {
return await $.ajax({
type: "post",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: JSON.stringify(data),
url: `/${this.controller}${handler}`,
contentType: "application/json",
dataType: "json"
});
}
}
(async () => {
const _ajax = new GenericService("Admin/Index");
await _ajax.post({ invitationId: 1 }, "Reset");
})();
I imagine that I'm misunderstanding the implicit deserialization, but examples I've seen elsewhere on the internet seem to indicate that sending a JSON serialized object should be fine.
This is using .NET Core 3.0.
Can anyone explain what might be my issue here?
As expected, I had some wires crossed as it relates to the deserialization.
If I send the data as a plain object without serialization (and remove the corresponding json type declarations from the .ajax() options), the invitationId comes across.
return await $.ajax({
type: "post",
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN", $('input:hidden[name="__RequestVerificationToken"]').val());
},
data: data, //Remove JSON.stringify(...)
url: `/${this.controller}${handler}`
//contentType: "application/json", Remove
//dataType: "json" Remove
});
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 have trouble with a piece of ajax code. This is the error message I get from mod security:
/ajaxController.php?mod=catalog&op=ajaxSeenProducts HTTP/1.1
Access denied with code 400 (phase 2). Operator EQ matched 0 at
REQUEST_HEADERS. [file "/usr/local/apache/conf/modsec2.user.conf"]
[line "12"] [id "960012"] [msg "POST request must have a
Content-Length header"] [severity "WARNING"] [tag
"PROTOCOL_VIOLATION/EVASION"]
There is a module in the web shop I am working on, which shows the last viewed products, and the jquery code I have is this:
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
While searching for the solution, I have found in various places that I need to set the
Content-length
parameter, but all I have found is in this format:
xmlHttp.setRequestHeader("Content-length", params.length);
Is there any way to set the request header in the code format I have provided above? I have already tried something like:
headers: {
"Content-Length": params.length
}
but with no result. Any help would be appreciated.
use code like:
var url = '{HOME}ajaxController.php?';
var data = "mod=catalog&op=ajaxSeenProducts";
$.ajax({
url: url,
data: data,
dataType: "html",
type:'post',
success:function(seenProducts){
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
},
error:function(response){
}
});
you can use the beforeSend function to set the headers
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
beforeSend: function (request)
{
request.setRequestHeader("Authority", authorizationToken);
},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
or other way you can do it like
$('#seen_products_box').ready(function() {
$.ajax({
type: "POST",
headers: {"X-Test-Header": "test-value"},
url: "{HOME}ajaxController.php?mod=catalog&op=ajaxSeenProducts",
success: function(seenProducts) {
$('#seen_products_box').empty();
$('#seen_products_box').append(seenProducts);
}
});
});
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.