API POST call with large model, need some guidance - javascript

I have a fairly large form (50 fields) and I need to pass it into an API call.
Doing it in the javascript file would be pretty large to serialize all the data on the form into the proper model.
Is it possible to call the controller, and use the model from that to pass it through to the api url?
Basically I want to know an easy way to take my form data and turn it into serialized data based on my model.
thanks!
EDIT: Easy meaning that I don't have to take each form input and create my model with them
My code now is basically this below, but I would need to fill out a bunch of fields (I haven't tried it any other way)
$("#submit").click(function () {
var name = $("#Name").val();
var address = $("#Address").val();
var dob = $("#DOB").val();
$.ajax({
url: "http://localhost:49493/api/Values",
type: "Post",
data: JSON.stringify([name, address, dob]),
//instead of 3 fields, I would have 50
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function () { alert('error'); }
});
});

jQuery has a function that you can use $("#myForm").serialize()
http://api.jquery.com/serialize/
$("#submit").click(function () {
var myData = $("#myForm").serialize()
$.ajax({
url: "http://localhost:49493/api/Values",
type: "Post",
data: myData,
//instead of 3 fields, I would have 50
contentType: 'application/json; charset=utf-8',
success: function (data) { },
error: function () { alert('error'); }
});
});
(Although a 50 form field sounds quite large. You might want to reconsider your design, but perhaps there is a valid use case)

A javascript MV* framework can be helpful here (I'm most familiar with angular). With angular, you can define a binding between your UI elements and the underlying javascript model representation (which can be sent to your Web API with the $http service).
Here is a language agnostic way to iterate over elements and build a model. It was done quick and dirty, and there is much room for improvement (i.e. using addEventListener, attachEvent, then onclick, etc.) -- but jquery handles much of this for you, so would suggest to stick with using that. This could easily be converted over to jQuery... The javascript iterates over input elements and adds them to a model object. This object can then be sent over AJAX if desired. The example just outputs it to a div placeholder.
http://jsfiddle.net/T9MyZ/
JavaScript:
document.getElementById("submitMe").onclick = function () {
var inputs = document.getElementsByTagName("input");
var model = {};
for (var i = 0, len = inputs.length; i < len; i++) {
var elem = inputs[i];
model[elem.name] = elem.value;
}
document.getElementById("jsonText").innerHTML = JSON.stringify(model);
};
HTML:
<input type="text" name="name"><br>
<input type="text" name="address"><br>
<input type="text" name="dob"><br>
<button id="submitMe">Submit</button>
<br>
<div id="jsonText"></div>

Related

AJAX - submit multiple POST data

I am desperately trying to submit multiple POST variables via AJAX, but just cant get manage to get the formatting right... Problem is that I have both a hardcoded / written action=problem_lookup variable and a dynamic field input as $(this).val and just cant manage to get both into one data string...
this works well:
data: 'problem=' + $(this).val(),
This does not:
data: { action: 'problem_lookup' , problem: $("problem").val() },
data: { action: 'problem_lookup' , problem: $(this).val() },
data: { action: problem_lookup, problem: $(this).val() },
I tried numerous formats from other threads and looked at the official jquery manual, but cant seem to get this figured out. Any help is appreciated.
EDIT:
full script below, tried the solutions posted so far but no success. $("problem") is a <select> field (with Select2 running) hence shouldnt cause me so much frustration, especially since the original approach with data: 'problem=' + $(this).val(), works fine.
$(function () {
$('#problem').change(function () { // on change in field "problem"
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
$.ajax({ // launch AJAX connection
type: 'POST', // via protocol POST
url: 'ajax.php',
//data: 'problem=' + $(this).val(), // send $_POST string
//data:"{'action':'"+action+"','problem':'"+$(this).val()+"'}",
//data:"{'action':'problem_lookup','problem':'"+$(this).val()+"'}",
//data: { action: 'problem_lookup' , problem: $("problem").val() },
//data : data_string,
data: $.param(data),
dataType: 'json', // encode with JSON
success: function (data)
{
// do something
},
});
});
});
An issue is in the
$("problem")
Jquery call.
If.problem is a css class try with
$(".problem")
if problem is a css id try with
$("#problem")
For posting arrays of object you can build data as an object containing arrays, changing a little bit your structure. Something like this
Var obj={};
obj.postData=[];
obj.postData.push(/*your first object here*/);
...
obj.postData.push(/*your n-th object here*/);
$.ajax({
.....
data:obj;
......
});
Try the FormData() FormData.
var data = new FormData();
data.append('action', value);
...
You need to specify your data variable first like this:
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
In AJAX serialize your data using $.param,
data: $.param(data),
Note: Twice check if $("problem").val() is correct. If problem is a class, you need to specify like this $(".problem").val() or if it is ID, $("#problem").val()

ASP.Net MVC model binding to javascript

The question is pretty straightforward: I use #Html.EditorForModel() to generate fields for my model. Then user fills all these fields and I want to send this field via AJAX, becuase I should do several server's services without page reload.
I googled several approaches, but it seems that there is no standard way to do such things. I mean I do not have an object on client-side that represent model. I found one single library calls JSModel (link) but it seems to be not working. My code for now is:
#model Student
<script src="#Url.Content("~/scripts/jquery-1.12.2.min.js")" type="text/javascript" async="async"></script>
<script src="#Url.Content("~/scripts/Requester.js")" type="text/javascript" async="async"></script>
<script src="#Url.Content("~/scripts/jsmodel.js")" type="text/javascript"></script>
<script type="text/javascript">
var requester = new Requester(#Html.Raw(Json.Encode(new Student())));
function SendSignupRequest() {
requester.SendSignupRequest();
}
</script>
<h2>Student</h2>
<div>
#Html.EditorForModel()
</div>
<input type="button" value="Send" onclick="SendSignupRequest()"/>
Requester.js:
function Requester(rawModel) {
this.modelObj = new JSModel(rawModel);
this.SendSignupRequest = function() {
var model = modelObj.refresh();
var val = model.prop("Name");
alert(val);
}
}
Is there any easy way to serialize a model object in JSON and send it to server, without manually constructing an object with millions of document.getElementById?
View
#using (Html.BeginForm("action", "controller", FormMethod.Post, new { #class = "form-horizontal form-compact ", role = "form", id = "form1" }))
{
}
Java Script
var formdata = $("#form1").serializeArray();
$.ajax({
url: url,
type: 'POST',
data: formdata,
success: function (data) {
}
Controller
public ActionResult action(Model model)
{
//access data here
}
You can serialize your form to a JSON object with jQuery:
var data = $('form').serialize();
(This would, of course, mean wrapping your form elements in a form, which really should be happening anyway.)
Then just pass that data object to the server in the POST request. Something as simple as:
$.post('some/url', data, function(response) {
// success callback
});
without manually constructing an object with millions of document.getElementById
Note that if your object has millions of fields then you may very well encounter other problems here.
Yes you can use form serialize using Jquery
var formData = $('#form').serializeObject();
$.extend(formData, { Contacts : myContacts});
$.extend(formData, { Address : myAddress});
var result = JSON.stringify(formData);
$('#formHiddenField').val(result);
then submit form using:
$.ajax(
url: #Url.Action("post url")
data: myForm.serialize(),
dataType: 'json',
type: 'POST',
success: function(){
})
Why not Ajax.BeginForm() for your purposes. I believe model binding works automatically.

JavaScript: Tips on how to use onblur to get info from another server and auto populate other textbox entries?

I'm trying to make a web page using primarily HTML, CSS and JavaScript (I'm fairly new to making websites, so these are the only three I am fairly decent with). This web page will be a form that will interface with an enterprise software (BMC Remedy ITSM) that will enforce validation and make all of our tickets precise when submitted.
One of the few static textboxes on the web page will be an ID number field, a full-name field and a phone-number field.
My goal is to have the user put in their ID number, and have this ID number communicate with the enterprise software, look up the ID number, and auto-populate the full name and phone number from the ID number given.
I want this to be a lostfocus event on the ID number textbox, so therefore I guess it would be under onblur for JavaScript.
Can someone chime in and give me some pointers on how I would achieve this?
Thanks!
A quick example of using the blur event is below in pure JavaScript. Top example shows JSON return and bottom example shows XML.
Fiddle: http://jsfiddle.net/9dpxmpru/2/
HTML:
<input id="empid" type="text" placeholder="Employee ID" />
<input id="name" type="text" placeholder="Full Name" />
<input id="phone" type="text" placeholder="Phone" />
JS:
var empid = document.getElementById('empid');
empid.addEventListener('blur',
function (event) {
var idVal = this.value;
// make some ajax call
// perhaps it returns this
var response = {
name: "John Doe",
phone: "555-5555"
};
var name = document.getElementById('name');
var phone = document.getElementById('phone');
name.value = response.name;
phone.value = response.phone;
}, true
);
As for the ajax call you can do something like this:
// Make Ajax Call
var requestObject = new XMLHttpRequest();
requestObject.open('POST', 'someurl', true);
requestObject.setRequestHeader('Content-Type', 'application/json; charset=utf-8');
// XML: requestObject.setRequestHeader('Content-Type', 'text/xml');
requestObject.onload = function () {
if (this.status >= 200 && this.status < 400) {
// Success!
}
else {
// Handle some server error
}
};
requestObject.onerror = function () {
// Handle some server error
};
requestObject.send(JSON.stringify('idValueFromField'));
This is of course very rough but the general idea.
Here is fiddle parsing xml: http://jsfiddle.net/9dpxmpru/4/
var empid = document.getElementById('empid');
empid.addEventListener('blur',
function (event) {
var idVal = this.value;
// make some ajax call
// perhaps it returns this
var response = "<response><name>John Doe</name><phone>555-5555</phone></response>";
var parser = new DOMParser();
var xmlDoc = parser.parseFromString(response, 'text/xml');
var name = document.getElementById('name');
var phone = document.getElementById('phone');
name.value = xmlDoc.getElementsByTagName('name')[0].childNodes[0].nodeValue;
phone.value = xmlDoc.getElementsByTagName('phone')[0].childNodes[0].nodeValue;
}, true
);
jQuery Examples:
$("#empid").on("focusout",
function (event) {
var idVal = $(this).val();
// make some ajax call
// perhaps it returns this
var response = {
name: "John Doe",
phone: "555-5555"
};
$("#name").val(response.name);
$("#phone").val(response.phone);
}
);
jQuery Ajax:
$.ajax({
method: "POST",
url: "someurl",
dataType: 'json',
// XML: dataType: 'xml',
data: {
empid: idVal
}
}).done(
function (msg) {
// success!
}
);
jQuery XML example:
$("#empid").on("focusout",
function (event) {
var idVal = $(this).val();
// make some ajax call
// perhaps it returns this
var response = "<response><name>John Doe</name><phone>555-5555</phone></response>";
var xmlDoc = $.parseXML(response),
var xml = $(xmlDoc),
$("#name").val(xml.find("name").text());
$("#phone").val(xml.find("phone").text());
}
);
As far as your idea goes, you're on the right track. But since you said you're newer to web development, I'll explain more. You're going to have a text input that listens for a blur. The blur event will then send an XMLHttpRequest to your ITSM software, supplying a response handler that will execute as soon as the request completes.
If you haven't looked into it yet, and if you have the option, I would suggest jQuery, because it provides traversal functionality for HTML that also [mostly] works on XML. It'll also make your calls a bit easier.
HTML:
<input id="employeeId" type="text" placeholder="Employee ID">
<input id="fullName" type="text">
<input id="phone" type="text">
Assuming your XML is something like this:
<lotsOfResponseParentNodes>
<person>
<fullName>John Doe</fullName>
<phoneNumber>5555551212</phoneNumber>
</person>
</lotsOfResponseParentNodes>
JavaScript (place at bottom of body):
function setFieldVals(fullName, phoneNumber) {
$("#phone").val(phoneNumber);
$("#fullName").val(fullName);
}
$("#employeeId").blur(function(e) {
$.ajax({
type: "POST", //or GET, depending on your api spec
url: ENDPOINT_URI, //Again, depending on your software
data: {employeeId: $(e.target).val()}
dataType: "xml",
success: function(xml) {
setFieldVals($(xml).find("fullName").text(), $(xml).find("phoneNumber").text());
},
error: function() {
alert("An error happened.");
}
});
});
What's key here is how you're parsing your XML. In the XML example I have above, find("nodeName") works. But if the XML were, say, <person phone="xxx"> then you'd have to $(xml).find('person').attr('phone') instead.

jQuery Ajax placing random "jQuery111201xxx" into string

I have made a booking system that utilizes FullCalendar; though that part should be irrelevant. My problem is that upon saving an appointment, a 'notes' field I have created very occasionally has this strange string inserted into it, generally at a random point in the string. Here is the latest example:
Has this been changedjQuery1112010047650896012783_1444929292744 with Rich- finishing sleeve off.bringing deposit in on saturday. told him space isnt secure.
As you can see, there is a totally out of place "jQuery1112010047650896012783_1444929292744" placed in the middle of the note. I can't find anything about this online (mainly because I have no idea what terms I'd use to find it). It must be related to jQuery, considering the string.
I am using jQuery v1.11.2 - obviously the string looks like a long version number.
Why is my ajax request seemingly succeeding, but placing this message in the middle of the sent string? I cannot replicate this issue at all, especially this time since it was another user who managed to cause it.
The function that fetches/prepares/sends data looks like this:
function postForm(content, action, update) {
loader('show');
var popup = content.parent();
var children = content.find(".input");
var data = {}
var elements = [];
data['elements'];
$( children ).each(function() {
var child = {};
child['name'] = $(this).attr('data-name');
if ($(this).is(':checkbox')) {
child['value'] = $(this).is(":checked");
} else {
child['value'] = $(this).val();
}
elements.push(child);
});
data.elements = elements;
data.request = action;
dataPost = JSON.stringify(data);
console.log(dataPost);
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});
return false;
}
The note section is just a textarea with the class 'input' (which is looped through and fetched).
I don't think there will be a solution for the exact problem, however, I'm looking for an explanation for the modification of the string. The application works perfectly, except for this very rare case.
Question marks (??) are replaced with a jQuery time stamp. To fix, I had to add jsonp: false to the parameters. Final ajax:
ajaxRequest = $.ajax({
type: "POST",
url: "/?page=ajax",
data: dataPost,
dataType: 'json',
jsonp: false,
success: function(response) {
loader('hide');
console.log(response);
if (update) {
$(update.element).load(update.url+" "+update.element+" > *");
checkError = doExtra(response, update.extra);
}
if (checkError == false) {
popup.fadeOut();
}
}
});

Telerik MVC Grid - Pass Value to New Controller Action

Using Telerik Extensions for ASP.NET MVC, I created the following Grid:
.. and I am able to extract the value of my Order Number using the client-side event "OnRowSelect", when the user selects any item in the grouped order. I can then get as far as displaying the selected value in an alert but what I really want to do is pass that value back to a different controller action. Is this possible using javascript?
When I tried the server-side control, I ended up with buttons beside each detail row, which was just not the effect/look desired.
You can easily make an ajax call in that event.
Kind of two part process (assuming your event handler resides in a separate .js file- otherwise you can define a url directly in .ajax call).
Define an url you need to post to - in $(document).ready(...)
like:
<script type="text/javascript">
$(document).ready(function() {
var yourUrl = '#Url.Action("Action", "Controller")';
});
Then place in your OnRowSelect event handler something like:
function onRowSelect(e) {
var row = e.row;
var orderId = e.row.cells[0].innerHTML;
$.ajax(
{
type: "POST",
url: yourUrl,
data: {id: orderId},
success: function (result) {
//do something
},
error: function (req, status, error) {
//dosomething
}
});
}
That should do it.
As it turns out there is an easier way to get to the new page by simply changing the Window.location as follows:
var yourUrl = '#Url.Action("Action", "Controller")';
var orderID;
function onRowSelected(e) {
var ordersrid = $('#IncompleteOrders').data('tGrid');
orderID = e.row.cells[1].innerHTML;
window.location = yourUrl + "?orderId=" + orderID;
}
Thanks to those who responded; however, the above answer as provided from Daniel at Telerik is more of what I was looking for.

Categories