function sendRequestToDelicious()
{
var xmlhttp=false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
var url = "http://localhost:52271/WebForm1.aspx";
var params = "q=hello";
xmlhttp.open("POST", url, true);
//Send the proper header information along with the request
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.setRequestHeader("Content-length", params.length);
xmlhttp.send(params);
}
In my ASP.NET app, I am reading the stream from page_load event, but I'm not receiving the data. what am I doing wrong?
C# CODE IN ASP.NET:
public partial class WebForm1 : System.Web.UI.Page
{
SqlConnection conn;
protected void Page_Load(object sender, EventArgs e)
{
StreamReader reader = new StreamReader(Page.Request.InputStream);
String data = reader.ReadToEnd();
}
...
It looks like this post contains the precise code for what you are trying to do:
Fake a form submission with C# WebClient
If you just need the data at Page_Load there isn't a requirement to do this with JavaScript- right?
I personally don't use the XmlHttpRequest object any more. I have abandoned it in favor of using the jQuery AJAX functions. The callback function for a successful post would make it easy to capture the response from the server.
Here is an example of how to do it with jQuery AJAX:
$.ajax(
{
type : 'POST',
url : 'http://localhost:52271/WebForm1.aspx',
dataType : 'json',
data:
{
q:'hello'
},
success : function(data)
{
$('mydiv').text(data.msg).show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown)
{
$('mydiv').text('There was an error.').show(500);
}
}
);
Related
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
I want to call my server asynchronously.
My code is as below:-
function GetSynchronousJSONResponse(url, postData) {
var xmlhttp = null;
if (window.XMLHttpRequest)
xmlhttp = new XMLHttpRequest();
else if (window.ActiveXObject) {
if (new ActiveXObject("Microsoft.XMLHTTP"))
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
else
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
}
xmlhttp.open("POST", url, false);
xmlhttp.send(postData);
var responseText = xmlhttp.responseText;
return responseText;
}
But service call gives "Bad Request" error.
Please help
You forgot to add content type in your request.
please add below line and try again
xmlhttp.setRequestHeader("Content-Type","application/json;charset=utf-8");
function GetSynchronousJSONResponse(URL,postData)
{
$.ajax({
url : URL,
type : "POST",
data : JSON.stringify(postData),//if required
contentType : 'application/json',
success : function(data) {}
})
}
you can Try this .....................
My current code:
Javascript
function pushFunc() {
mediaRecorder.requestData();
console.log(mediaRecorder.state);
mediaRecorder.ondataavailable = function (e) {
console.log("data size: ", e.data.size);
var encodeData = new Blob([e.data], { type: 'video/mp4' });
postBlobData(encodeData);
}
}
function postBlobData(blob) {
var formData = new FormData();
formData.append("blobContent", blob);
var request = new XMLHttpRequest();
request.open("POST", "/Device/Upload");
request.send(formData);
}
ASP.NET
**File: DeviceController.cs**
[HttpPost]
public string Upload(HttpPostedFileBase blobContent)
{
...
// return View();
}
The Java script code gets the blob from Media recorder and tries to post it down to the Controller.
Am i grabbing and posting blobs the way i should?
Should HttpPostedFileBase be used to receive the post request on the server side?
Fiddler Screenshot#1
Fiddler Screenshot#2
Fiddler Screenshot#3
Hi i have a requirement in which i have to check something from struts action class and then send the result back to the browser using ajax call called in a JS fx'.The issue is im not able to hit the action class and console is throwing the following error:
org.apache.struts.action.RequestProcessor processActionCreate No action instance for path /ChangePwdAjax could be created
java.lang.ClassNotFoundException:test.ChangePwdAjaxAction.java
The class is compiled and the package context is valid test.ChangePwdAjaxAction.java
Any ideas what and where im doing it wrong?
Here is what i have written so far.
JS code
function checkError()
{
var valuePassword="test";
var url = "/test/ChangePwdAjax.do?newPass="+valuePassword;
var xmlHTTP = getXMLHTTPRequest();
xmlHTTP.onreadystatechange = function() {
handleResponse(xmlHTTP); }
xmlHTTP.open("GET",url,true);
xmlHTTP.send();
}
function handleResponse(xmlHTTP){
alert("handleResponse");
if (xmlHTTP.readyState == 4 && xmlHTTP.status == 200) {
alert("handleResponse");
var xmlDoc = xmlHTTP.responseXML;
alert(xmlDoc.documentElement.getElementsByTagName("pwdFlag")[0].text);
}
}
function getXMLHTTPRequest(){
alert("getXMLHTTPRequest");
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
}
// IE
else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
else{
alert("XMLHttpRequest is not supported!");
}
}
Action class code
public class ChangePwdAjaxAction extends Action {
public ActionForward execute(final ActionMapping mapping, final ActionForm form,
final HttpServletRequest request,final HttpServletResponse response)
{
System.out.println("----IN--AJAX ACTION----------");
final HttpSession session= request.getSession(false);
if(session==null || session.getAttribute("user_id")==null){
return mapping.findForward("sessionexpired");
}
final String user_id=(String)session.getAttribute("user_id");
try{
final BusinessDelegate busdel=new BusinessDelegate(user_id,session.getId());
String newpwd = (String)request.getParameter("newPass");
boolean b=busdel.checkOldPWd(user_id, newpwd);
//checking return values from bus delegate
response.setContentType("text/xml");
PrintWriter printwriter = response.getWriter();
printwriter.println("<?xml version=\"1.0\"?>");
printwriter.println("<Root>");
if(b)
{
System.err.println("----New password Failed--Y--------");
printwriter.println("<pwdFlag>"+"Y"+"</pwdFlag>");
}
else
{
System.out.println("----New password OK---N-------");
printwriter.println("<pwdFlag>"+"N"+"</pwdFlag>");
}
printwriter.println("</Root>");
}catch(Exception e){
logger.logCommon("Login Action : Login Process in Action : ", "EXCEPTION");
logger.logError(e);
}
return null;
}
}
Struts-config entry
<action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction.java"/>
OOps this had to be
action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction"/>
rather than
action path="/ChangePwdAjax" type="test.ChangePwdAjaxAction.java"/>
I have asp.net application with JavaScript and I want to save in to ms sql DB additional information(TimeStamp) when a button is clicked.
onclick= "functionName();"
the function "functionName()" has another task and I want another function that store the timestamp as well
Write JS as below:
function functionName() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert(xmlhttp.responseText);
}
}
var now = new Date(); // You can also any kind of data using query string
xmlhttp.open("GET", "saveTimespan.aspx?datetime=" + now, true);
xmlhttp.send();
}
Write below code to code behind of saveTimespan.aspx' page as below(remove all markup other thanPage` directory of this page):
protected void Page_Load(object sender, EventArgs e)
{
UpdateTimeStamp();
}
public void UpdateTimeStamp()
{
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "UPDATE TargetTable SET DateTimColumnName = #DateTimColumnName";
cmd.Parameters.AddWithValue("#DateTimColumnName", MyDateTime);
cmd.CommandType = CommandType.Text;
try
{
using (SqlConnection connection = new SqlConnection("YourConnectionString"))
{
cmd.Connection = connection;
connection.Open();
cmd.ExecuteNonQuery();
Response.Write("Data Updated Successfully!");
}
}
catch (Exception ex)
{
//Handle exception
}
}
Try using jQuery ajax, would be easier like
function functionName() {
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
}
Ref: http://api.jquery.com/jQuery.ajax/