mockjax how to test url with parameters - qunit

I am having problem to mock one end point. Mockjax intercept the request when retrieving the params the from the URL. Nevertheless, when I add them into the URL or the data object, the request passes through.
I need to make two occurrences of this call pass. Otherwise, my integration tests are failing.
I am working with global calls. All other calls are working properly minus this one.
/* catches*/
$.mockjax({
url: '*search-by-keyword',
dataType: 'json',
headers: { 'X-CSRF-Token' : tokenId },
contentType: 'application/json',
responseText: mockLiferaySearchResponseSuccess
});
/* passes through*/
$.mockjax(
{ url: '*search-by-keyword',
data: {
page: '0',
perPage: '5',
lang: 'en',
path: 'http://testbanner.ypg.com/portal',
type: 'webcontent',
keyword: 'yellow'
},
dataType: 'json',
headers: { 'X-CSRF-Token' : tokenId },
contentType: 'application/json',
responseText: mockLiferaySearchResponseSuccess
});

Related

SharePoint ajax ValidateUpdateListItem

I would like to post an ajax call to update a list without updating the version. I was told I can make use of the ValidateUpdateListItem() function. However, when I try using it, I have the error: System.ArgumentNullException value cannot be null parameter name: formValues. Here is a code snippet.
url: "path/ValidateUpdateListItem()",
method: "POST",
contentType: "application/json;odata=verbose",
headers: {
"Accept": "application/json; odata=verbose",
"IF-MATCH": request.ETag,
"X-HTTP-Method": "MERGE",
"X-RequestDigest": $('#__REQUESTDIGEST').val()
},
data: JSON.stringify({
"formValues":[
{
'Field1': 'value1'
}
],
'bNewDocumentUpdate': true
}),

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) ajax request

I have an ajax request, and in django view, i have following prints and outputs.
I have the error in this line and i cant figured it out why.
parsed_json = json.loads(request.body)
I trid to decode request body with utf8 but nothing has changed
AJAX CALL:
$("#add_user_button").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/user/',
data:
{
'action': "addUser",
'username': $('#id_username').val(),
'password': $('#id_password').val(),
'groups': $('#id_groups').val()
}
,
contentType: 'application/json; charset=utf-8',
processData: false,
});
}
DJANGO VIEW PRINTS:
print(request.POST.get("username"))
#print(request.encoding) #returns none
print("Request body is :")
print(request.body)
print(type(request.body))
OUTPUTS:
hello
Request body is :
b'username=hello&password=world&csrfmiddlewaretoken=&addUser=Add+User'
<class 'bytes'>
If you analyse your request body you'll notice it is not JSON, to send JSON you have to encode it in your ajax request from your object.
$("#add_user_button").click(function (event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/user/',
data:
JSON.stringify({ // <--here
'action': "addUser",
'username': $('#id_username').val(),
'password': $('#id_password').val(),
'groups': $('#id_groups').val()
})
,
contentType: 'application/json; charset=utf-8'
});
}

ASP.NET Core FromBody is null on AJAX POST but populates in Postman

I'm trying to perform an AJAX post but I keep getting a null FromBody in my .NET controller. I think it has to do with how I'm formatting my AJAX post.
When I attempt to post with AJAX I get a null FromBody.
var data = {
Date: "2016-12-01",
BurnIdx: 23,
BurnStatIdx1: 3,
BurnStatIdx2: 3,
BurnStatIdx3: 3,
BurnSevIdx: 5,
WorkOrder: 32426,
Comment: "Hi"
};
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (result) {
console.log('Data received');
console.log(result);
}
});
});
However, when I attempt a post in Postman it's successful.
Figured out my problem. Needed to use JSON.stringify on my data.
$('#submit').on('click',function () {
$.ajax({
type: 'POST',
url: 'Home/BurnerMapUpdate',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (result) {
console.log('Data received');
console.log(result);
}
});
Not only the JSON.stringify().
If your data don't match with csharp class data it doesn't receive anything.
Like if you define in the class a field with int type, and send it in the json like "1", it happens to receive the whole data as null
I know you are already figured out of this problem. But I faced with the same just right now. My mistake was I used BODY parameter instead DATA in ajax request.
My Invalid ajax:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
body: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
Valid:
function sendRequest(url, method, body, callbackOk, callbackFail) {
$.ajax({
url: url,
data: JSON.stringify(body),
method: method,
contentType: 'application/json; charset=utf-8',
success: callbackOk,
error: callbackFail
})
}

How to get values from data: part in ajax call

$.ajax({
type: "POST",
url: baseUrl + "query?v=21266702",
contentType: "application/json; charset=utf-8",
dataType: "json",
headers: {
"Authorization": "Bearer " + accessToken
},
data: JSON.stringify({ query: text, lang: "en", sessionId: reqIdToken }),
success: function(data) {
xyz
}else{
setResponseForIT(data,"");
}
},
error: function() {
setResponse("Internal Server Error");
}
});
You would assign this stuff to variables before sending the raw data.
You have the data right here :
query: text, lang: "en", sessionId: reqIdToken
you are basically building the JSON on the fly, just process these before by setting them as variables.
Update (for clarification) :
This is creating json for you based on the variables already set etc.
JSON.stringify({ query: text, lang: "en", sessionId: reqIdToken })
This means you have access to 'text' and 'reqIdToken' and hence don't need to look at the 'data' variable that contains the json. Just use reqIdToken if you want to know the sessionId. (e.g. if (reqIdToken == "999") alert();)

Getting data from web service using ajax

I'm trying to get data from a webservice using ajax and POST method.
Ext.Ajax.request({
url: 'http://localhost......',
method:'POST',
success: function(response) { console.log(response.responseText); },
failure: function() { Ext.Msg.alert('Fail'); },
jsonData:{
/*Here I specify my request json*/
}
}
});
The above thing works fine but when i try to mimic the same in EXTJS store it responds with a error
he server responded with a status of 415 (Unsupported Media Type)
EXTJS STORE CODE
Ext.define('IWM.store.JsonTest', {
extend: 'Ext.data.Store',
autoLoad: true,
fields:['Name'],
proxy: {
type: 'ajax',
method : 'POST',
actionMethods: {
create : 'POST',
read : 'POST',
update : 'POST',
destroy: 'POST'
},
jsonData:{
/*JSON */
}
},
url: 'http://localhost......',
success: function(response) { console.log(response.responseText); },
failure:function(){console.log("failed");},
reader: {
type: 'json',
root: 'result',
successProperty: 'success'
}
}
});
First things first, try to change store config as below.
var IWMStore = new Ext.data.JsonStore({
// it seems to me you had forgotten model
model: 'YourDataModel',
autoLoad: true,
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
}
}
});
Example JSON value :
// here, ctgMains is the root value, CUST_ASSORT_SECTION_ID is the idProperty
{"ctgMains":[{"CUST_ASSORT_SECTION_ID":"1","CTG_SECTION":"HORECA"},{"CUST_ASSORT_SECTION_ID":"7","CTG_SECTION":"SCO"},{"CUST_ASSORT_SECTION_ID":"3","CTG_SECTION":"TRADER"}]}
Second Attempt :
Try to add headers property in your proxy definition, like below:
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
},
headers: {
'Content-type': 'application/json',
'Accept': 'application/json'
}
}
Following on from Oğuz Çelikdemir's answer, you may need to define a json writer for your proxy.
proxy: {
type: 'ajax',
url: 'http://your-url-address',
reader: {
type: 'json',
root: 'json-root-value',
idProperty: 'unique-property-in-json-file'
},
writer: {
type: 'json'
}
}
That should set the json mediatype header (assuming that's what your request is expecting).

Resources