Form is not checked by if statement - javascript

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);
});

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();
}

jquery onclick function not defined

I have an ajax script and I am trying to post from a function. I am using a onlick href but its not coming up as undefined. This is using wordpress. I have tried to move the code around inside and outside the scope but I still cant seem to get it to work.
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name"/>
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>"/>
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
Submit Comment
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function(){
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/get_chat.php"
}).done(function(html){
$('#displayComments').html(html);
});
}, 2000);
function submitComment(){
$.ajax({
method: "POST",
url: "template-live.php",
data: {submitComment:$('#chatBox').val(),submitName:$('#nameBox').val(),submitEmail:$('#emailBox').val()}
}).done(function(html){
alert('Your comment has been submitted, and will be displayed after approval.');
$('#chatBox').val('');
});
}
});
</script>
Thank you :)
When you do javascript:submitComment() that's calling a the global function submitComment. Since the submitComment is defined in the jQuery(function($) { ... }) function, it is not a global. Therefore, window.submitComment is undefined (hence undefined is not a function).
The globals are stored in the window object.
Therefore, you can expose that submitComment as a global:
window.submitComment = function () {...}
Note that you should avoid using globals as much as possible. In this case you can do that by adding:
$("#submit").click(submitComment);
// In this case, you shouldn't declare submitComment as a global anymore
And since you are in a form, you want to stop the default browser behavior when clicking the a element, by using return false at the end of the function.
Alternatively to #Ionică Bizău's solution.
You could use onclick="submitComment()" instead of href.
<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<div id="live">
<div class="container">
<?php the_content(); ?>
<div id="comment-display">
<form method="post" action="index.php" id="comments_submit">
<input type="hidden" id="nameBox" value="<?php echo $_SESSION['name'] ?>" name="name" />
<input type="hidden" id="emailBox" name="email" value="<?php echo $_SESSION['email']; ?>" />
<textarea id="chatBox" placeholder="Ask a question or make a comment" name="comment" class="form-control"></textarea>
<a onclick="submitComment()" type="submit" id="submit" name="submit" class="btn cardh-bg text-white text-bold margin-top-5"> Submit Comment </a>
</form>
<br />
<div id="displayComments"></div>
</div>
</div>
</div>
<script type="text/javascript">
jQuery(function($) {
setInterval(function() {
$.ajax({
method: "GET",
url: "<?php echo get_template_directory_uri()?>/get_chat.php"
}).done(function(html) {
$('#displayComments').html(html);
});
}, 2000);
window.submitComment = function(){
console.log('submitComment called!');
$.ajax({
method: "POST",
url: "template-live.php",
data: {
submitComment: $('#chatBox').val(),
submitName: $('#nameBox').val(),
submitEmail: $('#emailBox').val()
}
}).done(function(html) {
alert('Your comment has been submitted, and will be displayed after approval.');
$('#chatBox').val('');
});
}
});
</script>

Ajax not seeing textarea value

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>

Ajax - How to submit one by one input value - Codeigniter

Sorry for my english is not so good. And i'm newbie :)
I want to update one-by-one input value with ajax in Codeigniter, but it not work right.. only one save button (one form) work, others form not work .. please help me edit below code
Here's the demo code:
View:
<script>
$(function(){
$(".submit45").click(function(){
dataString = $("#prod_upd").serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
document.getElementById('dd').innerHTML=data;
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" id="prod_upd" method="post" >
<input type="text" name="p_ppx" id="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" id="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="button" name="sub" id="sub" class="submit45" value="Save4" />
<div id="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>
Controller:
function change_ppx3(){
$id_p = $_POST['ids_p'];
$rs = $this->ppx->get_ppx_by_id($id_p);
$ppx_value = $_POST['p_ppx'];
$this->ppx->update_ppx(array("id"=>$id_p),array("ppx_r"=>$ppx_value));
if($_POST['p_ppx']):
echo "done: ";
print_r($_POST['ids_p']);
echo "-";
print_r($_POST['p_ppx']);
return true;
endif;
}
because every form has the same id="prod_upd".
test this
<script>
$(function(){
$(".prod_upd").submit(function(){
var $this = $(this), dataString = $this.serialize();
$.ajax({
type: "POST",
url: "<?=PREFIX?>admin/update/change_ppx3/",
data: dataString,
success: function(data){
console.log(data);
$this.find('.dd').html(data);
}
});
return false;
});
});
</script>
<?$i=0;if(count($PPX) > 0)foreach($PPX as $item){$i++;?>
<form name="prod_upd" class="prod_upd" method="post" >
<input type="text" name="p_ppx" size="8" value="<?= number_format($item['p_ppx'],0,'','')?>" class="i_ppx">
<input type="hidden" name="ids_p" size="8" value="<?=$item['id']?>" class="i_ppx">
<input type="submit" class="submit45" value="Save4" />
<div class="dd" style="float: left;">hello</div>
</form>
<?}else{?>
<div class="no_data">Nothing here</div>
<?}?>

Sending values to the action script continuously. How to do that?

I want to repeatedly send values of username and password to the php script. How do I do this ? Like to send the values to the action script, we use submit button but how can I send the values automatically to the script and that too continuously ?
<form method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
Using the jQuery form plugin you can do the following:
setInterval(function() {
$('form').ajaxSubmit();
}, 1000);
Another solution is to target the form to an iframe so if you submit the form, it doesn't reload the page:
HTML:
<form id="myform" method="post" action="processor.php" target="frm">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<iframe name="frm" id="frm"></iframe>
JS:
var form = document.getElementById('myform');
setInterval(function() {
form.submit();
}, 1000);
try something like this
JAVASCRIPT
<script language=javascript>
var int=self.setInterval(function(){send_data()},1000);
function send_data()
{
document.getElementById('my_form').submit()
}
</script>
HTML
<form method="post" id="my_form" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
</form>
<form id="myform" method="post" action="processor.php">
<input type="username" value="suhail" />
<input type="password" value="secret_code" />
<input type="submit" />
</form>
<script type="text/javascript">
var count=100,i=0;
for(i=0;i<count;i++) {
document.getElementById('myform').submit();
}
</script>
This will submit the form 100 times
Use Ajax, it's really easy with jQuery. To send the form data to the processor.php script:
var sendForm = function () {
$.ajax({
type: 'post',
url: 'processor.php',
dataType: 'JSON',
data: {
username: $('#username').val(),
password: $('#password').val()
},
success: function (data) {
// do something with the answer from server?
},
error: function (data) {
// handle error
}
});
}
So, sendForm is a function that sends the form data to the server. Now, wee need to set a timer that will invoke it repeatedly:
window.setInterval(sendForm, 1000); // sends form data every 1000 ms
You may you $.post or $.get or $.ajax request repeatedly to send continuous request.
$(document).ready(function(){
setInterval(function() {
var username = $("#username").val();
var password = $("#password").val();
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
//your code what you want to do of response
alert(response);
});
}, 1000);
});
and html code is like following
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>
This is a full HTML file doing what you want, read the comments.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<form method="post" action="processor.php">
<input type="username" id="username" value="suhail" />
<input type="password" id="password" value="secret_code" />
<input type="submit" />
</form>
<script>
function send_request(username, password) {
var dataString = 'username='+username+"&password="+password;
$.post('login.php',dataString,function(response){
// You can check if the login is success/fail here
console.log(response);
// Send the request again, this will create an infinity loop
send_request(username, password);
});
}
// Start sending request
send_request($('#username').val(), $('#password').val());
</script>
Try this,
JS:
$(document).ready(function(){
var int=self.setInterval(function(){statuscheck()},1000);
function statuscheck()
{
var username = $("#username").val();
var password = $("#password").val();
$.ajax({
type:"post",
url:"processor.php",
dataType: "html",
cache:false,
data:"&username="+username+"&password="+password,
success:function(response){
alert(response);
}
});
}
});
HTML:
<form method="post" action="processor.php">
<input type="username" value="suhail" id="username"/>
<input type="password" value="secret_code" id="password"/>
<input type="submit" />
</form>

Categories

Resources