how to add parameter into HttpContext.Request.Form from client side - javascript

I wanted to know how to add parameters into HttpContext.Request.Form via client side so that in the serve side i can get these data
i don't want to use ajax.
I tried the following but with no success:
javascript code:
var request = new XMLHttpRequest();
request.open("POST", window.location.host, true);
request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var formData = new FormData();
formData.append('key1', 'value1');
formData.append('key2', 'value2');
formData.append('skip', '10');
request.send(formData);
the asp.net mvc line of code:
var a = HttpContext.Request.Form.GetValues("skip");
but a is equal to null.
thank you all
Update:
I want to do something like datatable. In datatbles you can set draw,start, col_order etc. And you can get it with request into the server side. I want to know how can i do something like that.

You will need to combine data like this - "key1=value1&key2=value2&skip=10".
View
<button type="button" onclick="postData()">Post data</button>
<div id="result"></div>
<script>
function postData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("result").innerHTML = this.responseText;
}
};
xhttp.open("POST", "#Url.Action("PostData", "Home")", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("key1=value1&key2=value2&skip=10");
}
</script>
Controller
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
[HttpPost]
public JsonResult PostData(FormCollection collection)
{
var key1 = collection["key1"];
var key2 = collection["key2"];
var skip = collection["skip"];
return Json($"key1: {key1}, key2: {key2}, skip: {skip}");
}
}
Screen Shots

Related

Send blob file from javascript to C# asp.net

Hi I have a problem when I send a blob file from client side to backend. The website is in C# web forms.
the code of javascript:
function (data) {
console.log(data.buffer);
window.open(URL.createObjectURL(new Blob([data.buffer], { type: 'application/pdf' }), "_blank", "resizable=yes, scrollbars=yes, titlebar=yes, width=800, height=900, top=10, left=10"));
PostBack(data);
<%-- $.unblockUI();--%>
delete data;
},
The POSTBACK function:
function PostBack(data) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log(this.status);
console.log("staturi");
console.log(data);
// Typical action to be performed when the document is ready:
/*document.getElementById("MainContent_Label2").innerHTML = xhttp.responseText;*/
}
};
xhttp.open("POST", '<%= ResolveUrl("Default.aspx/testSS") %>', true);
xhttp.send(data);
}
Can you help me recive the PDF file and save it to server folder.
The backend function:
[WebMethod]
public string testSS(byte[] fileContent)
{
string straudioPath = "~App_Data/";;
FileStream objfilestream = new FileStream(straudioPath, FileMode.Create, FileAccess.ReadWrite);
objfilestream.Write(fileContent, 0, fileContent.Length);
objfilestream.Close();
return "OK";
}
Thank you for your help in advanced.

Send array with vanilla Js from Ajax to Laravel controller

I would like to send an array with elements to my laravel controller with vanilla JS, (I don't want to use Jquery). But I can't get it work... I found several solutions on web with trying to make a json object and so on but nothing wanted to work...
This is my code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
alert('sent');
}
};
xhttp.open("GET", '{{route('profile.toggleCategory', $user)}}', true);
xhttp.send(categories);
and my laravel controller:
public function toggleCategory(Request $request, User $user)
{
dd($categories = $request->categories);
$user->categories()->sync(collect($categories));
}
I changed a few things and now it is working!
The working code:
web.php:
Route::post('{user}/togglecategory', 'Site\ProfileController#toggleCategory')->name('toggleCategory');
Javascript code:
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if(this.readyState == 4 && this.status == 200){
alert('send');
}
};
xhttp.open("POST", '{{route('profile.toggleCategory', $user)}}', true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.setRequestHeader("X-CSRF-TOKEN", document.head.querySelector("[name=csrf-token]").content );
xhttp.send("categories="+categories);
});
Laravel Controller:
public function toggleCategory(Request $request, User $user)
{
$categories = explode(',', $request->categories);
$user->categories()->sync($categories);
}

Rapidapi Api request with XMLHttpRequest

this is my second post, I hope to be luckier than last time end get some reply. 🙂
I’m trying to make a Rapidapi api request working with javascript ”XMLHttpRequest”
I must say that the api works perfectly with ios siri shortcut.
this is the code provided from apirapit site on the "XMLHttpRequest" section:
var data = null;
var xhr = new XMLHttpRequest();
xhr.withCredentials = true;
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
console.log(this.responseText);
}
});
xhr.open("GET", "https://download-video-youtube1.p.rapidapi.com/mp3/medPORJ8KO0");
xhr.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhr.setRequestHeader("x-rapidapi-key", "[my key here]");
xhr.send(data);
And this is my code:
<!DOCTYPE html>
<html>
<body>
<h2>The XMLHttpRequest Object</h2>
<button type="button" onclick="loadDoc()">Request data</button>
<p id="demo"></p>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", url);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "[my key here]");
xhttp.send();
}
</script>
</body>
</html>
Just to testing I created a simply bank html page to have the JSON response beneath the button just after pressing it. The result is just the string “ciao” i set before the this.responseText. If I remove the apikey or modify it with a wrong value an JSON error message appear ( so like the case posted, as I intentionally removed it).
Otherwise as said noting but “ciao” string
Is there any syntax error? Is there a logical reason why it behave like this?
Thanks
Franco
Trying adding a data variable as null. That's what RapidAPI provides in their code snippet.
function loadDoc() {
const data = null
var xhttp = new XMLHttpRequest();
xhttp.withCredentials = true;
url='https://download-video-youtube1.p.rapidapi.com/mp3/xF5t2jOsCt8';
xhttp.onreadystatechange = function() {
if ((this.readyState == 4 && this.status == 200 )||(this.readyState === this.DONE)) {
document.getElementById("demo").innerHTML = "ciao" + this.responseText;
}
};
xhttp.open("GET", URL);
xhttp.setRequestHeader("x-rapidapi-host", "download-video-youtube1.p.rapidapi.com");
xhttp.setRequestHeader("x-rapidapi-key", "my key here");
xhttp.send(data);
}

Controller not receiving data?

i'm trying to send data from a view to a controller using POST but i doesn't seems to work.
Here's my code (javascript function) :
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
var titre = str;
xmlhttp.open("POST", "CheckReturn", true);
//xmlhttp.send(titre);
xmlhttp.send({"titre":titre});
}
}
the html triggering it :
<div id="check-name" class="form-row">
<input id="name" type="text" name="name" placeholder="Titre de l'événement" onkeyup="showHint(this.value)">
<span id="txtHint"></span>
</div>
and finally, the controller SUPPOSED to get it :
[HttpPost]
public ActionResult CheckReturn(string titre)
{
var contexte = new intranetEntities();
var ajax = contexte.evenementiel.SqlQuery("Somequery" + titre);
ViewBag.ajax = ajax;
return PartialView();
}
i checked bit firebug, the data is sent, but with visual studio's debugger, i see that "titre" always stay null.
What can i do ?
I've run into something similar in the past with asp.net but I never really tried to understand what's happening. What fixed it for me was the following:
make a new class somewhere in your back-end (anywhere, doesn't matter for now)
class TitreWrapper {
public string titre {get; set;}
}
then in your controller
[HttpPost]
public ActionResult CheckReturn(TitreWrapper titreWrap)
{
string titre = titreWrap.titre;
}
this should work according to my previous experience
the top answer is wrong (but right in other circumstances I think)
for this problem the following worked:
xmlhttp.open("POST", "/CheckReturn?titre=" + titre, true);
and then just
xmlhttp.send();
OR
xmlhttp.open("POST", "CheckReturn", true);
then
xmlhttp.send("titre=" + titre);

Submit list of objects from jsp to controller

I have dynamically varying list of parameters that I need to pass from a jsp page to spring mvc controller, how do I achieve this? Please provide a suggestion or a pseudo code so that I can proceed with my development.
Have you considered this:
<form id="myForm" action="blammo">
<input type="hidden" name="hoot"/> <!-- dynamically add hidden elements to -->
<!-- myForm then submit it -->
</form>
You can use ajax from the .jsp to your controller with POST or GET.
.jsp:
<%
Gson gson = new Gson();
%>
<script>
var json = "<% out.println(gson.toJson(myList).toString()); %>";
function sendData() {
"use strict";
var xhr;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState === 4) {
console.log("data send to my controller ...");
}
};
xhr.open("GET", "http://localhost:8080/url_of_my_controller?value=" + json, false);
xhr.send(null);
}
</script>
controller.java:
#RequestMapping(value = "/url_of_my_controller", method = RequestMethod.GET)
public #ResponseBody String controller(HttpServletRequest request, HttpServletResponse response) {
if (request.getParameter("value") != null) {
Gson gson = new Gson();
List<foo> list = gson.fromJson(request.getParameter("value"), List<foo>);
System.out.println(request.getParameter("value"));
return ("ok");
}
return ("ko");
}

Categories

Resources