I'm working with the wenzhixin bootstrap-table (Because I'm being made to use it).
I have a bunch of search fields so on Post, I package up all of the fields nice and neat to send back to the server.
But As you can see all of the fields in pageParam are null but PrefixNameID should be 1. Please note that pageNumber, pageSize, and sortOrder are all correct and not null.
Is there something glaringly obvious that I'm doing wrong here?
Edit: Ajax call - this is the authors code
request = $.extend({}, calculateObjectValue(null, this.options.ajaxOptions), {
type: this.options.method,
url: this.options.url,
data: this.options.contentType === 'application/json' && this.options.method === 'post' ?
JSON.stringify(data) : data,
cache: this.options.cache,
contentType: this.options.contentType,
dataType: this.options.dataType,
success: function (res) {
res = calculateObjectValue(that.options, that.options.responseHandler, [res], res);
that.load(res);
that.trigger('load-success', res);
},
error: function (res) {
that.trigger('load-error', res.status);
},
complete: function () {
if (!silent) {
that.$loading.hide();
}
}
});
Edit 2:
JSON.stringify(data): "{"pageSize":10,"pageNumber":1,"sortOrder":"asc","pageParam":{"ID":null,"PrefixNameID":null,"FirstName":null,"MiddleName":null,"LastName":null,"SuffixName":null,"Address1":null,"Address2":null,"City":null,"StateID":null,"Zipcode":null,"EmployeeTypeID":null,"NPI":null}}"
Holy Cow, It's null!
Related
I'm trying to send form data from a NativeScript app to a TYPO3-Webservice.
This is the JavaScript I'm using:
httpModule.request({
url: "https://my.domain.tld/webservice?action=login",
method: "POST",
headers: { "Content-Type": "application/json" },
content: JSON.stringify({
username:username,
password:password
})
}).then((response) => {
console.log("got response");
console.log(response.content);
//result = response.content.toJSON();
callback(response.content.toJSON());
}, (e) => {
console.log("error");
console.log(e);
});
But I can't read this data in the controller. Even with this:
$rest_json = file_get_contents("php://input");
$postvars = json_decode($rest_json, true);
$postvars is empty. $_POST is empty, too (which is - according to some docs - because the data is sent as JSON and thus the $_POST-Array isn't populated.
Whatever I do, whatever I try, I can't get those variables into my controller.
I tried it with fetch as well as with formData instead of JSON.stringify, same result.
I might have to add, that when I add the PHP-part in the index.php of TYPO3, $postvars is being populated. So I guess something goes missing, until the controller is called.
Any ideas?
the nativescript part seems ok, your problem must be corrected in the server side.
i use similare call and its works
// send POST request
httpModule.request({
method: "POST",
url: appSettings.getString("SERVER") + '/product/list',
content: JSON.stringify(data),
headers: {"Content-Type": "application/json"},
timeout: 5000,
}).then(response => { // handle replay
const responseAsJson = response.content.toJSON();
console.log('dispatchAsync\n\tresponse:', responseAsJson);
}, reason => {
console.error(`[ERROR] httpModule, msg: ${reason.message}`);
});
https://github.com/simpleblog-project/Simple-Blog/issues/1
$.ajax({
method: "POST",
url: "http://localhost:5000/auth/login",
data: JSON.stringify({
"name" : id,
"password" : password
}),
contentType: 'application/json'
})
.done(function(msg) {
if (msg.access_token) {
createCookie(msg.access_token);
window.location.href = './Main.html';
}
else {
if(msg.message)
{
console.log(msg.message);
alert(msg.message);
}
}
});
this
else{
if(msg.message)
{
console.log(msg.message);
alert(msg.message);
}
}
that is not working.
log was jquery-3.3.1.min.js:2 POST http://localhost:5000/auth/login 400 (BAD REQUEST)
this problem is related by app.py this part ▼
#app.route('/auth/login', methods=['POST'])
def login():
data = request.json
name = data['name']
password = data['password']
user = User.query.filter_by(name=name).first()
if user is None or not User.verify_password(user, password):
return {"message": "invalid username or password"}, 400
return {
'access_token': create_access_token(user.id, expires_delta=access_token_exdelta),
'refresh_token': create_refresh_token(user.id, expires_delta=refresh_otken_exdelta)
}
Open the browser to your page and put a breakpoint in the browser on the code, you can click on F12 to open the developer window click on console and navigate to the line. click on the line to add a breakpoint.(red bullet) For ex.
The if statement would be a nice spot to put a breakpoint on. (javascript side) when in a breakpoint ( you see a blue line / redline) hovering on that spot when you hit it, and you can see which variables you have. and in console you can type "msg" and it would show you the current state of the msg object.
also might want to add a error part to the ajax call, just to check if the ajax call itself went ok.
$.ajax({
method: "POST",
url: "http://localhost:5000/auth/login",
data: JSON.stringify({
"name" : id,
"password" : password
}),
contentType: 'application/json',
success: function (data, status, xhr) {
console.log("Succes!" + data);
},
error: function (xhr) {
console.log("Error happened" +xhr.status);
}
});
Look at the documentation how the ajax call works:
https://api.jquery.com/jQuery.ajax/
and check if you get the object "msg" back from the server.
Good luck :).
I wrote a JQuery script to do a user login POST (tried to do what I have done with C# in the additional information section, see below).
After firing a POST with the JQuery code from my html page, I found the following problems:
1 - I debugged into the server side code, and I know that the POST is received by the server (in ValidateClientAuthentication() function, but not in GrantResourceOwnerCredentials() function).
2 - Also, on the server side, I could not find any sign of the username and password, that should have been posted with postdata. Whereas, with the user-side C# code, when I debugged into the server-side C# code, I could see those values in the context variable. I think, this is the whole source of problems.
3 - The JQuery code calls function getFail().
? - I would like to know, what is this JQuery code doing differently than the C# user side code below, and how do I fix it, so they do the same job?
(My guess: is that JSON.stringify and FormURLEncodedContent do something different)
JQuery/Javascript code:
function logIn() {
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
success: getSuccess,
error: getFail
});
} catch (e) {
alert('Error in logIn');
alert(e);
}
function getSuccess(data, textStatus, jqXHR) {
alert('getSuccess in logIn');
alert(data.Response);
};
function getFail(jqXHR, textStatus, errorThrown) {
alert('getFail in logIn');
alert(jqXHR.status); // prints 0
alert(textStatus); // prints error
alert(errorThrown); // prints empty
};
};
Server-side handling POST (C#):
public override async Task ValidateClientAuthentication(
OAuthValidateClientAuthenticationContext context)
{
// after this line, GrantResourceOwnerCredentials should be called, but it is not.
await Task.FromResult(context.Validated());
}
public override async Task GrantResourceOwnerCredentials(
OAuthGrantResourceOwnerCredentialsContext context)
{
var manager = context.OwinContext.GetUserManager<ApplicationUserManager>();
var user = await manager.FindAsync(context.UserName, context.Password);
if (user == null)
{
context.SetError(
"invalid_grant", "The user name or password is incorrect.");
context.Rejected();
return;
}
// Add claims associated with this user to the ClaimsIdentity object:
var identity = new ClaimsIdentity(context.Options.AuthenticationType);
foreach (var userClaim in user.Claims)
{
identity.AddClaim(new Claim(userClaim.ClaimType, userClaim.ClaimValue));
}
context.Validated(identity);
}
Additional information: In a C# client-side test application for my C# Owin web server, I have the following code to do the POST (works correctly):
User-side POST (C#):
//...
HttpResponseMessage response;
var pairs = new List<KeyValuePair<string, string>>
{
new KeyValuePair<string, string>( "grant_type", "password"),
new KeyValuePair<string, string>( "username", userName ),
new KeyValuePair<string, string> ( "password", password )
};
var content = new FormUrlEncodedContent(pairs);
using (var client = new HttpClient())
{
var tokenEndpoint = new Uri(new Uri(_hostUri), "Token"); //_hostUri = http://localhost:8080/Token
response = await client.PostAsync(tokenEndpoint, content);
}
//...
Unfortunately, dataType controls what jQuery expects the returned data to be, not what data is. To set the content type of the request data (data), you use contentType: "json" instead. (More in the documentation.)
var postdata = JSON.stringify(
{
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
});
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: postdata,
dataType: "json",
contentType: "json", // <=== Added
success: getSuccess,
error: getFail
});
If you weren't trying to send JSON, but instead wanted to send the usual URI-encoded form data, you wouldn't use JSON.stringify at all and would just give the object to jQuery's ajax directly; jQuery will then create the URI-encoded form.
try {
jQuery.ajax({
type: "POST",
url: "http://localhost:8080/Token",
cache: false,
data: {
"username": document.getElementById("username").value,
"password": document.getElementById("password").value
},
dataType: "json",
success: getSuccess,
error: getFail
});
// ...
To add to T.J.'s answer just a bit, another reason that sending JSON to the /token endpoint didn't work is simply that it does not support JSON.
Even if you set $.ajax's contentType option to application/json, like you would to send JSON data to MVC or Web API, /token won't accept that payload. It only supports form URLencoded pairs (e.g. username=dave&password=hunter2). $.ajax does that encoding for you automatically if you pass an object to its data option, like your postdata variable if it hadn't been JSON stringified.
Also, you must remember to include the grant_type=password parameter along with your request (as your PostAsync() code does). The /token endpoint will respond with an "invalid grant type" error otherwise, even if the username and password are actually correct.
You should use jquery's $.param to urlencode the data when sending the form data . AngularJs' $http method currently does not do this.
Like
var loginData = {
grant_type: 'password',
username: $scope.loginForm.email,
password: $scope.loginForm.password
};
$auth.submitLogin($.param(loginData))
.then(function (resp) {
alert("Login Success"); // handle success response
})
.catch(function (resp) {
alert("Login Failed"); // handle error response
});
Since angularjs 1.4 this is pretty trivial with the $httpParamSerializerJQLike:
.controller('myCtrl', function($http, $httpParamSerializerJQLike) {
$http({
method: 'POST',
url: baseUrl,
data: $httpParamSerializerJQLike({
"user":{
"email":"wahxxx#gmail.com",
"password":"123456"
}
}),
headers:
'Content-Type': 'application/x-www-form-urlencoded'
})
})
I've encounted a strange problem with Ko mapping.
I use this piece of code:
var PList = [{ "Region": { "RegionName": "SomeRegion" }, "CDetails": {}, "Category": { "Name": "SomeCategory" }, "PSource": 1, "PDate": "0001-01-01T00:00:00"}];
var PViewModel = ko.mapping.fromJS(search('someSearch', 'True'));
var PViewModel2 = ko.mapping.fromJS(PostList);
function search(queryString, isFirst) {
$.ajax({
type: 'POST',
url: 'url',
data: { 'searchQuery': queryString },
dataType: 'json',
success: function (dt) {
if (isFirst != 'True') {
ko.mapping.fromJS(dt, PostsViewModel);
}
return dt;
}
});
};
Strangely I see 2 outcomes:
When I go to PViewModel (the one populated by ajax) I see it as undefined
When I go to PViewModel2 (the one with static data) I can see the objects as expected
*The static data of PViewModel2 is just a copy of the data returned by the ajax post.
My questions are:
Does anyone know why is this so? And how to fix it?
Furthermore, is the if (isFirst != 'True') clause the right way to init the ko view model?
You are dealing with an asynchronous operation (an Ajax request). These operations do not have return values. Therefore, this can never work:
ko.mapping.fromJS(search('someSearch', 'True'));
That's what the success callback is for. Incoming data can only be handled there.
function search(queryString, targetObservable) {
$.ajax({
type: 'POST',
url: 'url',
data: { 'searchQuery': queryString },
dataType: 'json',
success: function (dt) {
ko.mapping.fromJS(dt, targetObservable);
}
});
};
search('someSearch', PostsViewModel);
I got some problem while posting JSON data into MVC 4 controller.
Below method is working fine in Firefox but unfortunately failed in IE 9
The JavaScript :
var newCustomer = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '#Url.Content("~/CustomerHeader/CreateCustomerHeader")',
cache: false,
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(newCustomer),
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
and this is my controller :
public JsonResult CreateCustomerHeader(CustomerHeader record)
{
try
{
if (!ModelState.IsValid)
{
return Json(new { Result = "ERROR", Message = "Form is not valid! Please correct it and try again." });
}
RepositoryHeader.Update(record);
return Json(new { Result = "OK", Record = record});
}
catch (Exception ex)
{
return Json(new { Result = "ERROR", Message = ex.Message });
}
}
the "data" variable as in public JsonResult CreateCustomerHeader(CustomerHeader **data**) is getting NULL but while using FireFox it holds the correct value.
UPDATE : New method trying using $.post
function CreateNewCustomer(newCustomer) {
$.post("/CustomerHeader/CreateCustomerHeader",
newCustomer,
function (response, status, jqxhr) {
console.log(response.toString())
});
}
Based off the bit that you've shown, this is a simplified variation that may work more consistently, using jQuery.post() (http://api.jquery.com/jQuery.post/):
var data = {
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.post({
'#Url.Action("CreateCustomerHeader", "CustomerHeader")',
data,
function(response, status, jqxhr){
// do something with the response data
}).success(function () {
$("#message").html("Success");
}).error(function () {
$("#message").html("Save failed");
});
$.post() uses $.ajax as it's base, but abstracts some of the details away. For instance, $.post calls are not cached, so you don't need to set the cache state (and setting it is ignored if you do). Using a simple JavaScript object lets jQuery decide how to serialize the POST variables; when using this format, I rarely have issues with the model binder not being able to properly bind to my .NET classes.
response is whatever you send back from the controller; in your case, a JSON object. status is a simple text value like success or error, and jqxhr is a jQuery XMLHttpRequest object, which you could use to get some more information about the request, but I rarely find a need for it.
first of all I would like to apologize #Tieson.T for not providing details on JavaScript section of the view. The problem is actually caused by $('#addCustomerHeaderModal').modal('hide') that occurred just after ajax call.
The full script :
try{ ..
var newCustomer =
{
CustName: $("#CustName").val(),
CustLocalName: $("#CustLocalName").val(),
CustNumber: $("#CustNumber").val(),
CountryID: $("#SelectCountry").val(),
City: $("#City").val()
};
$.ajax({
url: '/CustomerHeader/CreateCustomerHeader',
cache: false,
type: "POST",
dataType: "json",
data: JSON.stringify(newCustomer),
contentType: "application/json; charset=utf-8",
success: function (mydata) {
$("#message").html("Success");
},
error: function () {
$("#message").html("Save failed");
}
});
}
catch(Error) {
console.log(Error.toString());
}
//$('#addCustomerHeaderModal').modal('hide')//THIS is the part that causing controller cannot retrieve the data but happened only with IE!
I have commented $('#addCustomerHeaderModal').modal('hide') and now the value received by controller is no more NULL with IE. Don't know why modal-hide event behave like this with IE9.
Thanks for all the efforts in solving my problem guys :-)