Jquery UI Autocomplete - How to pass the variable from Jquery to ashx handler - jquery-ui-autocomplete

I am using Jquery UI Multiple Values Autocomplete and I'm making the request to Server:
.autocomplete({
source: function(request, response) {
$.getJSON("handlers/autocomplete.ashx", {
term: extractLast(request.term)
}, response);
},
How to I get back the value of term in my .ashx handler?
I have tried Request.Form["TextBox1"] but I'm getting object reference not set to an intance of an object error. Is there any way I can get it directly?
Thanks

pass TextBox1 value with the url
.autocomplete({
source: function(request, response) {
$.getJSON("handlers/autocomplete.ashx?TextBox1=curtxt", {
term: extractLast(request.term)
}, response);
},
Read TextBox1 from Handlers
public void ProcessRequest(HttpContext context)
{
HttpRequest request = context.Request;
HttpResponse response = context.Response;
string txtval = request["TextBox1"];
}

Related

How to intentionally make all Mirage JS request return 500?

Trying to make MULTIPLE mocked service response 500 for testing any suggestions?
Miragejs has a Response class which you can instantiate and return from your response handlers. The first argument in the constructor is the status:
import { Response } from 'miragejs';
this.get('/users', () => {
return new Response(500, { some: 'header' }, { errors: [ 'name cannot be blank'] });
});

Form Recognizer Anzalyze: Data loading error - 415

I am trying to call the form-recognizer API using SAPUI5 (Jquery / AJAX) post method. I am able to read the same pdf using RESTAPI client. The API when called from Javascript gives the below error.
The issue seems to be around data in the body of the ajax post method. Any suggestion/help is highly appreciated.
Error Message :
415 Unsupported Media Type
{"error":{"code":"2018","innerError":{"requestId":"a12dc9f8-b22f-4602-85d8-7330b16593f7"},"message":"Content
parsing error."}}
Javascript code :
onChange: function(oEvent) {
// var that = this;
var reader = new FileReader();
var file = oEvent.getParameter("files")[0];
var raw;
reader.onload = function (e) {
raw = e.target.result;
//alert(raw);
var sUrl2 = "https://formrecognizerforsap.cognitiveservices.azure.com/formrecognizer/v1.0-preview/custom/models/{mymodelid>/analyze";
jQuery.ajax({
type: "POST",
url: sUrl2,
context: this,
crossDomain: true,
data: raw,
beforeSend: function (xhr) {
xhr.setRequestHeader("content-type", "application/pdf");
xhr.setRequestHeader("ocp-apim-subscription-key", "my-subscription id");
},
error: function (jqXHR, textStatus, errorThrown) {
sap.m.MessageToast.show(errorThrown);
},
success: function (oData, status, jqXHR) {
sap.m.MessageToast.show(status);
}
});
};
reader.onerror = function (e) {
sap.m.MessageToast.show("error");
};
reader.readAsDataURL(file);
},
You could use atob javascript function to decode the Base64 string (link)
Example:
//plain text base64 WITHOUT datacontent and other stuff
let base64string = "JVBERi0xLjQKJ..."
let byteCharacters = atob(base64string);
jQuery.ajax({
type : "POST",
url : "<form recognizer url endpoint>",
context : this,
crossDomain: true,
data: byteCharacters,
beforeSend: function(xhr) {
xhr.setRequestHeader("ocp-apim-subscription-key", "<your_key>");
//To avoid specify pdf or image type use octet-stream
xhr.setRequestHeader("content-type", "application/octet-stream");
},
error : function(jqXHR, textStatus, errorThrown) {
console.error(errorThrown);
},
success : function(oData, status, jqXHR) {
console.info(status);
}
});
To get plain base64 string from pdf you could use this website to test: https://base64.guru/converter/encode/pdf

Using angular 4 to send form-data

Hi I'm building a WordPress theme and I need to use contact form 7 plugin on it, but I can't figure out the correct way to send the form data to the plugin.
here is my post service:
import {
Injectable
} from '#angular/core';
import {
HttpClient,
HttpHeaders
} from '#angular/common/http';
#Injectable()
export class FormsService {
constructor(private http: HttpClient) {}
postForm(url, form) {
return this.http.post(url, form, {
headers: new HttpHeaders().set('Content-Type', 'multipart/form-data'),
})
}
}
and the component part that use the service:
onSubmit() {
const fd = new FormData();
fd.append('your-name', this.name);
fd.append('your-email', this.email);
fd.append('your-message', this.message);
fd.append('your-subject', this.sumbject);
const url = `/wp-json/contact-form-7/v1/contact-forms/${this.form_id}/feedback`;
this.sendMsg.postForm(url, fd).subscribe(
data => {
console.log(data);
},
err => console.log({
error: err
})
)
this.submitted = true;
}
At this point the server response that the message was submitted ok, but when I go to the WP admin page, non of the field get the values.
But If I use postman with this url and params the form all works as I want.
I also found another solution that works but its not the angular way as I want to be.
the solution
onSubmit() {
const url = `/wp-json/contact-form-7/v1/contact-forms/${this.form_id}/feedback`;
this.submitted = true;
}
sendData(url) {
let XHR = new XMLHttpRequest();
const FD = new FormData();
FD.append('your-name', this.name);
FD.append('your-email', this.email);
FD.append('your-message', this.message);
FD.append('your-subject', this.subject);
// Define what happens on successful data submission
XHR.addEventListener('load', function(event) {
alert('Yeah! Data sent and response loaded.');
});
// Define what happens in case of error
XHR.addEventListener('error', function(event) {
alert('Oups! Something went wrong.');
});
// Set up our request
XHR.open('POST', url);
// Send our FormData object; HTTP headers are set automatically
XHR.send(FD);
}
I found my solution, the problem was on the headers definitions of my service, the correct way is:
postForm(url, body) {
var headers = new HttpHeaders();
headers.append('Content-Type', 'application/form-data');
return this.http.post(url, body, {headers: headers })
}

Form has enctype="multipart/form-data" but Request Content-Type is application/x-www-form-urlencoded; charset=UTF-8

I have a basic form in ASP.Net MVC4 using Html helpers. I have an input file in the form for uploading a file which will be added to a database. In my view model I have a property for the input file:
public HttpPostedFileBase AssetFile { get; set; }
In my view I have the form helper:
#using (Html.BeginForm("Create", "Contact", FormMethod.Post, new { enctype = "multipart/form-data" }))
Inside my form:
#Html.TextBoxFor(model => model.AssetFile, new { #type = "file", #name = "AssetFile" })
Yet, when I post the form there are no files in the Request.Files. Then I noticed that in Fiddler the Request Header has Content-Type: application/x-www-form-urlencoded; charset=UTF-8. I have another form with an input file and the header has Content-Type: multipart/form-data; boundary=----WebKitFormBoundaryCfBFSR0RXQRnasfb and this form works fine. I tried doing this without Html helpers and same thing happens. The view model itself inherits from another view model where the input file actually belongs but then I have a string property mapped to a textbox and the form is picking up this value. There is no nested forms (on this page this is the only form) but I am having the same problem with another page that has multiple form (not nested) using multiple partial views that contain the forms like this:
#using (Html.BeginForm("Edit", "Home", FormMethod.Post, new { #enctype = "multipart/form-data" })){ #Html.Partial("EditorTemplates/_Profile", Model.InstitutionProfileInformation)}
Thanks in advance for any help.
OK - Here's the weirdness. Since they're (the original coder(s)) using partial views they ajaxified this thing. When the partial view (with the form) is rendered:
var loadContactDiv = function (e) {
isChanged = false;
var url = e.href;
$("#Contacts").load(url, function (response, status, xhr) {
if (status == "error") {
var msg = "Sorry but there was an error: ";
}
$("#Contacts").find('form').submit(divSubmitHandler).change(function () {
isChanged = true;
});
$("#ReturnButton").click(function () {
loadContacts();
});
});
return false;
};
Then when the user click the submit button:
var divSubmitHandler = function () {
var form = $("#Contacts").find('form');
var test = form.serialize();
debugger;
$.ajax({
url: (form).attr('action'),
data: form.serialize(),
type: "POST",
success: function (data) {
if (data == "") {
loadContacts();
} else {
$("#Contacts").html(data);
$("#Contacts").find('form').submit(divSubmitHandler).change(function () {
isChanged = true;
});
$("#ReturnButton").click(function (e) {
loadContacts();
});
}
}
});
return false;
};
Still stuck: http://prntscr.com/20v2cp
Since you are not submitting the form, but using $.ajax to process the request remotely and then get the result, the enctype is ignored from the form itself.
As you can also see the form data is serialize and sent.
So the fix here is simple, to submit the content-type correctly, just add a
content-type
option to the ajax request like so,
var divSubmitHandler = function () {
var form = $("#Contacts").find('form');
var test = form.serialize();
debugger;
$.ajax({
url: (form).attr('action'),
**contentType: 'multipart/form-data',**
data: form.serialize(),
type: "POST",
success: function (data) {
if (data == "") {
loadContacts();
} else {
$("#Contacts").html(data);
$("#Contacts").find('form').submit(divSubmitHandler).change(function () {
isChanged = true;
});
$("#ReturnButton").click(function (e) {
loadContacts();
});
}
}
});
return false;
};
This should do the trick. However if it does not work, please refer to Jquery Form Ajax submit.
jQuery AJAX submit form
Have a nice session!

Model binding issue with property name as "Id"

Actually in one request, i am getting the data from the ajax call and then posting the data back in another request back to the controller and here i am using model binding,
here i have the following issues,
1. The dictionary in the bound object is null
2. The Id property [value received at Ajax response] but not received at controller during modelbinding
since i am not storing any values in the hidden fields and am just caching the data and passing to other requests, how do i handle the id and dictionary issues in ASP.Net MVC2.
EDIT
*Model in C#:*
public class ViewObject
{
public string Id {get;set;}
public string Name {get;set;}
}
AJAX Code
function fillExistingViews() {
$.ajax({
url: "..",
data: {
ViewId: $("#View_Id").val()
},
type: "POST",
success: function (data) {
if (data !== undefined) {
var ViewObj = JSON.parse(data);
if (ViewObj.ViewObjects === undefined) {
return false;
}
//ViewObj.ViewObjects = dictionary<string,ViewObject
for (var vo in ViewObj.ViewObjects) {
// HERE I GET ViewObj.ViewObjects[vo].Id
$.ajax({
url: "..",
type: "POST",
contentType: "application/json",
data: JSON.stringify(ViewObj.ViewObjects[vo]),
// on posting the viewobject to the server, i find ViewObject.Id to be null
success: function (data) {
//..
}
});
}
}
}
});
}