How to include headers in an ajax post request to web api - ajax

Hey guys I am having an issue I am a little confused with as I am new to dealing with Web API's. I am trying to run a POST from an html page to my web api to create a user. In the post method though it checks for authentication based on headers of the users id. How would I go about including a header when I send my ajax post. Right now I am getting the forbidden status response, so I know the ajax is actually hitting the method.
Here is my ajax post call:
$(function () {
var $users = $("#users");
$("#postForm").submit(function (event) {
event.preventDefault();
var $form = $(this),
firstName = $form.find("input[name='firstName']").val(),
lastName = $form.find("input[name='lastName']").val(),
email = $form.find("input[name='email']").val(),
password = $form.find("input[name='password']").val(),
url = $form.attr("action");
var posting = $.post(url, { firstName: firstName, lastName: lastName, email: email, password: password });
posting.done(function (data) {
var content = $(data).find("#content");
$("#result").empty().append(content);
});
});
});
and this is my html:
form action="http://localhost:24500/api/User" id="postForm">
<input type="text" name="firstName" placeholder="First Name">
<input type="text" name="lastName" placeholder="Last Name">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<input type="submit" value="Post User">
</form>
<div id="result"></div>

You simply need to use the more flexible .ajax() function. It allows you to specify username and password for basic authentication as configuration parameters.
The documentation - https://api.jquery.com/jQuery.ajax/

Related

AJAX form $('form')[0].reset(); on submit not clearing values. What am I missing?

thank you in advance for any help given. I'm just learning jQuery and AJAX and would appreciate some help with the following code. All validation rules work, the form submits and the page does not refresh. The problem is that the form values are not clearing/resetting to default after the submit has triggered. Thoughts?
**********EDITED to include HTML markup*************
<div id="form">
<h1 class="title">Contact Us</h1><!-- title ends -->
<p class="contactUs">Ask about our services and request a quote today!</p><!-- contactUs ends -->
<div id="success"><p>Your message was sent successfully. Thank you.</p></div>
<p id="required">* All fields required.</p>
<form name="form" id="contactMe" method="post" action="process.php" onSubmit="return validateForm()" enctype="multipart/form-data">
<input class="txt" type="text" maxlength="50" size="50" required name="name" value="<?php echo $_GET['name'];?>" placeholder="Name" />
<div id="nameError"><p>Your name is required.</p></div>
<input class="txt" type="text" maxlength="50" size="50" required name="email" value="<?php echo $_GET['email'];?>" placeholder="Email Address" />
<div id="emailError"><p>A valid email address is required.</p></div>
<textarea name="message" rows="6" cols="40" required placeholder="Message"></textarea>
<div id="messageError"><p>A message is required.</p></div>
<input type="hidden" maxlength="80" size="50" id="complete" name="complete" placeholder="Please Keep This Field Empty" />
<input type="submit" value="SUBMIT" name="submit" />
<input type="reset" value="RESET" name="reset" />
</form>
</div><!-- form ends -->
//hide form submit success message by default. to be shown on successfull ajax submission only.
$(document).ready(function() {
if ($('#success').is(':visible')){
$(this).hide()
}
});
//form validation
function validateForm() {
//name
var a=document.forms["form"]["name"].value;
if (a==null || a=="")
{
$('#nameError').fadeIn(250);
return false;
}
//email address
var c=document.forms["form"]["email"].value;
var atpos=c.indexOf("#");
var dotpos=c.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=c.length)
{
$('#emailError').fadeIn(250);
return false;
}
//message
var e=document.forms["form"]["message"].value;
if (e==null || e=="")
{
$('#messageError').fadeIn(250);
return false;
}
}//javascript form validation ends
//ajax submit and clear form on success
$(function () {
$('form').on('submit', function (e) {
var myForm = validateForm();
if (myForm == false){
e.preventDefault();//stop submission for safari if fields empty
}
else{
$.ajax({
type: 'post',
url: 'process.php',
data: $('form').serialize(),
success: function () {
$('#success').fadeIn(250);
if ($('#nameError, #emailError, #messageError').is(':visible')) {
$('#nameError, #emailError, #messageError').fadeOut(250);
}
$('form')[0].reset();//clear form after submit success
}//success ends
});//ajax ends
e.preventDefault();//prevent default page refresh
}//else ends
});//submit ends
});//function ends
//if reset button is clicked AND messages displayed, remove all form html messages
$(document).ready(function() {
$('#form input[type="reset"]').click(function() {
if ($('#success, #nameError, #emailError, #messageError').is(':visible')) {
$('#success, #nameError, #emailError, #messageError').fadeOut(250);
}
});
});
By giving your input id="reset" and/or name="reset", you effectively overwrote the form.reset method of the form because by doing so you made form.reset target the reset button. Simply give it a different id and name value.
Never give elements name or id attributes that equal the name of a property of a dom node.

Access Get or Post parameters in MVC Web Api Authorization filter

I want to achieve the same as Accessing post or get parameters in custom authorization MVC4 Web Api ,but it only works in the case of a GET request.
So I have written the follwoing action filter for a web api:
public override void OnActionExecuting(System.Web.Http.Controllers.HttpActionContext actionContext)
{
var request = actionContext.Request;
var headers = request.Headers;
HttpContext ctx = default(HttpContext);
ctx = HttpContext.Current;
if (ctx != null)
{
var apiKey = (string)actionContext.ActionArguments["apiKey"];
}
}
The form that posts looks like:
<form name="form1" method="post" enctype="multipart/form-data" action="#localPostUrl">
<fieldset>
<legend>File Upload Example</legend>
<div>
<label for="caption">Image Caption</label>
<input name="caption" type="text" />
</div>
<div>
<label for="image1">Image File</label>
<input name="image1" type="file" />
</div>
<div>
<input type="text" name="apiKey" id="apiKey" value="b2b54e7b-ca0b-4adf-a369-efe839e55120" />
<input type="submit" value="Submit" />
</div>
</fieldset>
So I'm trying to post an image and a string to the Web Api but the actionContext.ActionArguments in the ActionFilter is empty when doing a POST request but is working when doing a GET request.
When compared to the solution provided on top of my question I notice that the action where that posts has an attribute FormUri added to a parameter, but I can't send the ApiKey in the querystring.
Is there a solution to getting the Post paramteres in order to do some form on validation?

Hot Towel Angular data-ng-show not working during validation

Hello anyone has anyone tried doing a validation using angularjs in a with Hot Towel template?
Basically i have a property in my angular controller which is binded(two way) in my view.
I just want to do a simple required validation, and then show a <span> element with the message.
here is my controller code
(function () {
'use strict';
var controllerId = 'login';
angular.module('app').controller(controllerId, ['$scope', 'common', 'userservice','$location', login]);
function login($scope, common, userservice, $location) {
var getLogFn = common.logger.getLogFn;
var log = getLogFn(controllerId);
var vm = this;
vm.title = 'Login';
//view model for credentials
vm.email = null;
activate();
function activate() {
common.activateController([], controllerId)
.then(function () { log('Activated Login View'); });
}
}
})();
and this is my view
<div data-ng-controller="login as vm">
<form name="loginform" id="loginform" novalidate data-ng-submit="loginuser()">
<fieldset>
<legend>Login</legend>
<p>
<label>Email</label>
<input type="email" data-ng-model="email" placeholder="Email" required />
<span data-ng-show="loginform.email.$error.required">*</span>
</p>
</fieldset>
</form>
</div>
i dont know what the problem is, but the <span> just wont show. am i missing something?
You have to set 'name' attribute to your input email :
<input type="email" name="email" data-ng-model="email" placeholder="Email" required />
For each field of your form, angularjs will set a value like: loginform[name-attribute].
For your information, your span will be visible only when required error is triggered (when your email is not empty, your span will be hidden).
[EDIT] See this fiddle: http://jsfiddle.net/k82at

Automate AJAXed forms with Jquery

I want to improve my website and figured out a good way to do it was by submitting forms via AJAX. But, I have so many forms that it would be inpractical to do $('#formx').submit(). I was wondering if there was a way to do this automatically by making an universal markup like;
<form class="ajax_form" meta-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
</form>
And have this submit to ajax/pagename.php, where it automatically includes inputx and inputy?
This would not only save me a lot of time but also a lot of lines of code to be written.
First question so I hope it's not a stupid one :)
Something like this should work for all forms. It uses jQuery - is this available in your project? This specific code chunk hasn't been tested per say, but I use this method all the time. It is a wonderful time saver. Notice I changed meta-submit to data-submit so that its value can be fetched using $('.elemenet_class').data('submit');
HTML
<!-- NOTE: All Form items must have a unique 'name' attribute -->
<form action="javascript:void(0);" class="ajax_form" data-submit="ajax/pagename.php">
<input type="text" name="inputx" value="x_value">
<input type="text" name="inputy" value="y_value">
<input type="submit" value="go" />
</form>
JavaScript
$('.ajax_form').submit(function(e){
var path = $(this).attr('data-submit'); //Path to Action
var data = $(this).serialize(); //Form Data
$.post(path, {data:data}, function(obj){
});
return false;
})
PHP
//DEBUGGING CODE
//var_dump($_POST);
//die(null);
$data = $_POST['data'];
$inputx = $data['inputx'];
$inputy = $data['inputy'];
you can create ajax fot text boxes so that it can update to database whenever change the focus from it.
<form id="ajax_form1">
<fieldset>
<input type="text" id="inputx" value="x_value" />
<input type="text" id="inputy" value="y_value" />
</fieldset>
</form>
<script>
$(document).ready(function()
{
$("form#ajax_form1").find(":input").change(function()
{
var field_name=$(this).attr("id");
var field_val=$(this).val();
var params ={ param1:field_name, param2:field_val };
$.ajax({ url: "ajax/pagename.php",
dataType: "json",
data: params,
success: setResult
});
});
});
</script>

how do I add an ajax response to my form without adding a new js file?

I have this simple submission form and I want to "ajaxify" it so the user isn't redirected to this page thanks.php after submission. I want the content from thanks.php to respond and show inside the div.
What jquery code will plug right into this to show the response.
<div ><form method="post" action="http://domain.com/thanks.php">
<input type="text" placeholder="Enter Email" name="email" id="email" >
<input type="submit" name="submit" value="Submit" ></form></div>
I would give 'form' and 'div' a class or id so it is not so generic, but this should work.
$("form").submit(function (){
$.ajax({
url: "http://{url}/thanks.php",
type: 'POST',
data: {email: $("#email").val()},
success: function ( data ) {
$("div").html(data);
}
});
return false;
});

Resources