AJAX Post for multiple form - javascript

I have a list, each row is a form with a submit button. When I submit the form, data is sent through the post and must be update the div with the result. But there is a problem when sending the post, javascript does not send data correctly.
This is index file:
<!doctype html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://code.jquery.com/jquery-1.11.0.min.js"></script>
<script>
$(function() {
$(".notif-close").click(function(e) {
e.preventDefault();
var notif_id = $(".notif_id").val();
var data = 'notif_id='+ notif_id;
$.ajax({
type: "POST",
url: "post.php",
data: data,
beforeSend: function(send) {
$("#notif_box").fadeOut(400, function() {
$('.loader').fadeIn(50);
}
)},
success: function(html){ // this happen after we get result
$(".loader").fadeOut(50, function()
{
$("#notif_box").html(html).fadeIn(400);
$(".notif_id").val("");
});
return false;
}
});
});
});
</script>
</head>
<body>
<form method='post' action='post.php'>
<input type='hidden' id='notif_id' name='1' class='notif_id' value='1' />
<button type="submit" id="notif-close" class="notif-close">notif-close1</button>
</form>
<form method='post' action='post.php'>
<input type='hidden' id='notif_id' name='2' class='notif_id' value='2' />
<button type="submit" id="notif-close" class="notif-close">notif-close2</button>
</form>
<div class='notificationsblock' id='notif_box'>Result</div>
<span class='loader' style="display: none; position: absolute;">Please wait...</span>
</body>
</html>
And this is post.php:
<?
sleep(2);
print_r($_POST);
?>
Help me.
Please tell me what am I doing wrong?

Try changing
var notif_id = $(".notif_id").val();
to
var notif_id = $(this).parent().find(".notif_id").val();
You can also try changing
var data = { 'notif_id' : notif_id }
You also have same IDs: #notif_id, #notif_close, which can (and will) cause errors and conflicts. You must give unique IDs. Giving unique names to input elements and forms is also a better idea.

Related

submit form button trigger when secondary button clicked

I'm trying to get a check box to trigger the submit button in a form. Basically, this is a touch screen game that takes users emails using a touch keyboard. The Enter button on the touch keyboard is what switches into the game. When I add document.getElementById("").submit in the javascript just resets everything. What I've done to try and work around this is to put a button next to it that is like an "opt-in" type of deal. When you click the button it copies the email address into the form. But I still need the submit button on the form to click without resetting the site or not updating the data.txt where the form info goes.
<body>
<script>
function myFunction() {
var x = document.getElementById("name").innerHTML;
document.getElementById("demo").innerHTML = x;
}
</script>
<span id="name">
<!-- Displaying name input from touch keyboard here -->
</span>
<form method="post" class="emailForm" id="demo" name="myForm">
<input type="text" name="subscriptions" id="formName"><br>
<input type="submit" name="mySubmit" id="submitBtn">
</form>
<div class="roundedB">
<input onclick="myFunction()" type="checkbox" value="None" id="roundedB" name="Submit" />
<label for="roundedB"></label>
</div>
</body>
<?php
if(isset($_POST['subscriptions']))
{
$data=$_POST['subscriptions'];
$fp = fopen('data.txt', 'a');
fwrite($fp, $data);
fclose($fp);
}
?>
What I want to achieve is to click the check button, the form fills and auto-submits to data.txt. Website does not reload.
Drat - started this before the noticing an accepted answer but will post this anyway as it might help.
<?php
error_reporting( E_ALL );
ini_set( 'display_errors', 1 );
if( $_SERVER['REQUEST_METHOD']=='POST' ){
ob_clean();
/* This is where you would process the POST request somehow... */
$_POST['response']=date( DATE_ATOM );
$_POST['ip']=$_SERVER['REMOTE_ADDR'];
/* prepare data for saving */
$json=json_encode( $_POST );
/* write to file */
$file=__DIR__ . '/subscriptions-data.txt';
file_put_contents( $file, $json . PHP_EOL, FILE_APPEND );
/* send back a response of some sort to the ajax callback function */
exit( $json );
}
?>
<!DOCTYPE html>
<html lang='en'>
<head>
<meta charset='utf-8' />
<title>submit form button trigger when secondary button clicked</title>
<script>
document.addEventListener( 'DOMContentLoaded', function(){
const xhr_callback=function(r){
console.info( r );
};
const ajax=function(url,payload,callback){
let xhr=new XMLHttpRequest();
xhr.onreadystatechange=function(){
if( this.status==200 && this.readyState==4 )callback( this.response );
}
xhr.open( 'POST', url, true );
xhr.send( payload );
};
const clickhandler=function(e){
if( this.checked ){
let payload=new FormData( document.forms.myForm );
ajax.call( this, location.href, payload, xhr_callback );
}
};
document.querySelector('input[type="checkbox"][name="submit"]').addEventListener( 'click', clickhandler );
});
</script>
</head>
<body>
<span id='name'>
<!-- Displaying name input from touch keyboard here -->
</span>
<form method='post' class='emailForm' name='myForm'>
<input type='text' name='subscriptions' value='geronimo#hotmail.com' />
<br />
<input type='submit' />
</form>
<div class='roundedB'>
<input type='checkbox' value='None' name='submit' />
<label for='roundedB'></label>
</div>
</body>
</html>
You can try with something like this
As you can see I used Jquery for that. You can make a trigger on change.
Then to send ajax request to server.
$('#myCheck').on('change',function() {
// ajax request
alert('Do your action');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Check me <input type="checkbox" id="myCheck">
Simple ajax
$('#myCheck').on('change', function() {
var data = JSON.stringify({
email: $('input#email').val()
});
$.ajax({
type: "POST",
url: "email.php",
data: data,
success: function(){
alert('success');
},
error: function(){
alert('error');
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form id="form1">
Email: <input type="text" id="email" value="someone#email.com">
</form>
<form id="form2">
Check me <input type="checkbox" id="myCheck">
</form>
This one will give you error in alert, because there is not email.php file.
Here is code you need for that
index.php
$('#roundedB').on('change', function() {
var email = $('input#subscriptions').val();
$.ajax({
type: "POST",
data: {
'subscriptions': email
},
url: 'send.php',
success: function (data) {
alert(data);
},
error: function (data) {
alert(data);
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<span id="name">
<!-- Displaying name input from touch keyboard here -->
</span>
<form method="post" class="emailForm" id="demo" name="myForm">
<label for="subscriptions">Email address</label>
<input type="text" name="subscriptions" id="subscriptions"><br>
</form>
<div class="roundedB">
<input type="checkbox" id="roundedB" name="Submit" />
<label for="roundedB"></label>
</div>
</body>
send.php
<?php
if(isset($_POST['subscriptions']))
{
$data=$_POST['subscriptions']."\n";
$fp = fopen('data.txt', 'a');
if(fwrite($fp, $data)){
print 'successful';
}else{
print 'error';
}
fclose($fp);
}

How do I pass a value to a PHP script using AJAX?

I am trying to learn web design with a search function using MySql. I want make it to 2 steps selection however, I have run into a problem which really confuses me since I don't have a strong background to design. I am trying to be as specific as possible to make the question clear.
test.php
<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>count</title>
<link rel="stylesheet" type="text/css" href="dbstyle.css">
<script src='http://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js'>
</script>
</head>
<body>
<form id="serc" method="post" action="">
<input type="radio" value="typeA" name="comments" onclick="expr()">Good
<input type="radio" value="typeB" name="comments" onclick="expr()">Bad
</form>
<form id="form1" name="form1" method="post" style="visibility:hidden">
<p>please select reason:</p>
<input type="checkbox" class="check" name="checkbox[]" value="COL 8">aaa<br />
<input type="checkbox" class="check" name="checkbox[]" value="COL 9">bbb<br />
<input type="checkbox" class="check" name="checkbox[]" value="COL 10" >ccc<br />
<button id="aaa" type="submit" class="butt" name="sub2" style="visibility:hidden">Submit</button>
</form>
<?php
$comm = $_POST["gender"];
$reas = $_POST["checkbox"];
if($comm){$respond = $_POST['comments'];
echo $respond;
}
<script src="limit.js"></script>
</body>
</html>
limit.js
//click to get Value
$("input[type='Radio']").click(function(){
var radioValue = $("input[name='comments']:checked").val();
$("#serc").css("display", "none");
$("#form1").css("visibility", "visible");
});
//limit multiple selection up to 4
$("input:checkbox").click(function() {
var bol = $("input:checkbox:checked").length;
if(bol == 4){
$("input:checkbox").not(":checked").attr("disabled",bol);
$("#aaa").css("visibility", "visible");
}
else {
$("#aaa").css("visibility", "hidden");
$("input:checkbox").removeAttr("disabled");
}
});
// return value
function expr()
{
var radioValue = $("input[name='comments']:checked").val();
var dataTosend= radioValue;
$.ajax({
url: 'index.php',
type: 'POST',
data: dataTosend,
async: true,
success: function (data) {
alert(data)
},
});
}
The function will be:
First stage select from radio item, onclick use jQuery to hide the selection items and also get radioValue from the jQuery by Ajax way to send to php use.
Second stage select 4 items from checkbox, and submit to run search field.
I expect load the radioValue back to php as a variable but seems it didn't get the value.
Any help would be appreciated.
You must send data using key value pair like this:
function expr(){
var radioValue = $("input:radio[name='comments']").val();
var dataTosend= {'radioValue': radioValue};
$.ajax({
url: 'index.php',
type: 'POST',
data: dataTosend,
async: true,
success: function (data) {
alert(data)
},
});
}

Submission done. empty textarea

i need your help. i have a working form that uses ajax to send textarea posted value to a php file.
I have added emoji to that textarea input and everything is okay. But am facing a problem, when a form is submitted the textarea does not empty automatically.
I need the input to empty after the confirmation is set, but i don't know how.
HTML PAGE
<html>
<head>
<link rel="stylesheet" href="https://cdn.rawgit.com/mervick/emojionearea/master/dist/emojionearea.min.css">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript" src="https://cdn.rawgit.com/mervick/emojionearea/master/dist/emojionearea.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/core.js">
</script>
<script>
$(document).ready(function() {
$("#formsubmit").click(function() {
var msg = $("#emojionearea1").val();
if ( msg == '') {
alert("field empty");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.post("sss.php", {
msg1: msg
}, function(data) {
//alert(data);
$('#status').html(data);
$('#di_pr')[0].reset(); // To reset form fields
});
}
});
});
</script>
</head>
<body>
<p id="status"></p>
<form action="" id="di_pr" method="post" name="myForm" enctype="multipart/form-data">
<div class="row">
<div style="width: 303px;" class="span6">
<textarea id="emojionearea1" name="rby_message" placeholder="type here"></textarea>
</div><br/>
<div class="uhn">
<input type="button" value="Send" name="tlaj_submit" id="formsubmit" class="gpfy" >
</div>
</div>
<script>
$(document).ready(function() {
$("#emojionearea1").emojioneArea({
pickerPosition: "left",
tonesStyle: "bullet"
});
})
</script>
</form>
</body>
</html>
PHP PAGE
<?php
$hssh = $_POST['msg1'];
echo '<p>send message: '.nl2br($hssh).'</p>';
?>
The form rests but the input is not emptied.
$("#emojionearea1").data("emojioneArea").setText('');
Add this line inside the callback function :$("#emojionearea1").val('');
in the following way:
$.post("sss.php", {
msg1: msg
}, function(data) {
//alert(data);
$('#status').html(data);
$('#di_pr')[0].reset(); // To reset form fields
$("#emojionearea1").val('');//line to be added
});

Posted variable used in javascript 'if' statement disappears instantly

I have forms running on my page which post data to a php file which causes the posted item to appear in a cart:
<form method="post"><fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-name" value="is716" />
<input type="hidden" name="my-item-price" value="10" />
<input id="716" type="submit" name="my-add-button" value="&nbsp" />is716</input>
</fieldset></form>
I then put a script running at the bottom of my page which essentially toggles controls so that further selections become clear based on previous selections:
if (name == 'is716') {
document.getElementById('716b').style.display = 'none';
document.getElementById('716c').style.display = 'inline';
}else{
document.getElementById('716b').style.display = 'none';
document.getElementById('716c').style.display = 'inline';}
The problem is that the above script's if statement, that name == 'is716' apparently only becomes true for a moment when you click submit. The css will change and flash for just a second, showing that the statement is indeed working and then it will disappear. I can make the changes stay by adding 'return false' but this stops the form from being submitted and the data updated, which completely misses the point. Is there a way to both submit the data but also have the value 'stick'?
How can I make this change last until the statement changes again?
edit:
Here is the page's code:
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>jCart - Free Ajax/PHP shopping cart</title>
<link rel="stylesheet" type="text/css" media="screen, projection" href="style.css" />
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" media="screen, projection" href="jcart/css/jcart.css" />
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'> </script>
<style type="text/css">
input.add {
background-image: url('off.png');
width: 12px;
height: 12px;
border: 0;
cursor: pointer;
}
</style>
</head>
<body>
<div id="wrapper">
<div id="sidebar">
<div id="jcart"><?php $jcart->display_cart();?></div>
</div>
<div id="content">
<form method="post"><fieldset>
<input type="hidden" name="jcartToken" value="<?php echo $_SESSION['jcartToken'];?>" />
<input type="hidden" name="my-item-id" value="1" />
<input type="hidden" name="my-item-name" value="is716" />
<input type="hidden" name="my-item-price" value="5000" />
<input type="hidden" name="my-item-partn" value="716" />
<input type="hidden" name="my-item-qty" value="1" size="3" />
<input id="716a" type="submit" name="my-add-button" class="add" value="&nbsp" />
<a id="716b" href="addtocart.php?jcartRemove[]=1" /><img src="on.png"></a> &nbsp Apples $5<br>
<br></fieldset></form>
<div class="clear"></div>
<?php
//echo '<pre>';
//var_dump($_SESSION['jcart']);
//echo '</pre>';
?>
</div>
<div class="clear"></div>
</div>
<script type='text/javascript'>
$(document).ready(function() {
$('input[name=my-add-button]').change(function(){
$('form').submit();
});
});
</script>
<script type="text/javascript">
$('#720').click(function() {
$('#720click').click();
});
</script>
<script type='text/javascript'>
window.onload = function() {
var myItemName = <?php echo (isset($_POST["my-item-name"])? $_POST["my-item-name"] : ""); ?>;
if (myItemName == "is716") {
document.getElementById('716a').style.display = 'none';
document.getElementById('716b').style.display = 'inline';
}
}
That pushes to another page: jcart.php
Like Suman said your page is getting submitted, therefore the style reloads with the page so any changes made in the page session to your style will be reset.
A solution to your problem would be to set session flags in your form's php target page. You could do this like:
<?php
if (isset($_POST["my-item-name"]) {
session_start();
$_SESSION["my-item-name"] = $_POST["my-item-name"];
}
?>
And then on your cart page you would echo the session variable into a JavaScript that will toggle the styling of your page as necessary:
<?php session_start(); ?>
window.onload = function() {
var myItemName = <?php echo $_SESSION["my-item-name"]; ?>;
if (myItemName == "is716") {
document.getElementById('716b').style.display = 'none';
document.getElementById('716c').style.display = 'inline';
}
}
Hopefully this is what you are looking for.
EDIT: For if your target page is the same page you could simplify this by having your javascript look like this:
window.onload = function() {
var myItemName = "<?php echo (isset($_POST["my-item-name"])? $_POST["my-item-name"] : ""); ?>";
if (myItemName == "is716") {
document.getElementById('716b').style.display = 'none';
document.getElementById('716c').style.display = 'inline';
}
}
Your form is getting posted and hence the page is getting reloaded. Now, when a webpage is reloaded previous states are forgotten by the browser until and unless you use some persistence (like local storage or something) and check saved data and restore previous stage of any element on page reload by yourself.
Use ajax to post your data and to get information back from server. This way your styles and states will be retained.
Do an event.preventDefault() on your form submit button click and then do whatever server post activity you want to do by ajax call. That should do.

How to pass file array data by ajax and how to receive data in php file?

How to pass file array data by ajax and how to receive data by php file?
Please send me the example code of this issue. I have got data by FormData($(this)[0]) but fetch some problem. First time not got any data from text area (refresh page i.e. after page load first time). But second time I got (not refresh page).
I have made some code
<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script src="jquery-1.6.4.min.js" type="text/javascript"></script>
</head>
<body>
<script>
$(document).ready(function() {
$("form#formD").submit(function(event){
event.preventDefault();
var name = $("#name").val();
var text = $("#text").val();
var upload = $("#upload").val();
$.ajax({
type: "POST",
url: "test.php",
data: {"name" : name, "" : text, "upload" : JSON.stringify(upload)},
dataType: 'json',
async: false,
cache: false,
contentType: false,
processData: false,
beforeSend: function(){ $("#send").val('Sending...'); },
success: function( html ){
alert( html );
$("#send").val('send');
}
});
return false;
});
});
</script>
<form id="formD" action="" method="POST" enctype="multipart/form-data" accept-charset="utf-8">
<label>File name</label>: <input type="text" name="name" id="name" required /><br /><br />
<label>File Description</label>: <textarea id="text"></textarea><br /><br />
<label>Select File</label>: <input type="file" name="upload[]" id="upload[]" required /><br />
<input type="submit" value="send" id="send" />
</form>
</body>
</html>
In the PHP file, you would use the super global $_POST.
This is an array of all data passed via the POST command.
To iterate through it, would be like
foreach($_POST as $sPostKey => $sPostValue) {
// do stuff here
}
Remember to use json_decode to turn that JSON into something usable within PHP.

Categories