Submit button loop counter x amount of times - php

Okay so i need the following to be done.
There is an input form, with 2 input fields and a submit button.
Once the values are entered, the program does a calculation and displays the sum.
The calculation (sum) then gets stored into a database, then using Ajax gets filled dynamically in another form input fields.
Is there a way that once the submit button is clicked, it automatically does it 5 times with a loop counter?
AJAX
$(document).ready(function(){
var data_amount = $('#value').val();
$.when(
$.ajax({ // First Request
url:"fetch.php",
method:"POST",
data:{value:data_amount},
dataType:"text",
contentType: false,
processData:false,
success:function(data)
{
$('#load_data').val(data);
}
}),
$.ajax({ //Seconds Request
url:"fetch_another.php",
method:"POST",
data:{value_2:data_amount},
dataType:"text",
contentType: false,
processData:false,
success:function(data)
{
$('#load_data_2').val(data);
}
})
)
});
FORM
<form method="post" action="test.php">
<input type="number" name="value" id="load_data"></input>
<input type="number" name="value_2" id="load_data_2"></input>
<button type="submit" name="get_values"></input>
</form>
PHP
<?php
if(isset($_POST['value'])) {
$value = $_POST['value'];
}else{
echo "Nothing Entered";
}
?>
<?php
if(isset($_POST['value_2'])) {
$value_2 = $_POST['value_2'];
}else{
echo "Nothing Entered";
}
?>
$result = $value * $value_2;
$result_2 = $value * $value_2 * 2000;
$sql = "INSERT INTO values(value) VALUES('".$result."')";
mysqli_query($con,$sql);
$sql = "INSERT INTO values_2(value_2) VALUES('".$result_2."')";
mysqli_query($con,$sql);
FORM TO LOOP
<form method="post" action="test.php">
<input type="number" name="value" id="load_data" hidden=""></input>
<input type="number" name="value_2" id="load_data_2" hidden""></input>
<button id="somebutton" type="submit" name="get_values"></input>
</form>
I am pretty sure that a for loop with a counter could do the trick, i am just not sure how. Also i know this can be done without the form, just for this particular case i need it to be achieved with the forms.
I am trying something like this, which is not working out:
<script>
$(document).ready(function() {
$("#somebutton").click(function () {
for (var counter = 0; counter < 5; counter++) {
$("#somebutton").click();
}
});
});
</script>

Related

Multi form cloned issue when submit. Submit first input group

I have a Script which load data from MySQL and then i generate a div for each result set. In each div i load several data and generate a form. The problem I have, is that the script is submitting the data from the first form.
Here the code:
<script>
function getitems(){
$.ajax({
type: 'POST',
url: 'userAction.php',
data: 'action_type=view&'+$("#userForm").serialize(),
success:function(html){
$('#userData').html(html);
}
});
}
function userAction(type,id){
id = (typeof id == "undefined")?'':id;
var statusArr = {add:"added",edit:"updated",delete:"deleted"};
var userData = '';
if (type == 'add') {
userData = $("#addForm").find('#userForm'+id).serialize()+'&action_type='+type;
}else{
userData = 'action_type='+type+'&id='+id;
}
$.ajax({
type: 'POST',
url: 'userAction.php',
data: userData,
success:function(msg){
if(msg == 'ok'){
getitems();
$('.form')[0].reset();
}else{
alert('Hubo un problema, intentar de nuevo!');
}
}
});
}
</script>
And the form:
<form class="form" id="userForm<?php echo $r['id']; ?>">
<div class="form-group col-xs-7">
<label>Descripcion</label>
<input type="text" class="form-control" name="item_prt" id="item_prt"/>
</div>
<div class="form-group col-xs-3">
<label>Precio</label>
<input type="text" class="form-control" name="precio_prt" id="precio_prt"/>
</div>
<input type="text" class="form-control" name="idserv_prt" id="idserv_prt" value="<?php echo $orden;?>" />
</form>
I need to difference each form, because all are generated dinamically from mysql result. So, if I submit the first form, it works ok, but when I submit other one, It submit the first form too.
All works OK if i hace only one form.
Thanks!
You need to add the form ID as following :
...
if (type == 'add') {
userData = $("#addForm").find('#userForm'+id).serialize()+'&action_type='+type;
// ----------------------------------------^
}else{
...
and when you call the userAction() function just add the second parameter wish is the ID :

Using jquery ajax to serialize data and submit into mysql database

The problem i have is that whenever it inserts the data into the database it doesn't redirect the user to the invoice.php page. Please guys i really need your help.
This is the html code:
<form method="POST" action="">
<input type="text" name="resident_address" id="resident_address"/>
<input type="text" name="price" id="status"/>
<input type="hidden" name="status" id="status" value="0"/>
</form>
This is the jquery code:
var dataString = $('#applyform').serialize();
$.ajax({
type: "POST",
url: "applyform.php",
cache: false,
data: dataString,
beforeSend: function()
{
$(".apply_error").hide();
},
success: function(html) {
if (html == "true")
{
// You can redirect to other page here....
window.location.href = 'invoice.php';
}
else
{
//window.location.href = 'apply.php';
$("div.apply_error").html("Wrong details").show();
}
}
});
this is the php which is the applyform.php:
if(isset($_POST['Submit']))
{
$result = mysql_query("INSERT INTO mytable (resident_address, price, status) VALUES ('$addressfields', '$price', '$status')");
if($result){
echo "true";
}
}
you are not posting a POST var called "Submit" so your
if(isset($_POST['Submit']))
will always evaluate to false and your mysql query is never executed.

Ajax won't post form data to PHP script

I got a form with some data that needs to be sent and I want to do it with ajax. I got a function that respond on an onclick event of a button. When I click the button I got some post data in firebug but it just doesn't reach my PHP script. Does anyone know what's wrong?
JS:
function newItem() {
var dataSet = $("#createItem :input").serialize();
confirm(dataSet); //Below this code box is the output of this variable to check whether it is filled or not
var request = $.ajax({
type: "POST",
url: "/earnings.php",
data: dataSet,
dataType: "json"
});
request.done(function(){
$('.create_item').children(".row").slideUp('100', 'swing');
$('.create_item').children("h2").slideUp('100', 'swing');
confirm("succes");
});
request.fail(function(jqXHR, textStatus) {
confirm( "Request failed:" + textStatus );
});
}
dataSet result when the form is completly filled in:
id=123&date=13-09-2013&amount=5&total=6%2C05&customer=HP&invoicenumber=0232159&quarter=1&description=Test
The PHP:
<?php
include('includes/dbconn.php');
function clean_up($string){
$html = htmlspecialchars($string);
$string = mysql_real_escape_string($html);
return $string;
}
if($_POST){
$date = clean_up($_POST['date']);
$amount = clean_up($_POST['amount']);
$total = clean_up($_POST['total']);
$customer = clean_up($_POST['customer']);
$invoicenumber = clean_up($_POST['invoicenumber']);
$quarter = clean_up($_POST['quarter']);
$description = clean_up($_POST['description']);
$sql = ("INSERT INTO earnings (e_date, e_amount, e_total, e_customer, e_invoicenumber, e_quarter, e_description)
VALUES ($date, '$amount', '$total', '$customer', $invoicenumber, $quarter, '$description')");
echo $sql;
if($mysqli->query($sql) === true){
echo("Successfully added");
}else{
echo "<br /> \n" . $mysqli->error;
}
}
?>
The form works fine without the ajax but with it it just doesn't work.
Your help is appreciated!
Try this snippet code bro...
<form id="F_login">
<input type="text" name="email" placeholder="Email">
<input type="password" name="password" placeholder="Password">
<button id="btn_login" type="submit">Login</button>
</form>
$("#btn_login").click(function(){
var parm = $("#F_login").serializeArray();
$.ajax({
type: 'POST',
url: '/earnings.php',
data: parm,
success: function (data,status,xhr) {
console.info("sukses");
},
error: function (error) {
console.info("Error post : "+error);
}
});
});
Reply me if you try this...
prevent your form submitting and use ajax like this:
<form id="createItem">
<input id="foo"/>
<input id="bar"/>
<input type="submit" value="New Item"/>
</form>
$('#createItem).on("submit",function(e){
e.preventDefault;
newItem();
});
Try this
<input type="text" id="foo"/>
<input type="text" id="bar"/>
<input type="button" id="btnSubmit" value="New Item"/>
<script type="text/javascript">
$(function() {
$("#btnSubmit").click(function(){
try
{
$.post("my php page address",
{
'foo':$("#foo").val().trim(),
'bar':$("#bar").val().trim()
}, function(data){
data=data.trim();
// alert(data);
// this data is data that the server sends back in case of ajax call you
//can send any type of data whether json or json array or any other type
//of data
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>

JQuery issue on Ipad

I have a popup form on which a user provides a key to get access to the site. I validate the user provided key with Jquery. It is working fine on my local system but when I submit the form using ipad it does not work. The form is even nor submitted.
My Form is
<form name="form" method="post">
<div style="width:530px;">
<input style="display:none; height:25px;" id="downloadkey" name="downloadkey" type="text" />
<input style="display:none;" type="submit" id="submit" name="submit" value="<?php echo $variable['QUESTION_BUTTON']['value'] ?>"/>
</div>
<input type="hidden" id ="box_id" value="<?php echo $box_id ?>" />
</form>
JQuery is
$(document).ready(function() {
$('#submit').click(function(e) {
var key = $('#downloadkey').val();
var box_id = $('#box_id').val();
var dataString = {KEY:key, BID:box_id};
$.ajax({
url: "/home/validate_key",
type: 'POST',
data: dataString,
success: function(msg) {
if(msg=="false"){
alert("Your download key is either wrong or missing");
}
else{
$('#popupContact').hide();
$('#backgroundPopup').hide();
}
}
});
e.preventDefault();
});
});
In my controller the validate function is
function validate_key(){
$key = strtolower($this->input->post('KEY'));
$id = $this->input->post('BID');
$query = $this->db->get_where('mc_boxes', array('idmc_boxes' => $id));
$row = $query->row();
$download_key = strtolower($row->downloadkey);
if($download_key == $key){
$_SESSION['download_key'] = $key;
$_SESSION['timeout'] = time();
}
else{
echo 'false';
}
}
Do i need something special to make it working on ipad?
Thanks
jQuery.click() doesn't function properly on iOS.
Try using jQuery.on() or by binding other events like touchstart
.bind("click touch tap", function(){
// code
});
Is what I've seen used when dealing with iPad.
(It's not a CodeIgniter issue for sure.)

Send multiple checkbox data to PHP via jQuery ajax()

I want to submit a POST form that contains a textarea field and an input field(s) (type="checkbox" with an arbitrary/variable number of checkboxes) on my website via jQuery's .ajax(). PHP receives the textarea data and the ajax response is correctly displayed to the user. However, it seems that PHP is not receiving the checkbox data (was it checked, or not). How can I get this to work? Here is the code I have:
The HTML:
<form method="post" action="myurl.php" id=myForm>
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
...(maybe some more checkboxes - dynamically generated as necessary)
<input id="submit" type="submit" name="submit" value="Submit" onclick="submitForm()" />
</form>
The jQuery:
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: { myField:$("textarea[name=myField]").val(),
myCheckboxes:myCheckboxes },
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
Now, the PHP
$myField = htmlspecialchars( $_POST['myField'] ) );
if( isset( $_POST['myCheckboxes'] ) )
{
for ( $i=0; $i < count( $_POST['myCheckboxes'] ); $i++ )
{
// do some stuff, save to database, etc.
}
}
// create the response
$response = 'an HTML response';
$response = stripslashes($response);
echo($response);
Everything works great: when the form is submitted a new record is stored in my database, the response is ajaxed back to webpage, but the checkbox data is not sent. I want to know which, if any, of the checkboxes have been checked. I've read about .serialize(), JSON, etc, but none this has worked. Do I have to serialize/JSON in jQuery and PHP? How? Is one method better than another when sending form data with checkboxes? I've been stuck on this for 2 days. Any help would be greatly appreciated. Thanks ahead of time!
Yes it's pretty work with jquery.serialize()
HTML
<form id="myform" class="myform" method="post" name="myform">
<textarea id="myField" type="text" name="myField"></textarea>
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue1" />
<input type="checkbox" name="myCheckboxes[]" id="myCheckboxes" value="someValue2" />
<input id="submit" type="submit" name="submit" value="Submit" onclick="return submitForm()" />
</form>
<div id="myResponse"></div>
JQuery
function submitForm() {
var form = document.myform;
var dataString = $(form).serialize();
$.ajax({
type:'POST',
url:'myurl.php',
data: dataString,
success: function(data){
$('#myResponse').html(data);
}
});
return false;
}
NOW THE PHP, i export the POST data
echo var_export($_POST);
You can see the all the checkbox value are sent.I hope it may help you
var myCheckboxes = new Array();
$("input:checked").each(function() {
data['myCheckboxes[]'].push($(this).val());
});
You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push
Check this out.
<script type="text/javascript">
function submitForm() {
$(document).ready(function() {
$("form#myForm").submit(function() {
var myCheckboxes = new Array();
$("input:checked").each(function() {
myCheckboxes.push($(this).val());
});
$.ajax({
type: "POST",
url: "myurl.php",
dataType: 'html',
data: 'myField='+$("textarea[name=myField]").val()+'&myCheckboxes='+myCheckboxes,
success: function(data){
$('#myResponse').html(data)
}
});
return false;
});
});
}
</script>
And on myurl.php you can use print_r($_POST['myCheckboxes']);
$.post("test.php", { 'choices[]': ["Jon", "Susan"] });
So I would just iterate over the checked boxes and build the array. Something like.
var data = { 'user_ids[]' : []};
$(":checked").each(function() {
data['user_ids[]'].push($(this).val());
});
$.post("ajax.php", data);
You may also try this,
var arr = $('input[name="myCheckboxes[]"]').map(function(){
return $(this).val();
}).get();
console.log(arr);
The code you have at the moment seems to be all right. Check what the checkboxes array contains using this. Add this code on the top of your php script and see whether the checkboxes are being passed to your script.
echo '<pre>'.print_r($_POST['myCheckboxes'], true).'</pre>';
exit;

Categories