Need to post form Asynchronously without using jquery in MVC4 - javascript

I am working in MVC from last one year and in most of cases i am using JQuery ajax calling for Calling controller method. Now my requirement is that I have a button(Add User) on page on its click i open a Modal popup on which i need to partial view and 2 buttons(Save and Cancel).
After filling form i click on Save button .Now i want to MVC functionality and want to post data using Asynchronous Method of Ajax form. After save i want to reload Partial view with empty form.
Can someone guide me
Thanks in advance.

Youre looking for a javascript only kind of call?
function submitForm()
{
var xhr;
try { xhr = new ActiveXObject('Msxml2.XMLHTTP'); }
catch (e)
{
try { xhr = new ActiveXObject('Microsoft.XMLHTTP'); }
catch (e2)
{
try { xhr = new XMLHttpRequest(); }
catch (e3) { xhr = false; }
}
}
xhr.onreadystatechange = function()
{
if(xhr.readyState == 4)
{
if(xhr.status == 200)
document.ajax.dyn="Received:" + xhr.responseText;
else
document.ajax.dyn="Error code " + xhr.status;
}
};
xhr.open(GET, "data.txt", true);
xhr.send(null);
}
and your HTML:
<FORM method="POST" name="ajax" action="controller/action">
<INPUT type="BUTTON" value="Submit" ONCLICK="submitForm()">
<INPUT type="text" name="dyn" value="">
</FORM>

Related

How to submit form without reloading page, without jQuery?

I have form as follows, it require to sent an action to my java Servlet to do an update to the database.
How do I submit the form without the page get reloaded here?
Currently with action="myServlet" it keep direct me to a new page. And if I remove the action to myServlet, the input is not added to my database.
<form name="detailsForm" method="post" action="myServlet"
onsubmit="return submitFormAjax()">
name: <input type="text" name="name" id="name"/> <br/>
<input type="submit" name="add" value="Add" />
</form>
In the view of my Java servlet, request.getParameter will look for the name and proceed to add it into my db.
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
if (request.getParameter("add") != null) {
try {
Table.insert(name);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
In my JavaScript part, I have a submitFormAjax function
function submitFormAjax()
{
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
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); // Here is the response
}
var id = document.getElementById("name").innerHTML;
xmlhttp.open("POST","/myServlet",true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("name=" + name);
}
A similar question was asked here
Submit form without reloading page
Basically, do "return false" after invoking the function. Something like this should work:
<form name="detailsForm"
method="post"
action="myServlet"
onsubmit="submitFormAjax();
return false;"
>
This is how I used to implement Ajax in JS without JQuery. As am a PHP and JS guy I cant possibly help you with Java Servlet side but yes heres my little help from JS side. This given example is a working example.See if it helps you.
// HTML side
<form name="detailsForm" method="post" onsubmit="OnSubmit(e)">
// THE JS
function _(x){
return document.getElementById(x);
}
function ajaxObj( meth, url )
{
var x = false;
if(window.XMLHttpRequest)
x = new XMLHttpRequest();
else if (window.ActiveXObject)
x = new ActiveXObject("Microsoft.XMLHTTP");
x.open( meth, url, true );
x.setRequestHeader("Content-type", "application/json");
return x;
}
function ajaxReturn(x){
if(x.readyState == 4 && x.status == 200){
return true;
}
}
function OnSubmit(e) // call this function on submit
{
e.preventDefault();
var username = _("name").value;
if (username == "")
{
alert("Fill out the form first");
}
else
{
var all = {"username":username};
all = JSON.stringify(all);
var url = "Myservlet";
var ajax = ajaxObj("POST", url);
ajax.onreadystatechange = function()
{
if(ajaxReturn(ajax) == true)
{
// The output text sent from your Java side in response
alert( ajax.responseText );
}
}
//ajax.send("user="+username+");
ajax.send(all);
}
}
Thanks
Change the code in form
onsubmit="submitFormAjax(event)"
Change your JS code
function submitFormAjax(e)
{
e.preventDefault();
var xmlhttp;
if (window.XMLHttpRequest) {
// code for modern browsers
xmlhttp = new XMLHttpRequest();
}
......
................
...............
return false; //at last line

how to call External URL as getJSON when i submit Form Button

Please help I tried everything cant get this simple code running
this is my html
HTML form:
<form id="searchForm" method="GET" action="" class="hpi check">
<label for="licencePlate" title="Enter vehicle registration"> </label>
<input id="licencePlate" maxlength="9" name="licencePlate" type="text" value="mt09nks" />
<button class="btn btn-primary" type="submit" id="searchButton">Click to Check</button>
</form>
Java script:
If u put the Json code in document.ready function it works fine and return the data on page refresh. but when i try to call it on a button click it does not return anything.
var getJSON = function(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.responseType = 'json';
xhr.onload = function() {
var status = xhr.status;
if (status == 200) {
resolve(xhr.response);
} else {
reject(status);
}
};
xhr.send();
});
};
$('#searchButton').click(function(event) {
getJSON('https://dvlasearch.appspot.com/DvlaSearch?licencePlate=mt09cna&apikey=DvlaSearchDemoAccount').then(function(json) {
alert('Your Json result is: ' + json.make);
result.innerText = json.make; // display
}, function(status) { //error detection....
alert('Something went wrong.');
});
});
The above javascript works fine when I run it in document.ready but when i use to call it with button click even it gives alert message - Something went wrong.
I m just using a demo from DVLA to get the details. Which i will use it display.
A user will input the vehicle registration number and search the car details.
but for example only mt09nks will work. plz guide me where I am making mistake.
Thanks in Advance.
The above code I found in Stackoverflow and it works fine when called directly but doesnt work when i call after i click a button.
Please check where I am making mistake.
$.getJSON
should be
getJSON(
I think you want to call the method that you have created right ?
You seem to be calling the method that is provided by jQuery

Javascript - Posting a form with AJAX and getting return values

I have now got everything to post correctly but this script keeps loading it into a new page. Is it something to do with the way my php file returns it? "echo(json_encode($return_receipt));"
<script>
// Get XML HTTP Type
function get_XmlHttp() {
var xmlHttp = null;
if(window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
}else if(window.ActiveXObject) {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
return xmlHttp;
}
function ajaxSuccess () {
alert(this.responseText);
}
function ajaxrequest(oFormElement,tagID) {
//Get The Correct XMLHTTP Object
var request = new XMLHttpRequest();
request.onload = ajaxSuccess;
request.open(oFormElement.method, oFormElement.action, true);
//request.setRequestHeader("Content-type","application/x-www-form-urlencoded");
request.send(new FormData(oFormElement));
}
</script>
you have two easy options..
1.you can use jquery ajax method... or
2. javascript form submission without loading the page by targetting the form to the hidden inline frame
here i'm using it for image upload image name without hitting submit button and save the data to the database table without reloading the page.. edit it according to your convenience.
function upload(img)//Javascript function
{
var types = /\.jpg|\.gif|\.jpeg/i;
var filename = img.value;
if (filename.search(types) == -1) {
alert("Select only images ( jpg or gif or jpeg format)");
img.form.reset();
return false;
}
img.form.action = 'upload-picture.php';
img.form.target = 'iframe';
img.form.submit();
return true;
}
// here is iframe on the same page
<iframe name="iframe" id="u_iframe" style="display:none;"></iframe>
<input type="file" name="picture" id="picture" onchange="return upload(this);" />

window.location.href using GET when I need POST

I have the following script, a few lines up from the bottom I have a window.location.href which posts the reults from my form though the address bar. This is very messy and I would like to use POST instead of GET, any ideas anyone ?
<script language="javascript">
function OnChangedUsername()
{
if(document.signup.newuserid.value == "")
{
document.signup.btnCheckAvailability.disabled = true;
}
else
{
document.signup.btnCheckAvailability.disabled = false;
}
}
function createRequestObject() {
var ro;
var browser = navigator.appName;
if(browser == "Microsoft Internet Explorer"){
ro = new ActiveXObject("Microsoft.XMLHTTP");
}else{
ro = new XMLHttpRequest();
}
return ro;
}
var http = createRequestObject();
function sndReq() {
http.open('get', 'password_check.asp?emailaddress=<%Response.Write(emailaddress)%>&check=<%Response.Write(check)%>&password_check='+document.signup.newuserid.value);
http.onreadystatechange = handleResponse;
http.send(null);
}
function handleResponse() {
if(http.readyState == 4){
var response = http.responseText;
var update = new Array();
if(response.indexOf('|' != -1)) {
update = response.split('|');
document.getElementById("username_chk").innerHTML = update[0];
if(document.getElementById("username_chk").innerHTML == "Ok") {
window.location.href='detailsupdate.asp?username=<%Response.Write(sUsername)%>&check=<%Response.Write(check)%>&EmailAddress='+document.signup.EmailAddress.value+'&Address='+document.signup.Address.value+'&Address1='+document.signup.Address1.value+'&Address2='+document.signup.Address2.value+'&City='+document.signup.City.value+'&PostalCode='+document.signup.PostalCode.value+'&Country='+document.signup.Country.value+'&WorkPhone='+document.signup.WorkPhone.value+'&HomePhone='+document.signup.HomePhone.value+'&MobilePhone='+document.signup.MobilePhone.value+'&FaxNumber='+document.signup.FaxNumber.value+'&AlternativePhone='+document.signup.AlternativePhone.value+'&OO='+document.signup.OO.checked+'&Workshop='+document.signup.Workshop.checked+'&Raised='+document.signup.Raised.checked+'&Ground='+document.signup.Ground.checked+'&pd='+document.signup.newuserid.value+'&Tram='+document.signup.Tram.checked;
}
}
}
}
</script>
The only way to make a POST request with the response rendered directly into the browser window is to use a form (which you generate with DOM) and submit it (which you can likewise do through DOM).
The alternative is to use XMLHttpRequest (or some other Ajax technique) and render the response with DOM.
There is no need to pass form data as GET data. You can specify the method as POST.
<form action="script.asp" method="post">
...
<input type="submit" value="submit">
</form>
You also should not be using window.location.href. This is very ugly. When you submit the form (click the submit button) it will POST your form data to script.asp.
Another way to submit your form is to submit it via DOM. document.forms[0].submit();

Popup preview of a textarea using a PHP function

I'd like to make a popup preview of a textarea, using a PHP function inside the popup.
Let's say you type "Hello world" in the textarea, then you click "preview" and you get your text converted to "Hey you" by a PHP function in a popup (of course the function is not that simple, that's the reason why I can't adapt this in pure javascript).
Is it possible to do so ?
I know it could easily send the form to an intermediate page, but I must keep the form in background... that's why I need a quick preview on fly.
I did the following:
function PreviewMe() {
var newWin = window.open("", "_blank");
newWin.document.write("<html><body>"+document.getElementById('myText').value+"</body></html>");
newWin.document.close();
}
and
<textarea id="myText" ... />
<input type="submit" ... onclick="PreviewMe();">
Obviously it works without reformatting anything, so how to reformat this result in the popup please ?
Would it be possible (and mayber a better option) to use XMLHttpRequest ?
Thx !
Yes , you should use an XHR request to send data to a script which will return you data to be manipulated on the client side.
Thanks, it was by far easier in the end.
In case it might help others, here is what I've done.
Js function became :
function PreviewMe() {
var xhr = null;
if (window.XMLHttpRequest || window.ActiveXObject) {
if (window.ActiveXObject) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
} else {
xhr = new XMLHttpRequest();
}
} else {
alert("XMLHTTPRequest not supported...");
return;
}
xhr.open("POST", "page.php", true);
xhr.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {
if (xhr.readyState == 4 && (xhr.status == 200 || xhr.status == 0)) {
document.getElementById('show').innerHTML = xhr.responseText;
}
};
xhr.send("var="+document.getElementById('myText').value+"");
return;
}
Of course page.php includes my PHP function, show is the id of the div where the result is printed.

Categories