How to save textarea data when click outside the textarea using ajax - javascript

I am using froala editor and i want text in text area of editor saved when user clicks outside that textarea using Ajax i am new in ajax id of content editor is #id_content
This is my form part in django
<form method="POST" id="froala_form" class="PageForm _inputHolder">
{% csrf_token %}
<div class="_alignRight posR _saveBTNOut">
<button type="submit" class="_btn btnPrimery">Save as Draft</button>
</div>
</form>
This is what i have tried but not getting any proper logic
function loadDoc(){
var xhttp=new XMLHttpRequest();
xhttp.onreadystatechange=function{
if(this.readyState==4 && this.status==200){
var x = document.getElementById("id_content");
x.addEventListener("click", ajaxsavefunc);
}
};
xhttp.open("GET",'url', true);
xhttp.send();
}
function ajaxsavefunc(xhttp) {
document.getElementById("froala_form").innerHTML = editor.html.get()
}

This is a example of how to use blur(when user click outside of field) in Jquery.
Basically this example will return a alert with the value of input when user click in the field and click out of the field.
<form method="post" action="" >
<input type="text" id="test" value="123">
<input type="submit">
</form>
$(function () {
$('#test').blur(function (e) {
e.preventDefault();
var x = document.getElementById("test").value;
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: {input: x},
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
});
});

Related

form validation through javascript - error alert coming but saving the data

here I am comparing the location name whether its already entered or not, In my code I am getting alert when I click submit button but also data submitted. onchange function not working as I expected, can anyone help me how stop the data not submitting when I get alert?
When submitting time validation should be done, why because in our test server we are getting some delay after click button, so only data submitting after alert also. do you have any idea on this? Thanks in advance
<form class="form-inline" id="desgForm" accept-charset="UTF-8" method="post" action="../locationSubmit.htm" enctype="multipart/form-data">
<input type="text" id="locationName" autocomplete="off" name="locationName" class="form-control validate[required]" onchange="desgCheck();" onkeyup="firstToUpperCase1();" value="">
<button type="submit" class="btn btn-primary" >Save</button>
</form>
Javascript:
<script>
function desgCheck()
{
var locationName = document.getElementById('locationName').value;
$.ajax({
type: "POST",
url: "../designation/locationName.htm",
data: {
locationName: locationName
},
dataType: "text",
success: function (data)
{
if ($.trim(data) !== 'Data available')
{
alert("This Location already exist!!");
document.getElementById("locationName").value = "";
return false;
}
},
error: function (error) {
document.getElementById("locationName").value = "";
}
});
}
function firstToUpperCase1() {
var str = document.getElementById("locationName").value;
var a = str.toUpperCase();
$("#locationName").val(a);
}
jQuery("#desgForm").validationEngine();
</script>

jQuery Ajax POST save delete submit

Here is my code
<form method="post" role="form" id="form" enctype="multipart/form-data" autocomplete="off">
<input type="submit" id="save" name="save" value="Simpan Data Client" class="btn" style="font-size:0.7em; letter-spacing:1px; color:#666666" /> //For save
<input type="submit" id="delete" name="delete" value="Delete Client" class="btn-delete" style="font-size:0.7em; letter-spacing:1px; color:#666666; padding:8px 15px" /> //For Delete
</form>
<script type="text/javascript">
$("#form").on("submit",function (e)
{
e.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax(
{
url:'Master/Database/Client/RunClient.php',
type: 'POST',
data: formData,
contentType: false,
enctype: 'multipart/form-data',
processData: false,
beforeSend:function()
{
document.getElementById("loading").style.display = "";
},
complete:function()
{
//document.getElementById("loading").style.display = "none";
},
success:function(result)
{
document.getElementById("info").innerHTML = result;
var n = result.search("error");
if(n < 0) /*document.getElementById("form").reset();*/ $(".input").val('');
}
});
});
</script>
I can get all data from inside my form except from Input type submit i make.
I can't use isset($_POST["save"]) and isset($_POST["delete"]) at my RunClient.php
Create separate function for a submit and pass "submit type" depending on what button is clicked;
$('#save').click(function() {
submitForm('save');
});
$('#delete').click(function() {
submitForm('delete');
});
function submitForm(submittype) {
var formData = new FormData();
//push your form data to formData and add the submittype
formData['type'] = submittype
}
in your php file
$submittype = $_POST['type']; // 'save' or 'delete'
if($submittype == 'save') {
//do save action
}
if($submittype == 'delete') {
//do delete action
}
I use to avoid submit inputs and change by buttons.
<button type="button" id="save">SUBMIT</button> //For save
<script type="text/javascript">
$("#save").on("click",function (e)
{
});
</script>
So, if anyone deativates javscript form will not submit.
And you can send the data like this:
data: {
foo: 'var'
foo2: 5
},
EDIT. Sorry missunderstood your question.
Just control with javascript what button is clicked and assign a value with a hidden field.
'$("#form").on("submit",function (e)' replace the function with
$("#save").click(function() {
});
$("#delete").click(function() {
});

Custom made google form opens another tab on submit

I have made a custom google form and using google spreadsheet as my database.
But on clicking the submit button on the form the same page opens in a new tab
and the previous page text boxes have the data that the user has entered .
The custom form code is :
<form action="" target="hidden_iframe" method="POST" id="mG61Hd" onsubmit="submitted=true;">
<h5>Name</h5>
<input type="text" id ="_name" name="name">
<h5>emailaddress</h5>
<input type="text" id="_email" name="email">
<h5>message</h5>
<textarea name="entry.839337160" id ="_message"></textarea>
<button class="btn btn-lg btn-warning" onclick="postContactToGoogle()">Send</button>
</form>
The JavaScript code is :
function postContactToGoogle() {
var name = $('#_name').val();
var email = $('#_email').val();
var message = $('#_message').val();
validate();
if(validate=true)
{
$.ajax({
url: "https://docs.google.com/forms/d/1sKGYnZfwEC_3sQvsjjx57swxLxdHMHPBC89s5C72x5s/formResponse",
data: { "entry.2005620554": name,
"entry.1045781291": email, "entry.839337160": message },
type: "POST",
dataType: "xml",
statusCode: {
0: function () {
swal("Heyy there","Thank You for your feedback!","success");
$('#_name').val('');
$('#_email').val('');
$('#_message').val('');
window.setTimeout(function(){location.reload()},4000)
},
200: function () {
swal("Heyy there","Thank You for your feedback!","success");
$('#_name').val('');
$('#_email').val('');
$('#_message').val('');
window.setTimeout(function(){location.reload()},4000)
}
}
});
}
}
function validateEmail(email) {
var re = /^(([^<>()[\]\\.,;:\s#\"]+(\.[^<>()[\]\\.,;:\s#\"]+)*)
(\".+\"))#((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA
Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
return re.test(email);
}
function validate() {
var email = $('#_email').val();
if (validateEmail(email)) {
} else {
swal('Oops!','The email '+email+' is not valid','error');
return false;
}
}
I myself solved the above issue by keeping the target of the form to a hidden iframe and creating a hidden iframe on the same page.

How can we send json encoded data through ajax via form text input

I am fetching php json encoded data using ajax and then setting values to form input then sending it to other page . But json fetched values does not post to other page while normal input values are posting . Here's the code i am using . Your help will be highly appriciated .
`
if(isset($_POST['send_mail'])){
header('Content-Type: application/json');
$out = array('a'=>"Volvo", 'b'=>"BMW", 'c'=>"Toyota");
echo json_encode($out);
//print_r($out);
exit();
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
function send_mail_test(){
var txt = $("#test_txt").val();
if( txt !=""){
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType: "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data){
document.getElementById('code_r').setAttribute('value', data.a);
}
});
//return false;
}
else alert("please enter some text");
//return false;
}
</script>
<form method="post" action="sub.php" name="myform" onSubmit="return send_mail_test()">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>`
sub.php
<?php
print_r($_POST);
?>
UPDATE
I am using onclick on button in another form and trying to change action page from there and then submitting form to that action is that possible ??
<script>
function action(){
var str = location.href;
var x = "feedback.php?page="+str;
$("#quick_query").attr("action", x);
$('#quick_query').submit();
}
</script>
<form id="myform" method="post" action="">
<input type="button" onclick="action()">
</form>
It is changing the action but doesn't submit the form ? how can i achieve it that will be of great help.
ANSWER UPADTED:
The problem with your code is that the submit event occurs even before ajax is called. The following changes have been done in your code
HTML
<form method="post" action="sub.php" name="myform" id="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="button" name="_mail" value="send" onclick="return send_mail_test()" >
</form>
<br><hr><br>
<form method="post" action="xyz.php" name="anotherform" id="anotherform">
<input type="button" name="change" value="Change action of above form" onclick="changeformaction();" >
</form>
The onsubmit on the form is removed & the submit button is changed to normal button. The send_mail_test() function is called on the Send button now.
JAVASCRIPT
<script>
function send_mail_test() {
var txt = $("#test_txt").val();
if (txt != "") {
$.ajax({
url : "chckvar.php",
type : "POST",
//async : false,
dataType : "JSON",
data : {
send_mail : 1,
txt_val : txt
},
success : function(data) {
$('#code_r').val(data.a);
$('#myform').submit();
}
});
}else{
alert("please enter some text");
return false;
}
}
function changeformaction(){
$("#myform").prop('action','newaction.php');
$('#myform').submit();
}
</script>
Here a small change is made in ajax success callback , after the response is received and the value is set in the input , the form is made to submit then.
No change is needed in your ajax file.
Try this:
<script>
$(function () {
$('form[name="myform"]').on('submit', function (e) {
e.preventDefault();
var txt = $(this).find("#test_txt").val();
if (txt.length > 0) {
$.ajax({
url: "chckvar.php",
type: "POST",
//async : false,
dataType: "JSON",
data: {
send_mail: 1,
txt_val: txt
},
success: function (data) {
$('#code_r').attr('value', data.a); //$('#code_r').val(data.a);
$(this).submit()
}
});
} else alert("please enter some text");
});
});
</script>
<form method="post" action="sub.php" name="myform">
<input type="text" name="name" id="test_txt">
<input type="text" name="code_r" id="code_r">
<input type="submit" name="_mail" value="send" >
</form>

execute php code by pressing a button inside form before submitting the form itself

I have a form with several fields. One of those fields is an input file field where user can upload a JSON file.
My need: When a button is pressed (not to submit form) I need to grab that input file field and pass it to a function executing it, but without submitting the form itself.
<form action=''>
<input type="text" name="abc">
<input type="text" name="cde">
<input type='file' name='import' />
<button class="button" type='submit' name='restore'>
<span class="icon-upload"> </span> Restore
</button>
<input type="submit" value="Submit">
</form>
How can I achieve it?
You can use
var form = document.forms.formName("fileinput"); \\ change the form name and the file input
form.addEventListener('submit', function(ev) {
var
oOutput = document.getElementById("output"),
oData = new FormData(document.forms.formNAme("fileinput"));
oData.append("CustomField", "This is some extra data");\\if you need to...
var oReq = new XMLHttpRequest();
oReq.open("POST", "thepphpfile.php", true);
oReq.onload = function(oEvent) {
if (oReq.status == 200) {
oOutput.innerHTML = "Sent!";
} else {
oOutput.innerHTML = "Error " + oReq.status + " occurred uploading your file.<br \/>";
}
};
oReq.send(oData);
ev.preventDefault();
}, false);
you need to capture the button click with javascript, preferably jquery, and post it via ajax to a php-script. look up "ajax" on jquery.
include jquery in your file
then change the input and button to somthing like that:
<input type='file' id="myinput" name='import' />
<button class="button" id="ajaxsubmit">restore</button>
after this, add the ajax call (read the sample code from api.jquery.com):
$("#ajaxsubmit").click(function(e){
e.preventDefault();
var formData = new FormData($('form')[0]);
$.ajax({
type: "POST",
url: "receiver.php",
data: formData,
cache: false,
contentType: false,
processData: false
});
});
finally set up your php-file receiver.php where you work with your received file data like you would when the form gets submitted.
http://jsfiddle.net/9nfn2Las/

Categories