Ajax not seeing textarea value - javascript

I have a textarea input on my page that I want to post to the server using AJAX. The AJAX call is good, however, it will not see the value that's inside the textarea.
My HTML:
<div class="promptBody">
<div id="promptText" onclick="replaceWithInput(this)">
<p class="promptBody"><div id="prompty">{{prompt.prompt|linebreaks}}</div></p>
</div>
<form id="promptUpdateForm">
<div id="promptInput">
<p><textarea class="input" cols="40" id="id_prompt" name="prompt" placeholder="Prompt" rows="10"></textarea></p>
<p><input class="submit" type="submit" name="submit" id="submit" value="Edit Prompt" /></p>
</div>
</form>
</div>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('submit', '#promptUpdateForm', function(e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: '/apps/litprompt/a/{{prompt.id}}/update/',
data: {
'prompt': $('#id_prompt').val(),
csrfmiddlewaretoken: $('input[name="csrfmiddlewaretoken"]').val(),
},
success: function(json) {
$('#promptText').html(json.prompt_data);
var promptText = document.getElementById('promptText');
var promptInput = document.getElementById('promptInput');
promptText.style.display = 'block';
promptInput.style.display = 'none';
}
});
});
});
</script>
If I change my ajax code in data to 'prompt': 'blah', it works just fine. But every time I post with 'prompt': $('#id_prompt').val(), it is a null value.

The textarea HTML element is not self-closing. It has to be closed by </textarea>.
See as follows:
<div class="promptBody">
<div id="promptText" onclick="replaceWithInput(this)">
<p class="promptBody"><div id="prompty">{{prompt.prompt|linebreaks}}</div></p>
</div>
<form id="promptUpdateForm">
<div id="promptInput">
<p><textarea class="input" cols="40" id="id_prompt" name="prompt" placeholder="Prompt" rows="10"></textarea></p>
<p><input class="submit" type="submit" name="submit" id="submit" value="Edit Prompt" /></p>
</div>
</form>
</div>

Related

How do I automatically submit two forms without the page refreshing?

<form id="addToCart" action="http://my-website/cart/action.php">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="POST">
<input type="submit" value="Submit request" />
</form>
<script>
document.forms[0].submit();
document.forms[1].submit();
</script>
This only submits the first form but not the second. How can I get it to submit both?
Before anyone asks, I also tried this below and it still didn't work.
document.getElementById("addToCart").submit();
document.getElementById("buy").submit();
In order of preference
Submit all data to action and have that add AND buy
Use ajax, submit the second form in the success of the first submit
const url = "https://my-website/cart/action.php";
document.getElementById("container").addEventListener("click", e => {
const itemNum = e.target.dataset.itemnum;
fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
action: "add",
itemNum: itemNum
})
})
.then(() => {
fetch(url, {
method: "post",
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
//make sure to serialize your JSON body
body: JSON.stringify({
action: "buy",
itemNum: itemNum
})
})
})
});
<div id="container">
<input type="button" data-itemnum="201" value="Buy 201 with one click " />
<input type="button" data-itemnum="202" value="Buy 202 with one click " />
<input type="button" data-itemnum="203" value="Buy 203 with one click " />
</div>
Two iframes (don't change the fields or methods, only the value of action):
<form id="addToCart" method="post" action="http://my-website/cart/action.php" target="iframe1">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php" method="POST" target="iframe2">>
<input type="hidden" name="action" value="buy" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<iframe name="iframe1"></iframe>
<iframe name="iframe2"></iframe>
<script>
document.forms[0].submit();
setTimeout(() => document.forms[1].submit(),2000);
</script>
This would be my approach. Use jquery ajax to define a .submit() function for each form (the procedure to follow when submitted). Use .click() to "click" both submit buttons programmatically. Then use return false to prevent page refresh. This should submit both forms simultaneously. I was unable to test this without the php actions.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addToCart" action="http://my-website/cart/action.php" method="get">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="post">
<input type="submit" value="Submit request" />
</form>
<script>
$(document).ready(function() {
const $addToCartForm = $("#addToCart");
const $buyForm = $("#buy");
const addToCartUrl = $("#addToCart").attr("action");
const buyUrl = $("#buy").attr("action");
$buyForm.submit(function() {
$.ajax({
url: buyUrl,
type: $buyForm.attr("method"),
data: $buyForm.serialize()
});
return false;
});
$addToCartForm.submit(function() {
$.ajax({
url: buyUrl,
type: $addToCartForm.attr("method"),
data: $addToCartForm.serialize()
});
return false;
});
$addToCartForm.find("[type='submit']").click();
$buyForm.find("[type='submit']").click();
});
</script>
you can use AJAX with JQuery $.post() method for submitting both forms simultaneously.
$(document).ready(main);
function main(){
submitFormUsingAjax('#addToCart');
submitFormUsingAjax('#buy');
}
function extractInputDataOfFromRef(formSelector){
var $inputRefs = $(formSelector +' input:not([type=submit])');
var data = {};
$inputRefs.each(function($index){
var name = $(this).attr("name");
var value = $(this).attr("value");
data[name] = value;
})
return data;
}
function submitFormUsingAjax(formSelector){
var $formRef = $(formSelector);
var url = $formRef.attr('action');
var data = extractInputDataOfFromRef(formSelector);
var method = $formRef.attr('method');
method = method && method.toUpperCase();
var posting;
if(method == 'GET'){
posting = $.get(url,data);
}else{
posting = $.post(url,data)
}
posting.done(function(response) {
console.log("form submitted: ",response);
});
posting.fail(function(error) {
console.log("form submittion failed:",error.statusText);
});
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="addToCart" action="http://my-website/cart/action.php" method="get">
<input type="hidden" name="action" value="add" />
<input type="hidden" name="itemNum" value="201" />
<input type="submit" value="Submit request" />
</form>
<form id="buy" action="http://my-website/cart/action.php?action=buy" method="POST">
<input type="submit" value="Submit request" />
</form>
document.forms[0].onsubmit = (e) => {
e.preventDefault();
}

FormData Returning Undefined in Ajax and Wordpress Form

I created a contact form for a Wordpress theme (custom) using jQuery/Ajax. When I tested the wp_send_json_sucess with "it works" it returned as suspected. However, when I added $formdata and the name of a field on the form the from returned undefined in the JS alert box. I'm pretty sure I've typed it correctly, as I was following this tutorial: https://www.youtube.com/watch?v=LYvx_L9ESn0. But I cannot seem to get it to work.
Code for functions.php here
add_action('wp_ajax_contact', 'contact_form');
add_action('wp_ajax_nopriv_contact', 'contact_form');
function contact_form()
{
$formdata = [];
wp_parse_str( $_POST['contact'], $formdata );
wp_send_json_success( $formdata ['myName'] );
}
Form Code Here :
<form id="contact">
Name: <input type="text" name="myName" class="contactform
fields" placeholder="name"required><br><br>
Email: <input type="text" name="myEmail" class="contactform
fields" placeholder="you#youremail.com" required><br><br>
<p>What is your inquiry regarding?</p><be>
<input type="radio" name="reason" value="general">
<label for="news">General Inquiry</label><be>
<input type="radio" name="reason" value="course">
<label for="news">Courses</label><br>
<p class="contact_txt">Your Message:</p>
<textarea name="msg" rows="5" cols="700" placeholder="begin
typing message here..." required>
</textarea>
<p class="contact_txt">Would you like to subscribe to our
newsletter?</p>
<br>
<input type="checkbox" name="news" value="Subscribe">
<label for="news">Yes, I would like to subscribe</label>
<br>
<input class="btns" name="btn-send" id="mySubmit" type="submit" value="submit">
<input class="btns" name="btn-reset" id="myReset" type="reset" value="reset">
</form>
Script Here :
<script>
jQuery('#contact').submit( function(event){
event.preventDefault();
var endpoint = '<?php echo admin_url('admin-ajax.php' ); ?>';
var form = jQuery('#contact').serialize();
var formdata = new FormData;
formdata.append('action', 'contact');
formdata.append('contact', 'form');
jQuery.ajax(endpoint, {
type: 'POST',
data: formdata,
processData: false,
contentType: false,
success: function(res){
alert(res.data);
},
error:function(err){
}
})
})
</script>

Get json response from url and display it in html

I have a python script file that returns a json
{"message": "Login or password is empty", "success": 0}
I want to go to this url in html and dislpay "Login or password is empty" and also save the success int to be used later for pass fail verification.
I have no idea how to get the json parsed so that I can use it in html.
This is my html
<h2> Login</h2>
<form action="http://test.com/cgi-bin/login.py" method="POST" target="hiddenFrame2">
Username:<br>
<input type="text" name="username">
<br>
Password:<br>
<input type="password" name="password">
<br>
<br>
<input type="submit" value="Submit">
<br>
<iframe src="about:blank" frameborder="0" width="100" height="50" scrolling="no" name="hiddenFrame2" class="hide"></iframe>
<br>
<br>
</form>
Suppose you have form like this,
<h2> Login</h2>
<form action="http://test.com/cgi-bin/login.py" method="POST" target="hiddenFrame2" id="myform">
Username:<br>
<input type="text" name="username">
<br>
Password:<br>
<input type="password" name="password">
<br>
<br>
<input type="submit" value="Submit">
<br>
<iframe src="about:blank" frameborder="0" width="100" height="50" scrolling="no" name="hiddenFrame2" class="hide"></iframe>
<br>
<br>
</form>
<span id="log"></span>
You can submit your form like this using ajax,
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="application/javascript">
$(document).ready(function(){
$("#myform").submit(function(){
var formvars = $("#myform").serialize();
var url = "http://test.com/cgi-bin/login.py";
$.ajax({
url: url,
dataType: 'text',
data : formvars,
type:"POST",
success: function(data){
alert( data );
var json = eval(data);
var success = json.success;
var message = json.message;
if(success =="1")
$("#log").text(message); // Success
else
$("#log").text(message); // Failed
},
error: function(data){
alert('error; '+ data);
}
});
return false;
});
});
</script>

Form is not checked by if statement

I have two forms with id formA and comments and I want to submit them via AJAX. But the if and else here doesn't check the form. I always get alert hello3.
JS:
function submitformbyajax() {
var currentForm = $(this);
if (currentForm.attr("id") == 'formA') {
$.ajax({
type: 'post',
url: 'commentformhandler.php',
data: $("form").serialize(),
success: function() {
$("#refresh").load("commentform.php #refresh");
}
});
} else if (currentForm.attr("id") == 'comments') {}
alert("hello3");
return false;
}
the function is called by
<div>
<form name="formA" id="formA" action="" method="" onsubmit="return submitformbyajax();">
<textarea name="comment" id="commentform" style="width:90%; height:45px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</div>
here is the full demo page ....
<?php
?>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"> </script>
<script>
function submitformbyajax (){
var currentForm = $(this);
if (currentForm.attr("id") == 'formA' ) {
$.ajax({type: 'post',
url: 'commentformhandler.php',
data: $("form").serialize(),
success: function(){
$("#refresh").load("commentform.php #refresh");
alert ("hello1");
}
} );
}
else if (currentForm.attr("id") == 'comments') {
alert("hello2");
}
alert ("hello3");
return false;
}
</script>
<title>
comment forms..
</title>
</head>
<body>
<div>
<form name="formA" id="formA" action="" method="" onsubmit="return submitformbyajax();">
<textarea name="comment" id="commentform" style="width:90%; height:45px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</div>
<div id="refresh">
<?php
include_once('databaseconnection.php');
$selectdata=mysql_query("select * from `fetwork_view` ");
while($selectedinarray=mysql_fetch_array($selectdata)){ ?>
<table>
<tr>
<td>
<?=$selectedinarray['view']?>
</td>
</tr>
<tr>
<td>
<form name="comment" id="comments" action="" method="">
<textarea name="comment" id="commentform" style="width:70%; height:25px;"></textarea>
<input type="submit" name="submit" value="submit" id="submitbtn" />
<input type="hidden" name="onid" value="2" id="submitbtn"/>
</form>
</td>
</tr>
</table>
<?php } ?>
</div>
</body>
</html>
Your alert(...) statement is executed regardless of condition tested by if. It is executed right after that if.
Note that ajax will not redirect the "flow" of the code. Browser will just "launch" the AJAX request and continue. Then, after a response from server is received - AJAX callback function will be executed.
Update:
To "pass" your form to submitformbyajax function add this as an argument:
<form name="formA" id="formA" onsubmit="submitformbyajax(this);">
JS:
function submitformbyajax(your_form) {
var currentForm = $(your_form);
I think you should use
$("form#formA").submit(function(){
alert(1);
});

facebox not closing on submit

On submit, it doesn't close the facebox for some reason. Can you guys help me out?
my code is:
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script type="text/javascript">
$(function() {
$('#reset_form').click(function() {
$('#name,#comment').val('');
});
$('#submit').click(function() {
var name = $('#name').val();
var comment = $('#comment').val();
$.ajax({
url: '../forms/comment_ajax.php?id=<?php echo $_GET['id']; ?>',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').append(data);
$(document).trigger('close.facebox');
$('#new_comment').effect("bounce", { direction:'down', times:5 }, 300);
$('html,body').animate({scrollTop:0}, 2000, "easeOutQuart");
return false;
}
});
});
});
</script>
Name: <br />
<input type="text" id="name" class="userpass" maxlength="15"/><br /><br />
Comment: <br />
<textarea id="comment" rows="6" cols="75"></textarea><br /><br />
<input type="submit" id="submit" value="Comment" class="button" />
<input type="reset" id="reset_form" name="submit" value="Reset" class="button" />
this isn't doing it $(document).trigger('close.facebox');
I have it opened in a facebox. The index for it to post on is: http://pastebin.com/JhpDhevr
Kinda messy, but yeah. It's not closing on submit.
try
$('#button-id').click($.facebox.close);
instead of
$(document).trigger('close.facebox');

Categories

Resources