I've written a Chrome browser extension that uses Ajax to post data to an MVC3 controller. To make sure that the controller code works, I first wrote a Razor web page to prototype the ajax code. This code works within the web page, JSON model binding an all. I published it to an IIS7 server complete with DNS host and domain name. The code still works on the test page.
function addUrl()
{
$('#res').html('Adding...');
var myData = { url: $('#urlDiv').html(), comments: $('#c1').val() };
$.ajax(
{
url: 'http://hostname.domainname/ControllerName/AddUrl',
type: "post",
dataType: "json",
data:JSON.stringify(myData),
contentType: "application/json; charset=utf-8",
success: function (result)
{
$('#res').html(result);
},
error: function()
{
$('#res').html('An error occurred');
}
}
);
};
I copied this jQuery function into the Chrome JavaScript file and called it from a pop-up window via a conventional form button.
<body onload="buildPopupDom();">
<form>
<h2>Add URL</h2>
<div id='urlDiv'></div>
<p>Comments<br /><textarea id="c1" cols="80" rows="3"></textarea></p>
<p><input type="button" value="Save" id="s1" onclick="addUrl();" /> <input type="button" value="Close" onclick="javascript:window.close();" /></p>
</form>
For some reason posts from the Chrome extension incur a 404 error and it occurred to me that that some MVC3 XSS protection or similar is blocking the post - or perhaps something in IIS7 (UrlScan is not installed).
In order to make cross domain XHR calls corresponding domain permissions need to be declared in the manifest.
Related
I need an anchor tag or button that sends a POST to a URL but doesn't navigate to anywhere.
This might not comply with current standards, but it works in Chrome.
<!DOCTYPE html>
<iframe style="display:none;" name="some"></iframe>
<form method="POST" target="some">
<button class="btn" style="margin:0px 10px 15px 0px;" type="submit"
formaction="http://www.example.org:1234/test?P1=X">Test</button>
</form>
In order to post the data without navigating to another page or refreshing the same page, you need to use Ajax.
From your code, I assume you are using jQuery. In jQuery, there are functions that allow to implement Ajax easily.
I will add a sample code below for your reference.
$("#myLink").click(function(event) {
event.preventDefault();
var url = "http://example.com"; //The url/uri where you want to post the data to
var data = {field1: "data1", field2: "data2"}; //Your data
$.post(url, data, function(data, status) {
//Data and status from server after posting your data
console.log(data);
console.log(status);
});
});
And your a tag will remain the same.
Send
i have a form, i am asking customer to enter few details,
<form id="redirectForm" accept-charset="UTF-8" method="post" action="https://test.test.com//api/v1/order/create" >
customerName: <input type="text" name="customerName" value=<%=customerName %> />
customerEmail: <input type="text" name="customerEmail" value=<%=customerEmail %> /><br><br>
customerPhone: <input type="text" name="customerPhone" value=<%=customerPhone %> /><br><br>
signature:<input type="text" name="signature" value=<%=signature %> />
On submit page redirect according to action of form and display a JSON type response(status + payment link).
response is like:
{"status":"OK","paymentLink":"https:\/\/test.test.com\/billpay\/order\/3ackwtoyn7oks4416fomn"}
Help me out with this
i am working in jsp.
thank you in advance.
Since this look like a simple Webservice answer (not a full HTML page), I would use Ajax to send the form and manage the response.
With JQuery, this is easy using $.ajax
$.ajax({
url: //the URL
data: //the form value
method: //GET/POST
success: function(response){
//decode the JSON response...
var url = $.parseJSON(response).paymentLink;
//then redirect / not sure since this could be cross-domain...
window.loacation = url;
},
error: function(error){
...
}
})
The only think is that the form should not be send with a submit input, you need to link a button to a function doing this Ajax call.
This can be done without JQuery but I can write this from memory ;)
If you can edit the JSP creating the response, you could generate an HTML to return the value directly.
<html>
<head>
<script>
window.location.href = '${paymentLink}';
</script>
</head>
<body>
Redirection ...
<br>If nothing happend, you can <a href='${paymentLink}'>click here</a> to be redirected.
</body>
</html>
Where ${paymentLink} is a EL that will print the value of this variable (well the name it has on the server) to complete the script with the URL.
Once it is received by the client, it will be executed.
Of course, this will not be cross-domain on every browser. If this is not, you will need to provide the link to the user with <a href='${paymentLink}'>Redirection</a> itsefl.
Try this...
while submitting the form write one JS function and get the URL value.
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script type="text/javascript">
function check(){
//here you have to get value using element name or id (val1,val2,val3)
$.ajax({
type:'GET',
data: {customerName: val1, customerEmail: val2,customerPhone: val3},
url:'https://test.test.com/billpay/order/3ackwtoyn7oks4416fomn',// Replace with Your Exact URL
success: function(response){
alert(response);
var json = JSON.parse(response);
var values = json.values;
for(var i in values)
{
var New_redirect = values[i].address;
alert(values[i].address);
}
window.loacation=New_redirect;
}
});
})
}
</script>
</head>
i think you are looking for response message and redirecting to somewhere
if so you can use the following code
if(condition)
{
response.sendRedirect("urpage.jsp");
}
or
if(condition)
{
request.getRequestDispacher("page.jsp");//enter the name of page you want to redirect inside ""
}
I've created a simple web service using asp.net and hosted on my machine's IIS server. I am trying to call this web service from plain html page without using Asp.net. The problem is that I am not getting response. Here is my code below :
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Calling Classic Web Services with jQuery</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("a#SayHello").click(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
data: '{firstName:10,lastName:15}',
// url: 'Service.asmx/SayHello',
url: 'http://192.168.1.20/MyService/Service.asmx/SayHello',
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function(response) {
alert(response.d); //getting the Response from JSON
},
failure: function(msg) {
alert(msg);
}
});
});
});
</script>
</head>
<body>
<input id="name" /><a id="SayHello" href="#">Greetings!</a>
</body>
</html>
Can anybody please help me where I am going wrong in this code..?? If I run this in ASP.Net environment, it works perfectly. But if I host this, then it doesn't work. Please help me...!!
Are you sure the web service is responding in JSON format? It usually answers in XML. Also your <script> block should go in the <body> and not in the <head>.
if you have hosted the web service on the same IIS, then change 192.168.1.20 to localhost and then try..
New to ajax and sorry for asking such a basic question. I am using ajax:
to submit a form (written in python)
to conduct some calculation and generate output page, and
to redirect the browser to the output page
Currently, Steps 1 and 2 are done, but when the browser tries to redirect, I got a 405 error. I appreciate any suggestions.
HTML form
<form method="post" id="form1">File to upload:
<input type="file" id="upfile1" name="upfile" class="required input_button" accept=".csv" />
<input class="submit_button" type="button" value="Submit" />Upload the file!
</form>
JS code
$('.submit_button').click(function () {
var form_data = new FormData();
$.each($('input[name^="upfile"]')[0].files, function (i, file) {
form_data.append('file-' + i, file);
});
$.ajax({
type: "post",
url: "/geneec_batchoutput.html", ///////NOTE 1/////////
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function () {
window.location = '/geneec_batchoutput.html'; ///////NOTE 2/////////
},
error: function (data) {
console.log('error');
}
});
});
NOTE 1
Form firebug, I can tell the calculations have been finished and the output page is generated.
NOTE 2
Here is the place I got 405 error. So my guess is ajax did not redirect the browser to the "correct" output page, instead it let the browser go to a generic one. So without data support, I got 405 error.
So it seems like my question is how to redirect the browser to the output page generated in ###note 1 at location ###note 2.
update
I have attached a "working" scenario, but this is not the real ajax approach, since I use .submit() to send the form.
html form
<form method="post" id="form1" enctype="multipart/form-data" action=geneec_batchoutput.html>File to upload:
<input type="file" id="upfile1" name="upfile" class="required input_button" accept=".csv" />
<input class="submit_button" type="submit" value="Submit" />Upload the file!
</form>
JS code
form.submit();
$.ajax({
type: "post",
url: "/geneec_batchoutput.html",
success: function () {
window.location = '/geneec_batchoutput.html';
}
});
Update 2
I tried to check the content of url by posting it to the console. It looks like the url has everything I need, which is the output page. So temporally I use $("body").html(url); to replace current page content. But the url is still the /geneec_batchinput.html. Is there a way to update the url as well?
$.ajax({
type: "post",
url: "/geneec_batchoutput.html",
data: form_data,
cache: false,
contentType: false,
processData: false,
success: function(url) {
console.log(url)
$("body").html(url);
},
error: function(data) {
alert('error')
}
});
Thanks!
It looks like the location redirect is getting called as a POST request because it's inside the submit action. Try tweaking your submit handler like so:
$('.submit_button').click(function (event) {
event.preventDefault();
// carry on...
so that you can use event.preventDefault to avoid needing to return something from the submit event.
Update:
This may be it. Using your original code:
$('.submit_button').click(function (event) {
event.preventDefault();
// .. blah blah ..
$.ajax({
type: "post",
url: "/geneec_batchoutput.html", ///////NOTE 1/////////
// .. blah blah ..
success: function () {
window.location = '/geneec_batchoutput.html'; ///////NOTE 2/////////
},
error: function (data) {
console.log('error');
}
});
retun false;
});
Because it's asynchronous, the outer event handler is ending before the location change is issued in the success callback function. I thought the preventDefault would avoid the need to return false, but other similar questions suggest not.
I am trying to send an http DELETE method to a URI. After realizing that I cannot do this with plain old html forms, I was told to use jQuery.ajax. I found a few posts on it and this is the code I found that will supposedly do it:
<script type="text/javascript">
$.ajax({
url: '/groups/dissolve/$org_ID',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
</script>
Please bear with me as I have not used jQuery before. What I am trying to do is replace my html form with this code above but I don't know where to start. How do I place a button in there as I would in a regular form? Thanks and please forgive my ignorance!
Something like:
$("form").on("submit", function() {
$.ajax({
url: '/groups/dissolve/$org_ID',
type: 'DELETE',
success: function(result) {
// Do something with the result
}
});
});
This will bind the AJAX method to the submit action of your form.
Another option is to use method override. This allows you to specify the method (GET, POST, PUT, DELETE) in a query string parameter or a hidden field in your form. You will need to check with your specific language and web framework, but most support this in some variation.
<input type="hidden" name="_method" value="DELETE" />