I'm trying to create an object to be sent in an AJAX request in the format I need.
In the code I'm able to get the name attribute for each input element and its value, but I need to create an object in the below format. How can I create that?
{
"userrole":"",
"userAttributes":{
"username":"alks",
"useraddress":"ajdaa",
"usercity":"lajsdk"
}
}
<div class="data-fields-container">
<div class="input-type" data-attr-name="userrole">
<input type="text" name="userrole">
</div>
<div class="input-type" data-attr-name="username">
<input type="text" name="username">
</div>
<div class="input-type" data-attr-name="useraddress">
<input type="text" name="useraddress">
</div>
<div class="input-type" data-attr-name="usercity">
<input type="text" name="usercity">
</div>
</div>
<button id="submit_data">Submit</button>
$(document).ready(function() {
$('#submit_data').on('click', function() {
$('.data-fields-container > .input-type').each(function() {
dataobj = {};
var attrkey = $(this).attr('data-attr-name');
var attrval = $(this).find('input').val();
})
$.ajax(function() {
url: "https://map.net/api/v44",
data: dataobj,
type: 'POST',
dataType: 'Json',
success: function(data) {
console.log('successful')
},
error: function(request, error) {
console.log('failed')
}
})
})
})
You could map the serializeArray() result and construct your object like:
$(document).ready(function() {
$('#submit_data').on('click', function() {
var dataobj = {userrole: $('[name="userrole"]').val()};
var attr = $('.data-fields-container input:not([name="userrole"])').serializeArray().map(function(o) {
this[o.name] = o.value;
return this;
}.bind({}))[0];
dataobj['userAttributes'] = attr;
console.log(dataobj);
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="data-fields-container">
<div class="input-type" data-attr-name="userrole">
<input type="text" name="userrole">
</div>
<div class="input-type" data-attr-name="username">
<input type="text" name="username">
</div>
<div class="input-type" data-attr-name="useraddress">
<input type="text" name="useraddress">
</div>
<div class="input-type" data-attr-name="usercity">
<input type="text" name="usercity">
</div>
</div>
<button id="submit_data">Submit</button>
dataObj = {
"userrole":document.querySelector('div.input-type input[name="userrole"]').value,
"userAttributes":{
"username":document.querySelector('div.input-type input[name="username"]').value,
"useraddress":document.querySelector('div.input-type input[name="useraddress"]').value,
"usercity":document.querySelector('div.input-type input[name="usercity"]').value
}
}
You don't need to iterate through the inputs since your JSON format is static.
Related
I want to iterate over the items array that the google books API provide and print the result inside a div but somehow I am not able to do so. This is what I've written till now.
<body>
<div class="main-body">
<form id="form">
<div class="form-group">
<label for="usr">Enter Book Name</label>
<input type="search" class="form-control" id="search-text">
</div>
<div class="search-button">
<button onclick="function2();" type="button" id="search-button" class="btn btn-default">Search</button>
</div>
</form>
<div id="result">
<!--something seems wrong here-->
<h3 class="title"></h3>
<h4 class="author"></h4>
<img src="" alt="" class="thumbnail">
</div>
</div>
<script>
function function2(){
var result = document.getElementById('search-text').value;
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q="+result,
type: 'GET',
dataType: 'json', // added data type
success: handleResponse
});
function handleResponse(res){
$.each(res.items,function(i,item){
var title = item.volumeInfo.title,
author = item.volumeInfo.authors[0],
thumb = item.volumeInfo.imageLinks.thumbnail;
<!--want to iterate over each element in items array and print it-->
$('.title').text(title);
$('.author').text(author);
$('.thumbnail').attr('src',thumb);
})
}
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</body>
Your current code replaces the previous data with the current data on each iteration.
The easiest way to do what you want should be to build new elements and append them to your "result" div as shown below.
I would also recommend validating the data. Some queries I tested with returned books with no covers or authors.
function function2() {
var result = document.getElementById('search-text').value;
$.ajax({
url: "https://www.googleapis.com/books/v1/volumes?q=" + result,
type: 'GET',
dataType: 'json', // added data type
success: handleResponse
});
function handleResponse(res) {
$.each(res.items, function(i, item) {
var title = item.volumeInfo.title,
author = item.volumeInfo.authors[0],
thumb = item.volumeInfo.imageLinks.thumbnail;
var elTitle = $('<h3 class="title"></h3>').html(title),
elAuthor = $('<h4 class="author"></h4>').html(author),
elThumb = $('<img src="" alt="" class="thumbnail">').attr('src', thumb);
$('#result').append(elTitle, elAuthor, elThumb);
})
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<div class="main-body">
<form id="form">
<div class="form-group">
<label for="usr">Enter Book Name</label>
<input type="search" class="form-control" id="search-text">
</div>
<div class="search-button">
<button onclick="function2();" type="button" id="search-button" class="btn btn-default">Search</button>
</div>
</form>
<div id="result">
</div>
</div>
</body>
I try to submit form via ajax, below is the form.
<form class="form-vertical" method="POST" id="request-form" action="/post_handler?request=add_data" enctype="multipart/form-data">
<div class="form-group">
<label for="date_inp" class="control-label">Date</label>
<input class="form-control hasDatepicker" id="datepicker" type="text" name="date">
</div>
</div>
<div class="form-group">
<label for="file_inp">Upload File</label>
<div>
<input class="form-control" id="file_inp" type="file" placeholder="Upload File" name="file">
</div>
</div>
<div class="form-group">
<div>
<button type="submit" class="btn btn-default submit-button" onclick="on_click_form_submit(event);">Submit</button>
</div>
</div>
</form>
This is the click function.
on_click_form_submit = function(event) {
event.preventDefault();
var form_data = new FormData($('#request-form')[0]),
form_url = '/' + $('#request-form')[0].action.split('/').pop();
console.log('url: ' + form_url);
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
dataType: 'json',
encode: true
})
.done(function(response) {
alert(response);
})
.fail(function(xhr, status, error) {
alert(xhr.responseText);
});
return false;
};
When I click submit, it reports
Uncaught TypeError: Illegal invocation
at add (jquery-1.9.1.js:7340)
at buildParams (jquery-1.9.1.js:7392)
at Function.jQuery.param (jquery-1.9.1.js:7360)
at Function.ajax (jquery-1.9.1.js:7863)
at Object.on_click_form_submit (spa.shell.js:301)
Per the docs, jQuery's $.ajax accepts:
Type: PlainObject or String or Array
So, your form_data should be in one of those formats - it should not be an instantiation of a FormData. It depends on what your backend is expecting, but one option would be to convert the form's values to an object with serializeArray():
on_click_form_submit = function(event) {
event.preventDefault();
var form_data = $('#request-form').serializeArray(),
form_url = '/' + $('#request-form')[0].action.split('/').pop();
console.log('url: ' + form_url);
$.ajax({
url: form_url,
type: 'POST',
data: form_data,
dataType: 'json',
encode: true
})
.done(function(response) {
alert(response);
})
.fail(function(xhr, status, error) {
alert(xhr.responseText);
});
return false;
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-vertical" method="POST" id="request-form" action="/post_handler?request=add_data" enctype="multipart/form-data">
<div class="form-group">
<label for="date_inp" class="control-label">Date</label>
<input class="form-control hasDatepicker" id="datepicker" type="text" name="date">
</div>
</div>
<div class="form-group">
<label for="file_inp">Upload File</label>
<div>
<input class="form-control" id="file_inp" type="file" placeholder="Upload File" name="file">
</div>
</div>
<div class="form-group">
<div>
<button type="submit" class="btn btn-default submit-button" onclick="on_click_form_submit(event);">Submit</button>
</div>
</div>
</form>
We are working on form where user can upload 4 different photos. when i click choose file, it is calling to upload.php file and storing that file into uploadfiles directory.
but after file is uploaded unable to passing that particular file name to the angularjs.
Here is the UI Code
<head>
<script src="add-customer.js"></script>
<script type="text/javascript" src="angular-file-upload.js"> </script>
</head>
<body data-ng-cloak data-ng-app="AddCustomerApp" data-ng-controller="AddCustomerController as parentCtrl">
<section id="container">
<section id="main-content">
<section class="wrapper">
<div class="row mt">
<div class="col-lg-12">
<div class="form-panel">
<h4 class="mb">Add Customer</h4>
<form class="form-horizontal" role="form" id="AddCustomerForm" name="AddCustomerForm" autocomplete="off" enctype="multipart/form-data" novalidate="" data-ng-submit="AddCustomerData(AddCustomer)">
<div class="form-group">
<div class="col-sm-4">
<label for="firstname">First Name</label>
<input class="form-control" type="text" id="firstname" name="firstname" required placeholder="First Name" autofocus data-ng-model="AddCustomer.firstname">
</div>
</div>
<div controller="ChildController as childCtrl">
<div class="form-group" >
<div class="col-sm-6">
<label for="photo">Aadhaar Front</label>
<input type="file" class="form-control" id="adarfront" name="adarfront" required placeholder="Aadhaar Front" data-ng-model="AddCustomer.adarfront" ng-file-select="onFileSelect($files)">
</div>
<div class="col-sm-6">
<label for="photo">Aadhaar Back</label>
<input type="file" class="form-control" id="adarback" name="adarback" required placeholder="Aadhaar Back" data-ng-model="AddCustomer.adarback" ng-file-select="onFileSelect($files)">
</div>
</div>
<div class="form-group">
<div class="col-sm-6">
<label for="photo">Other ID Photo Front</label>
<input type="file" class="form-control" id="otheridfront" name="otheridfront" required placeholder="Other ID Photo Front" data-ng-model="AddCustomer.otheridfront" ng-file-select="onFileSelect($files)">
</div>
<div class="col-sm-6">
<label for="photo">Other ID Photo Back</label>
<input type="file" class="form-control" id="otheridback" name="otheridback" required placeholder="Other ID Photo Back" data-ng-model="AddCustomer.otheridback" ng-file-select="onFileSelect($files)">
</div>
</div>
</div>
<button type="submit" class="btn btn-theme" data-ng-disabled="AddCustomerForm.$invalid">Add</button>
</form>
</div>
</div>
</div>
</section>
</section>
</section>
</body>
Here is the AngularJs Code
var AddCustomer = angular.module("AddCustomerApp", ['angularFileUpload','ui.bootstrap'])
AddCustomer.controller("AddCustomerController", function ($scope, $timeout, $http, jsonFilter)
{
$scope.PersonalDetails = true;
var logResult = function (data, status, headers, config)
{
return data;
};
$scope.AddCustomerData = function (AddCustomer)
{
if($scope.AddCustomer.firstname==undefined || $scope.AddCustomer.adarfront==undefined || $scope.AddCustomer.adarback==undefined || $scope.AddCustomer.otheridfront==undefined || $scope.AddCustomer.otheridback==undefined)
{
alert("All fields are mendatory");
$scope.PersonalDetails = true;
$scope.WarningAlert = data;
}
else
{
$http.post('add-customer-process.php',{'firstname':$scope.AddCustomer.firstname,'adarfront':$scope.AddCustomer.adarfront,'adarback':$scope.AddCustomer.adarback,'otheridfront':$scope.AddCustomer.otheridfront,'otheridback':$scope.AddCustomer.otheridback})
.success(function (data, status, headers, config)
{
if(data=="Success")
{
$scope.PersonalDetails = true;
$scope.SuccessAlert = "Data added successfully";
$scope.AddCustomer = {};
$scope.AddCustomerForm.$setPristine();
$scope.AddCustomerForm.$setUntouched();
}
})
.error(function (data, status, headers, config)
{
$scope.WarningAlert = logResult(data, status, headers, config);
});
}
$scope.switchBool = function (value) {
$scope[value] = !$scope[value];
};
};
});
AddCustomer.controller('ChildController',function ($scope, $http, $upload)
{
$scope.parentCtrl.childCtrl = $scope.childCtrl;
$scope.onFileSelect = function($files)
{
$scope.message = "";
for (var i = 0; i < $files.length; i++)
{
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'upload.php',
method: 'POST',
file: file
}).
success(function(data, status, headers, config)
{
$scope.message = data;
$scope.message=$scope.message.replace('\"', '');
$scope.childCtrl.message=$scope.message.replace('\"', '');
})
.error(function(data, status)
{
$scope.message = data;
});
}
};
});
kindly help Us. I'm newbie to AngularJS. Thank you in Advance.
I'm using knockout to get some data from an API to fill my textboxes. I want to get the unit price from the API when you select a drug. How can I do this?
<div class="control-group">
<label class="control-label">Drug:</label>
<div class="form-horizontal">
<select id="Drug_ddl" data-bind="options: drugs, optionsText: function (item) { return item.Description; }, value: selectedDrug" class="input-xlarge"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">Unit Price:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: unitPrice" step="0.01" class="input-xlarge" id="UnitPrice_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Quantity:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: quantity" step="1" class="input-xlarge" id="Qty_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Cost:</label>
<div class="form-horizontal">
<input type="text" data-bind="value: drugcost" readonly="readonly" step="0.01" class="input-xlarge" id="Cost_txt" />
<input type="button" id="AddDrugs_btn" data-bind="click: addDrug" class="btn btn-primary" value="Add" />
</div>
</div>
This is the code for the viewModel:
var claimEntryViewModel = function () {
var drugs = ko.observableArray([]);
var unitPrice = ko.observable('0.00');
var quantity = ko.observable('1');
var drugcost = ko.computed(function () {
return quantity() * unitPrice();
});
var loadDrugs = function () {
url = apiServerUrl + "Items/";
$.ajax({
url: url,
headers: { 'Access-Control-Allow-Origin': '*' },
contentType: 'application/json',
dataType: 'json',
type: 'GET',
crossDomain: true,
success: function (data) {
drugs(data);
},
error: function (data) {
console.log("Is not answered");
console.log(data);
}
});
}
var selectedDrug = ko.observable();
var addDrug = function () {
var match = ko.utils.arrayFirst(claimDrugs(), function (item) {
return selectedDrug().ID === item.Id;
});
if (!match) {
claimDrugs.push({
Id: selectedDrug().ID,
Description: selectedDrug().Description,
unitPrice: selectedDrug().SalesPrice,
quantity: quantity(),
drugcost: drugcost(),
});
} else {
errorMessage("Already exists!");
}
}
return {
drugs: drugs,
addDrug: addDrug,
selectedDrug: selectedDrug,
unitPrice: unitPrice,
quantity: quantity,
drugcost: drugcost,
}
}
someone kindly provide me with a code that can do this, i'm fairly new to knockout and don't really know how to go about this. thanks
super cool is right, subscribing is a good way to handle this.
selectedDrug.subscribe(function (newValue) {
neededInfo(getSelectedDrugInfoFromApi(newValue));
});
This will call the getSelectedDrugInfoFromApi() every time the selectedDrug observable value changes, and update the neededInfo observable.
Keep in mind not to update the selectedDrug value inside the subscribe function though, as it will create a loop.
I am finding it difficult to send data to the controller through Ajax post since the object to be sent to the controller cannot be used within the ajax post because of the structure of my code.I am using knockout for data-binding the click event of the Update button.
This is my code
$(document).ready(function () {
var provider = function () {
var self = this;
self.providerID = ko.observable(providerEditInfo.ProviderID);
self.firstName = ko.observable(providerEditInfo.FirstName);
self.lastName = ko.observable(providerEditInfo.LastName);
self.contactEmail = ko.observable(providerEditInfo.ContactEmail);
self.NPI = ko.observable(providerEditInfo.NPI);
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: { providerForUpdate }, -- Cant send this
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
self.cancelEdits = function () {
if (confirm("Are you sure you want to Cancel?")) {
window.location.href = "/Provider/ShowTheListOfProviders";
}
};
}; //End of Constructor.
var providerForUpdate = new provider();
ko.applyBindings(providerForUpdate);
});
On the clck of Update Button,I am calling the 'updateProviderDetails' method.
HTML
#model Greenway.Demo.DataAccess.Entity.Provider
<body>
<div class="container">
<h1 class="col-sm-offset-2">Edit Provider Details:</h1>
<br />
<form class="form-horizontal" role="form" id="editProviderDetailsForm">
<div class="form-group">
<label class="col-sm-2 control-label labelfont">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" autofocus="autofocus" placeholder="Enter the First Name" id="firstName" name="firstName" data-bind="value:firstName , event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Last Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the Last Name" id="lastName" name="lastName" data-bind="value:lastName ,event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group text-center">
<button type="Submit" data-bind="click: updateProviderDetails" class="btn btn-primary">Update</button>
<button type="button" data-bind="click: cancelEdits" class="btn btn-primary">Cancel</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
var providerEditInfo = #Html.Raw(Json.Encode(Model));
</script>
<script type="text/javascript" src="../../App_Scripts/Shared/Functions.js"></script>
Could someone guide me on how I can send the data to the controller with this code structure.I can't put updateProviderDetails outside the constructor because otherwise, I can't bind it.
Use ko.toJSON to serialize your view model to json:
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
This is also in the Knockout Tutorial