Cascading Dropdown - How to load Data? - javascript

I try to make an cascading dropdown, but I have problems with the sending and fetching of the response data.
Backend:
[HttpPost]
public async Task<JsonResult> CascadeDropDowns(string type, int id)
{ .............
return Json(model);
}
Here I get the correct data.
First I tried:
$("#dropdown").change( function () {
var valueId = $(this).val();
var name = $(this).attr("id");
let data = new URLSearchParams();
data.append("type", name);
data.append("id", valueId);
fetch("#Url.Action("CascadeDropDowns", "Home")", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: data
})
.then(response => {
console.log('Success:', response);
return response.json();
})
.then(json => {
console.log('Success:', json );
console.log('data:', json.Projects);
PopulateDropDown("#subdropdown1",json.Projects)
})
.catch(error => {
console.log('Error:', error);
});
});
Here I can send the Request and get a "success" back. However, when I access json.Projects I just get an `undefined. I have tried to change the Content-Type, without success.
Secondly I have used:
$.ajax({
url: "#Url.Action("CascadeDropDowns", "Home")",
data: data,
type: "POST",
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function (data) {
console.log(data);
},
error: function (r) {
console.log(r.responseText);
},
failure: function (r) {
console.log(r.responseText);
}
});
With this I get an Illegal Invocation Error.
What do I have to do that get either of those working? What are their problems?

I try to make an cascading dropdown, but I have problems with the
sending and fetching of the response data.What do I have to do that get either of those working? What are their problems?
Well, let consider the first approach, you are trying to retrieve response like json.Projects but its incorrect because data is not there and you are getting undefined as below:
Solution:
Your response would be in json instead of json.Projects
Complete Demo:
HTML:
<div class="form-group">
<label class="col-md-4 control-label">State</label>
<div class="col-md-6">
<select class="form-control" id="ddlState"></select>
<br />
</div>
</div>
Javascript:
var ddlState = $('#ddlState');
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Please wait ...'));
let data = new URLSearchParams();
data.append("type", "INDIA");
data.append("id", 101);
fetch("http://localhost:5094/ReactPost/CascadeDropDowns", {
method: "POST",
credentials: "include",
headers: {
"Content-Type": "application/x-www-form-urlencoded;charset=UTF-8"
},
body: data
})
.then(response => {
return response.json();
})
.then(result => {
console.log(result);
var ddlState = $('#ddlState');
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Select State'));
$.each(result, function (index, states) {
ddlState.append($("<option></option>").val(states.cityId).html(states.cityName));
});
})
Second approach:
In ajax request you are passing object as object fahsion like data: data whereas, your controller expecting as parameter consequently, you are getting following error:
Solution:
You should pass your data within your ajax request like this way data: { type: "YourTypeValue", id:101 }, instead of data: data,
Complete Sample:
$.ajax({
url: 'http://localhost:5094/ReactPost/CascadeDropDowns',
type: 'POST',
data: { type: "YourValue", id:101 },
success: function (response) {
ddlState.empty();
ddlState.append($("<option></option>").val('').html('Select State'));
$.each(response, function (i, states) {
ddlState.append($("<option></option>").val(states.cityId).html(states.cityName));
});
},
error: function (response) {
alert('Error!');
}
});
Note: I have ommited contentType because, by default contentType is "application/x-www-form-urlencoded;charset=UTF-8" if we don't define.
Output:

Related

how to pass data to ajax for an express api call

I'm developing a website with express and ejs. I got into a trouble where i need to call an api via ajax. The problem is on a button onclick i'm passing two values to ajax data. but it gives error ,i tried a lot of ways and i'm messed up. i'm a newbie , find my code below.
const parsedData = JSON.parse(localStorage.getItem('myData'));
const container = document.getElementById('s1');
parsedData.data.rows.forEach((result, idx) => {
var a = result.master_id;
var b = result.session_name;
console.log(a,b,"a","b")
var userData = {"pid":a,"session" :b};
console.log(userData,"userData");
sessionStorage.setItem("user", JSON.stringify(userData));
console.log(userData,"data for api");
const card = document.createElement('div');
card.classList = 'card';
const content = `
<div class="row">
<div class="card-body" onclick="graphApi()">
</div>
</div>
`;
container.innerHTML += content;
});
function graphApi(){
var apiValue =JSON.parse( sessionStorage.getItem("user"));
console.log(apiValue, "value from card");
$.ajax({
type: "POST",
data: apiValue,
dataType:"json",
url: "http://localhost:5000/graphFromcsv",
success: function(data) {
console.log(data,"graph api");
}
error: function(err){
alert("graph api failed to load");
console.log(err);
},
});
i'm always getting this pid in api value undefined and 400 badrequest . but if i use raw data like,
{
"pid":"WE6",
"session":"W.csv"
}
instead of apiValue my ajax is success and i'm gettig the data. i'm using this data to plot a multiple line graph. Any help is appreciated.
You need to correct data key and their value(value must be string in case of json data) and also add contentType key like
$.ajax({
type: "POST",
data: sessionStorage.getItem("user") || '{}',
dataType: "json",
contentType: "application/json",
url: "http://localhost:5000/graphFromcsv",
success: function (data) {
console.log(data, "graph api");
},
error: function (err) {
alert("graph api failed to load");
console.log(err);
},
});
Note: In backend(ExpressJS), make sure you are using correct body-parser middleware like app.use(express.json());
Let assume your apiValue contain {"pid":"WE6", "session":"W.csv" } then body: { apiValue } will be equal to:
body: {
apiValue: {
"pid":"WE6",
"session":"W.csv"
}
}
But if you use the link to the object like body: apiValue (without brackets) js will build it like:
body: {
"pid":"WE6",
"session":"W.csv"
}

how to test submitted data in Cypres

I need to check if some values in submitted data have expected values. To do this i tried to access and sent data by XMLHttpRequest in Cypress during the request run.
describe('test submitted data', () => {
it('some data is changed', () => {
submitBtn().click({force: true});
//in this case Cypress doesnt get into this debugger point
cy.server({
onAnyRequesty: (props) => {
debugger
}
});
//in this one Cypress go into and stops at the point but
//the data variable doesnt contrain submitedData
cy.route('PUT', `${APP_CONTEXT}/api/model/${modelId}`, (data) => {
debugger;
});
});
});
Data is sent by the way below:
$.ajax({
url: url,
method: "PUT",
data: "{"inputData":"123"}",
contentType: "application/json",
success: () => {},
error: () => {}
});
What am i doing wrong? Thanks
One more thing: and how to make Cypress check if the data condition is met? for example:
it('some data is changed', () => {
submitBtn().click({force: true});
cy.route('PUT', `${APP_CONTEXT}/api/model/${modelId}`, (data) => {
const parsedData = JSON.parse(data);
// the test is passed if the value is equal
expect(parsedData.inputData).to.eq('123');
});
UPDATE
i tried proposed answer from #richard-matsen and different callBack keys but neither were working:
onResponse
onAnyResponse
onRequest
onAnyRequest
But callback function in neither of them didnt run
it("Signature removed from the field and empty value submitted", () => {
cy.server();
submitBtn().click();
//here i check the put url as an url submitting to
cy.log(`${BASE_URL}/api/data/${formId}/${modelId}`);
cy.route({
method: "PUT",
url: `${BASE_URL}/api/data/${formId}/${modelId}`,
onAnyRequest: (data) => {
const signValue = JSON.parse(data)[`${modelId}|sign_2||`];
debugger;
cy.log(signValue);
expect(signValue).to.eq(null)
}
})
})
UPDATE UPDATE
#richard-matsen ,thanks, you were right, I did an error in method options, but I decided to simplify the route options but still the debugger cannot get in neither handler:
it("Submitted data", () => {
cy.server({ whitelist: (xhr) => console.log('custome log: server', xhr) });
submitBtn().click({force: true});
cy.route({
url: /.+/,
onResponse: (data) => {
debugger;
cy.log('onResponse signature value - ' + data);
},
onAnyResponse: (data) => {
debugger;
cy.log('onAnyResponse signature value - ' + data);
},
onRequest: (data) => {
debugger;
cy.log('onRequest signature value - ' + data);
},
onAnyRequest: (data) => {
debugger;
cy.log('onAnyRequest signature value - ' + data);
}
})
})
Also tried to click submission btn right after cy.route, but that wasn't working as well.
I appreciate your help!
The patterns for using cy.route() are
cy.route(url)
cy.route(url, response)
cy.route(method, url)
cy.route(method, url, response)
cy.route(callbackFn)
cy.route(options)
Looks like your command is interpreted as #4, but response is the value used to stub. Never seen it with a function, so is best guess.
To be sure, use the pattern with options and put function in onResponse
cy.route({
method: 'PUT',
url: `${APP_CONTEXT}/api/model/${modelId}`,
onResponse: (data) => {
expect(parsedData.inputData).to.eq('123');
}
})
Also onAnyRequesty: (props) => change to onAnyRequest: (props) =>.
In your latest code,
onAnyRequest: (data) => {,
data is already parsed so JSON.parse(data) causes an error.
In my test, I get a weird error about cross-origin when trying to re-parse within onResponse() (Expecting a message like 'Unexpected token o in JSON at position 1').
In any case, put the debugger up one line to avoid other code problems.
If cy.route() is not matching the url, you can see all calls with (temporary)
cy.server({ whitelist: (xhr) => console.log('server', xhr) }).
Maybe APP_CONTEXT !== BASE_URL?
Submit can be a native event which won't be captured by Cypress.
I think you can test if this is so, see Submit a POST form in Cypress and navigate to the resulting page.
If you do the following instead of submitBtn().click({force: true}) and the cy.route() does pick it up, then you have a native event.
cy.visit({
url: `${BASE_URL}/api/data/${formId}/${modelId}`,
method: "PUT",
form: true,
body: {
inputData :"123"
}
});

Array empty after posting data from angular controler

I am using codeigniter and angular for my app. When I post the data from angular controller to CI controller, array seems to be empty (result of print_r is "array()") .Can someone tell me why?
Angular Part:
$scope.posaljiKontroleru = function () {
$scope.prosek = {kalorije: 0.0, proteini: 0.0, uh: 0.0, masti: 0.0};
$http({
method: 'POST',
url: 'http://localhost/psi/Pravljenjejela/dodajBazi',
data: $scope.prosek
}).then(function (res) {
$window.location.href = "http://localhost/psi/Pravljenjejela/dodajBazi";
}, function (err) {
console.log(err);
});
});
}
CI part
public function dodajBazi() {
$info = $this->input->post();
print_r($info);
}
You need to use default content-type header
Try this:
$http({
method: 'POST',
url: 'http://localhost/psi/Pravljenjejela/dodajBazi',
data: $scope.prosek,
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
}).then(function (res) {
$window.location.href = "http://localhost/psi/Pravljenjejela/dodajBazi";
}, function (err) {
console.log(err);
});

How can I get post parameters on ajax request in Symfony 3

I have an ajax request working fine. My problem is I do not really know how to use correctly my controller to get the datas in the format I would like.
I would like to use this kind of method:
$request->request->get('pseudo'); // will return "bob"
Here is my controller code:
public function mainPlayAction(Request $request)
{
if ($request->isXmlHttpRequest())
{
$allContent = $request->getContent(); // will return a string with this format "selectedBalls=34&selectedStars=11"
$selectedBalls = $request->request->get('selectedBalls'); // will return null
$selectedstars= $request->request->get('selectedStars'); // will return null
$all = $request->request->all(); // will return Array[0]
$response = [
'allContent' => $allContent,
'selectedballs' => $selectedBalls,
'selectedStars' => $selectedStars,
'all' => $all,
'success' => true,
"status" => 100
];
return $this->json($response);
}
}
Here is my ajax code
$.ajax({
url: url,
dataType: "json",
contentType: "application/json; charset=utf-8",
type: "POST",
data: {
'selectedballs': selectedBalls,
'selectedStars': selectedStars,
'countGames': countGames
},
success: function (response) {
window.console.log(response);
},
})
You simply need to call ->get() on Request object to get the data passwed along with AJAX Request.
Like this,
$selectedballs=$request->get('selectedballs');
$selectedStars=$request->get('selectedStars');
$countGames=$request->get('countGames');
I found a good answer.
I deleted this line of code from my ajax request
contentType: "application/json; charset=utf-8"
And now I can retrieve my datas using
$request->get('selectedBalls');

How to prevent sending duplicate request with a single click in AngularJs

I have an angularJs application that has an api call with a click on a link . but everytime i click on the link it sends 2 same api calls to the server. Why this occurs and how can i resolve this.
my service is like: SomethingService
function getData() {
return apiSettings.getApiInformation().then(function (response) {
var url = response.data.Url + "/odata/Something?$expand=Something";
var data = {
url: url,
type: "GET",
token: response.data.Token,
data: {},
async: true,
cache: false,
headers: {
"accept": "application/json; charset=utf-8",
'Authorization': 'Bearer ' + response.data.Token
},
dataType: "json",
success: {},
error: {},
complete: {},
fail:{}
};
return $http(data);
});
}
Api Settings :
angular.module('myApp.services')
.factory('apiSettings', apiSettings);
apiSettings.$inject = ['$http'];
function apiSettings($http) {
return {
getApiInformation: function () {
return $http.get(baseUrl+ '/api/GetApiInformation', {cache: true});
}
}
}
SomethingController:
var vm = this;
function getSlots(filterCriteria, selectedValue) {
somethingService.getData().then(function (response) {
if (response && response.value.length > 0) {
vm.someData = response.value;
}
});
View:
clicking on this link calls getSlots that sends duplicate request
<a ui-sref="something" class="action-icons" id="slotNav"><i class="fa fa-square-o fa-fw"></i>
something
</a>
this view displays data
<div ng-repeat="data in vm.someData">
<p> {{data.Name}}</p>
</div>
Issue: For a single trigger browser sends duplicate requests like the following. the first call doesn't have callback but the second call has callback:
someuls?$expand=something&_=1432722651197
someuls?$expand=something&_=1432722651197
I had a similar problem which I fixed by checking this answer. I had declared "ng-controller" in HTML as well as routed to it using routeProvider. Fixed the issue by removing the "ng-controller" property in HTML.
Hope this helps.

Categories

Resources