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.
Related
I am getting the JSON object back TO the HTML request (I am using GlassFish on localhost just to demo). I am not, however, able to display any of my JSON objects. (I am a rookie when it comes to HTML.)
Here is my attempt at HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"></script>
<title>Dss</title>
<script>
function onSubmit() {
alert(document.getElementById('text').value);
$.ajax({
url: 'rest/dss/acceptInput',
type: 'GET',
dataType: 'jsonP',
data: {'UserInput': document.getElementById('text').value },
statusCode: {
200: function(data) {
alert(data);
$.each( data.items, function(item ) {
alert(item.Type);
$( "<p>" ).attr( "value", item.Type ).appendTo( "#Test" );
});
},
404: function() {
alert("Page NOT found");
}
},
done: function(data) {
alert("NOPE" + data);
$.each( data.items, function(item ) {
alert(item.Type);
$( "<p>" ).attr( "value", item.Type ).appendTo( "#Test" );
});
}
});
alert("at the end");
};
</script>
</head>
<body style="background-color:black;">
<img src="http://i.imgur.com/97.png" alt="DSS_Thumbnail" style="display: inline;width:120px;height:120px;">
<h1 style="display: inline;color:rgb(241,85,50)">Search for details:</h1>
<br>
<input id="text" type="text" name="UserInput" value="Enter search criteria">
<br>
<button id="submit" onclick="onSubmit()" type='button'>Submit</button>
<br><br>
<div id="Test"></div>
</body>
</html>
I run this in the Chrome browser, and the alerts show me the object Object returns within the status code 200. I am not sure HOW to display this information... I thought I had it, but I have tried for a few hours.
After running the HTML I receive these acknowledgements:
Initial acknowledgement of input:
Acknowledgement of finish:
Displaying the object after status code 200 received:
I understand that it is asynchronous which is why I would get them out of order, but what do I do with said object Object?
What do i have to add to the HTML file to display the JSON to the current page? (Or even populate a new page with the information on it?)
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 been trying to convert an HTML form into Json. When I submit the form my alert is just returning an empty array. Any help is greatly appreciated!
Here is the form
<form action="" method="post" name="myForm">
Code (xxxx-xxx):<input type="text" name="drugcode" /> <br/>
<p><input type="submit" onClick='submitform()' /></p>
</form>
And here is the javascript
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<script language ="javascript" type = "text/javascript" >
function submitform() {
var formData = JSON.stringify($("form[name*='myForm']").serializeArray());
alert(formData);
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json",
processData: false
});
}
</script>
All that this is returning is:
[]
EDIT:
It now returns:
[{"name":"code","value":"1234"},{"name":"blah","value":"4321"}]
how would I would I have it return:
{"code":"1234","value":"4321"}
$("#myForm") is not going to match the form for you. # specifies an id. You need to match on the name:
$( "form[name='myForm']" )...
You can also use simple javascript and select the form using
document.querySelector("form[name='myForm']")
or
document.forms[0]
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" />
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.