I have a form, which can either be submitted via AJAX or usual way, working with the submit button. The Ajax part is here:
parentForm.onsubmit = function(e) { // e represents trigering event
if(srteValidateMode()){ // works only in WYSIWYG mode
var outputString = srteEditArea.innerHTML; // first we prepare the text output data
outputString = outputString
.replace(/<(\/?)strong>/gi, '<$1b>') // unify output tags for all browsers -> B I P (instead of strong em div)
.replace(/<(\/?)em>/gi, '<$1i>')
.replace(/<(\/?)br>/gi, '<p>')
.replace(/<(\/?)div/gi, '<$1p');
document.getElementById('simpleRTEoutput').value=outputString; // pass output string to hidden form field
if (srteAjaxSubmit) { // ajax version - filling FormData
e.preventDefault(); // canceling the submit function - we will call it with Ajax
var srteFormData = new FormData(e.target); // getting form data from submitted form
var ajaxRequest = new XMLHttpRequest(); // now going to invoke AJAX
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
srteShowInfo(ajaxRequest.responseText); // return message and display as info window
}
}
ajaxRequest.open("POST", e.target.action); // getting target script from form action
ajaxRequest.send(srteFormData); // send FormData
}
else { // Standard submit
return true; // true = standard submit will proceed (works ok)
}
}
else {return false;} // on false return form will not be submitted
};
It works fine. Now I want to add redirection functionality - clicking on another (non submit) button with some onclick function to SAVE (do the predefined submit) AND redirect. I have such Idea (not tested), but not sure it this might work especially in the AJAX part.
function srteSubmitForm(redirectTo) {
if (srteAjaxSubmit) { // redirect when submitted via Ajax Call
parentForm.submit(); // save form data
window.location.href = redirectTo; // change location - does it wait for previous function ?
}
else {
parentForm.action = parentForm.action + '?redirect=' + redirectTo; // rest handled by target PHP
parentForm.submit();
}
}
Button in HTML then would look like:
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=A\")" value="Redirect A">
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=B\")" value="Redirect B">
<input type="button" onclick="srteSubmitForm(\"somepage.php?page=C\")" value="Redirect C">
I am not sure, if I need to wait for the AJAX to be finished somehow before redirect ? Or any other way how redirect after the submit?
no jQuery solutions, please.
Thanks, Jan
Why not add a 'callback' parameter to your submit method that gets called when the call completes.
parentForm.submit(function(status){
//The call completed, you can display a confirm message 'Form submitted,
//now redirecting' (because it's not nice to redirect without warning ;)
window.location.href = redirectTo;
});
And in your submit:
ajaxRequest.onreadystatechange = function () {
if (ajaxRequest.readyState == 4 && ajaxRequest.status == 200) {
srteShowInfo(ajaxRequest.responseText);
if(callback instanceof Function) callback(ajaxRequest.responseText);
}
}
Related
I have to make a chat with JSP, AJAX and Java and I have a problem: when I try to use my variable to store value of a input text, this variable is null.
If I add 'action' property to the form, the variable 'textParam' will have the value of the input text, but, if I do that I have to redirect with action to a page and I don't what that.
I need to process something bigger in the JSP page and then to reload in the HTML page (which is a JSP page) (the reload part is not on actual probem).
How I can make to populate 'textParam' with the input text value when I press the button?
PS: I need to make it with pure javascript, not with some libraries :)
The JSP which have to process is:
String textParam = request.getParameter("chatMessage");
System.out.println("textParam = " + textParam);
My form it look like that:
<form id="frmmain" name="frmmain" onsubmit="return blockSubmit();">
<input type="text" id="chatMessage" name="chatMessage" style="width: 447px;" />
<input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onclick="sendChatText();" />
</form>
The .js file it's this:
var request = getXmlHttpRequestObject();
var response = getXmlHttpRequestObject();
var lastMessage = 0;
var mTimer;
function getXmlHttpRequestObject() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if(window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function sendChatText() {
if(document.getElementById('chatMessage').value == '') {
alert("You have not entered a message");
return;
}
if (request.readyState == 4 || request.readyState == 0) {
request.open("POST", 'getChat2.jsp?chat=1&last=' + lastMessage, true);
request.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
request.onreadystatechange = handleSendChat;
var param = 'message=' + document.getElementById('chatMessage').value;
param += '&chat=1';
request.send(param);
document.getElementById('chatMessage').value = '';
}
}
function handleSendChat() {
clearInterval(mTimer);
getChatText();
}
function blockSubmit() {
sendChatText();
return false;
}
The problem is here:
String textParam = request.getParameter("chatMessage");
I was trying to get 'chatMessage' parameter, which it was only the name of the input. The solve is to get 'message' param which it was defined and requested in js:
String textParam = request.getParameter("message");
My problem is when the data is submitted and saved using ajax it gives the response text and after that it echo the whole form again.
example:
this is a form
submit button save button
When response received from ajax the page looks like this..
this is a form
ajax response..
this form again
submit button save button
submit button save button
When this button is called
<div id="output"></div>
<button type="button" onClick="save()">Save to drafts</button>
it calls an ajax function to execute
function save(){
var save = new XMLHttpRequest;
var url = "panel.php";
var name = document.getElementById("name").value;
var page = document.getElementById("page").value;
var cont = document.getElementById("cont").value;
var send = "name="+name+"&page="+page+"&cont="+cont+"&call=yes";
save.open("POST", url, true);
save.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
save.onreadystatechange = function(){
if(save.readyState == 4 && save.status == 200){
var output = save.responseText;
document.getElementById("output").innerHTML = output;
}
}
save.send(send);
document.getElementById("output").innerHTML = "saving.... Please wait..";
}
My php script just echo a string saved or not saved.
I'm guessing panel.php is also the page that has the form in the first place.
Make sure you die() after outputting your AJAX response, otherwise it will continue happily along outputting anything else on the page - in this case, your form.
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();
I have a form on my site that when submitted takes the user from Page1.html to Page2.html.
I would like to display a message between the form being submitted and "Page2 loading".
Can someone provide me with an example of this?
If your form submit data via ajax then you could try something this:
$('form#myform').submit(function(e) {
e.preventDefault();
$('#message').html('Sending....'); // #message may be a div that contains msg
$ajax({
url: 'url_to_script',
data: 'your_data',
success: function(res) {
// when submit data successfully then page reload
window.location = 'page2.html'
}
});
});
What you're looking to do can't be done by standard form submission.
You'll want to submit the form using ajax, and display a "Please wait" message while you are waiting for a response. Once the response is received and validated to be OK, you can then redirect the user to the page you now call page2.
The easiest way to submit a form via ajax is to serialize it to a string and pass it along. Then, you'll need a page to process the received data, and return an OK or and ERR.
The JS will then need to decipher next action.
This is not tested, but copied and pasted from various working projects.
You'll need to download and include the json2.js project.
page1
<div id='pleaseWait'>Please Wait...</div>
<form id="theForm" onsubmit="doAjaxSubmit();">
<input type='text' name='age' id='age' />
<input type='submit' value='submit'>
</form>
<script type="text/javascript">
function doAjaxSubmit(){
var j = JSON.stringify($('#theForm').serializeObject());
$('#pleaseWait').slideDown('fast');
$.post('processor.php?j=' + encodeURIComponent(j), function(obj){
if(obj.status=='OK'){
window.location='page2.php';
}else{
$('#pleaseWait').slideUp('fast');
alert('Error: ' + obj.msg);
}
}, 'json');
return(false);
}
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
</script>
processor.php
<?php
$j=json_decode($_POST['j'], true);
if ((int)$j['age']<=0 || (int)$j['age']>120){
$result = array('status'=>'ERR', 'msg'=>'Please Enter Age');
}else{
//Do stuff with the data. Calculate, write to database, etc.
$result = array('status'=>'OK');
}
die(json_encode($result));
?>
This is essentially very similar to the answer below (by #thecodeparadox), but my example shows how to pass the entire for without having to manually construct your data object, shows how to validate on the PHP side as well as return the appropriate JSON data to either redirect the user, or to display an error, and uses animations to display the message.
Here's how the situation looks :
I have a couple simple forms
<form action='settings.php' method='post'>
<input type='hidden' name='setting' value='value1'>
<input type='submit' value='Value1'>
</form>
Other small forms close to it have value2, value3, ... for the specific setting1, etc.
Now, I have all these forms placed on the settings.php subpage, but I'd also like to have copies of one or two of them on the index.php subpage (for ease of access, as they are in certain situations rather frequently used).
Thing is I do not want those forms based on the index.php to redirect me in any way to settings.php, just post the hidden value to alter settings and that's all.
How can I do this with JS ?
Cheers
Yes, you could use an ajax call to send a request to the settings.php file. You'd probably want that PHP code to return something that the JavaScript can use to know if the request was successful or not (for example, using JSON instead of HTML).
Here is an ajax getData function.
function getData(dataSource, targetDiv){
var XMLHttpRequestObject = false;
if (window.XMLHttpRequest) {
XMLHttpRequestObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
XMLHttpRequestObject = new
ActiveXObject("Microsoft.XMLHTTP");
}
if(XMLHttpRequestObject) {
var obj = document.getElementById(targetDiv);
XMLHttpRequestObject.open("GET", "settings.php?form="+dataSource+"&t="+new Date().getTime());
XMLHttpRequestObject.onreadystatechange = function()
{
if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200) {
obj.innerHTML = XMLHttpRequestObject.responseText;
}
}
XMLHttpRequestObject.send(null);
}
}
use this function to send the form to your setting.php file which should return confirmation message to index.php(inside targetDiv).
Parameters of the function
1) dataSource - is the variable value that you send to settings.php
2) targetDiv - is the div on index php that with display the response from settings.php
Hope it makes sense.