How to get value from multiple input fields on different class? - php

I have form like this:
<div class="satu">
<input type='text' size='1' maxlength='1' name='score[1][]' id='score[1][]'>
</div>
<div class="dua">
<input type='text' size='1' maxlength='3' name='weight[1][]' id='weight[1][]'> %
</div>
<div class="tiga">
<input type='text' size='5' name='weightscore[1][]' id='weightscore[1][]' disabled>
</div>
<div class="satu">
<input type='text' size='1' maxlength='1' name='score[2][]' id='score[2][]'>
</div>
<div class="dua">
<input type='text' size='1' maxlength='3' name='weight[2][]' id='weight[2][]'> %
</div>
<div class="tiga">
<input type='text' size='5' name='weightscore[2][]' id='weightscore[2][]' disabled>
</div>
this is the jquery script:
$('[id^="score"]').keyup(function()
{
var score=$('[id^="score"]').val();
var weight=$('[id^="weight"]').val();
$.ajax({
url: "cekweightscore.php",
data: "score="+score+"&weight="+weight,
success:
function(data)
{
$('[id^="weightscore"]').val(data);
}//success
});//ajax
});
this is the php code:
<?php
include "connection.php";
$score = $_GET['score'];
$weight = $_GET['weight'];
$totalweightscore=(($weight * $score )/ 100);
echo"$totalweightscore";
?>
When i keyup on score[1][], the value of weight[1][] is not coming out. PLease Help me, How to get value from multiple input fields on different class ??

Your code works for me for the first group of input elements. It would not work for the second set of elements because with .val you get "the current value of the first element in the set of matched elements". So when you keyup on score[2] the JS code actually sends the values of score[1] and weight[1], which may be empty.
To fix that one easy way is to wrap an element around each group of items so that you can easily target the "associated" weight element when keyup is triggered, like this:
<div class="group">
<div class="satu"><input type='text' name='score[1][]' id='score[1][]'></div>
<div class="dua"><input type='text' name='weight[1][]' id='weight[1][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[1][]' id='weightscore[1][]' disabled></div>
</div>
<div class="group">
<div class="satu"><input type='text' name='score[2][]' id='score[2][]'></div>
<div class="dua"><input type='text' name='weight[2][]' id='weight[2][]'> %</div>
<div class="tiga"><input type='text' name='weightscore[2][]' id='weightscore[2][]' disabled></div>
</div>
And the code would look like
<script type="text/javascript">
$('.satu input').keyup(function () {
var $satuInput = $(this);
var score = $satuInput.val();
var weight = $satuInput.closest(".group").find('.dua input').val();
$.ajax({
url: "cekweightscore.php",
data: "score=" + score + "&weight=" + weight,
success: function (data) {
$satuInput.closest(".group").find('.tiga input').val(data);
} //success
}); //ajax
});
</script>
I also changed the jQuery selectors to work with the classes in your HTML rather than the element ids; while the code should work either way, this style feels better to me.

you can get value with this
score.each (function () {
console.log(this.value);
});

Related

Ajax form submission within a php foreach loop

I am trying to use an ajax form submission for a list of forms generated by a php foreach loop. My issue is I obviously need to mark each generated form as unique and can't seem to figure it out. I thought to use the HTML data- attribute but cant seem to make it work.
Here is the code so
<?php
if (isset($_SESSION['team_mem_id'])) {
$query_team_matches = $conn->prepare($sql_team_matches);
$query_team_matches->bindParam(':tid', $tid, PDO::PARAM_INT);
$query_team_matches->execute();
$matches = $query_team_matches->fetchAll(PDO::FETCH_ASSOC);
if (!empty($matches)) {
foreach($matches as $Matches) {
$tmid = $Matches['tmid'];
$opponent = $Matches['opponent'];
$location = $Matches['location'];
$tm_datetime = $Matches['tm_datetime'];
$match_date = date("F j",strtotime($tm_datetime));
$match_time = date("g:i A",strtotime($tm_datetime));
$match_when = $match_date. " # ".$match_time;
?>
<div class='match_container'>
<div class='match_basic_info'>
<h3><?php echo $match_when.' - <span style="font-size: 16px">'.$location.' vs '.$opponent; ?></span></h3>
<a class='match_details_link' href='http://localhost:1234/tennisexcel/teams/match.php?r=team&tid=<?php echo $tid; ?>&tmid=<?php echo $tmid; ?>'>More info...</a>
</div>
<div id='match_avail_container' class='match_avail_container'>
<h3>My availability:</h3>
<form id='avail_submit_form' data-tmid='<?php echo $tmid; ?>' class="" action='http://localhost:1234/tennisexcel/test_ajax.php' method='POST'>
<input type='hidden' name='uid' value='<?php echo $_SESSION['uid']; ?>'/>
<input type='hidden' name='tid' value='<?php echo $_SESSION['tid']; ?>'/>
<input type='hidden' name='tmid' value='<?php echo $tmid; ?>'/>
<button class='match_avail_yes' type='submit' name='availability' value='1'>✔</button>
<button class='match_avail_no' type='submit' name='availability' value='2'>✖</button>
</form>
<div id="signup" data-tmid='<?php echo $tmid; ?>' class='match_avail_success success_display'>
<p>success!</p>
</div>
</div>
</div>
<?php
}
}
}
?>
I added a data-tmid='$tmid' to the form and the div that need to be marked as unique. The jquery is below:
$(document).ready(function() {
$('#avail_submit_form').submit(function(evt) {
evt.preventDefault();
var url = $(this).attr('action');
var fromData = $(this).serialize();
$.post(url, fromData, function(response) {
$('#avail_submit_form').hide();
$('#signup').removeclass('success_display');
}); //end post
}); //end submit
}); //end ready
I tried adding on [data-tmid='+$(this).attr('data-tmid')+'] to each id but not sure how to make it work properly or if it is even the correct way to do it.
Thank anyone who can lead me in the right direction!
Use a class instead of ID.
<div class='match_container'>
<div class='match_basic_info'>
<h3><?php echo $match_when.' - <span style="font-size: 16px">'.$location.' vs '.$opponent; ?></span></h3>
<a class='match_details_link' href='http://localhost:1234/tennisexcel/teams/match.php?r=team&tid=<?php echo $tid; ?>&tmid=<?php echo $tmid; ?>'>More info...</a>
</div>
<!-- fix #1 -->
<div class='match_avail_container'>
<h3>My availability:</h3>
<!-- fix #2 -->
<form data-tmid='<?php echo $tmid; ?>' class="avail_submit_form" action='http://localhost:1234/tennisexcel/test_ajax.php' method='POST'>
<input type='hidden' name='uid' value='<?php echo $_SESSION['uid']; ?>'/>
<input type='hidden' name='tid' value='<?php echo $_SESSION['tid']; ?>'/>
<input type='hidden' name='tmid' value='<?php echo $tmid; ?>'/>
<button class='match_avail_yes' type='submit' name='availability' value='1'>✔</button>
<button class='match_avail_no' type='submit' name='availability' value='2'>✖</button>
</form>
<!-- fix #3 -->
<div data-tmid='<?php echo $tmid; ?>' class='match_avail_success success_display'>
<p>success!</p>
</div>
</div>
</div>
I am assuming you only want to target the current form in your jQuery
$(document).ready(function() {
// add event handler to your forms
$('.avail_submit_form').submit(function(evt) {
evt.preventDefault();
// cache the current form object
var form = $(this);
var url = form.attr('action');
var fromData = form.serialize();
$.post(url, fromData, function(response) {
// make changes to current form and its related element
form.hide();
form.next('.match_avail_success').removeclass('success_display');
});
});
});

How to add/append PHP + HTML code in JQuery .append()

I'm trying to append PHP code in Jquery. I'm getting confused in the quotation marks and not getting correct result.
below code.
<script>
$(document).ready(function(){
$("#add").click(function(event){
event.preventDefault();
//var text_box = "<br>Fee type: <input type='text' name='f1[]'>amount : <input type='text' name='f2[]'><br>";
var text_box = "<?php
#Fee type textbox
if(form_error('feetype'))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
?>
<label for='feetype' class='col-sm-2 control-label'>
<?=$this->lang->line('invoice_feetype')?>
</label>
<div class='col-sm-6'>
<input type='text' class='form-control' id='feetype' name='feetype[]' value='<?=set_value('feetype')?>' >
</div>
<span class='col-sm-4 control-label'>
<?php echo form_error('feetype'); ?>
</span>
</div>";
$("#info").append(text_box);
});
<script>
You can use an AJAX call to execute a PHP script on the server. So, for your if statements, just send the variables with conditions to be tested to a php script via ajax and php will return the html code of the div which you can then append to an element.
As an example for your first div;
You can set up an ajax call like;
<script>
$(document).ready(function(){
$("#add").click(function(event){
event.preventDefault();
var part;
var test = 'feetype';
$.ajax({
type: 'POST',
url: "get_div.php",
data: {test:test},
success: function(result){
part = result;
}
})
var text_box = part + "<label for='feetype' class='col-sm-2 control-label'>"
/***
all other code here
***/
</script>
Then in your php script
<?php
#Fee type textbox
if(form_error($_POST['test']))
echo "<div class='form-group has-error' >";
else
echo "<div class='form-group' >";
Let me know if it helps or if you find a problem.

data not retrieve through formdata

I am trying to save image using ajax .and passing data through Formdata()
but at php file i can not retrieve data or image name please help me
here is my code
<form name='signup' id='signup'>
<div class="row">
<!--<form id="uploadimage" action="" method="post" enctype="multipart/form-data">-->
<div id="selectImage">
<label>Select Image</label>
<div id="image_preview">
<img id="previewing" src="uploaded_files/259700.png" height="150" width="150" />
</div>
<input type="file" name="file" id="file" required />
<!--<input type="submit" value="Upload" class="submit" />-->
</div>
<!--</form>-->
</div>
<div class='row'>
<p>
<label for='username'>First name</label>
<input type='text' name='firstname' id='firstname' value='' placeholder='Enter First name' />
</p>
</div>
<div class='row'>
<p>
<label for='lastname'>Last name</label>
<input type='text' name='lastname' id='lastname' value='' placeholder='Enter Last name' />
</p>
</div>
<div class='row'>
<p>
<label for='email'>Email</label>
<input type='text' name='email' id='email' value='' placeholder='Enter Email' />
</p>
</div>
<div class='row'>
<p>
<label for='phno'>Phno.</label>
<input type='text' name='phno' id='phno' maxlength="10" value='' placeholder='Enter ph no' />
</p>
</div>
<!--<input type="hidden" name="actionfunction" value="saveData" />-->
<input type="hidden" name="actionfunction" value="saveData" />
<div class='row'>
<input type='button' id='formsubmit' class='submit' value='Submit' />
<!--<input type='submit' id='formsubmit' class='submit' value='Submit' />-->
</div>
</form>
here is my ajax script code:
$("#signup").on('submit', (function() {
var fname = $("#firstname");
var lname = $("#lastname");
var email = $("#email");
var phno = $("#phno");
if (validateform(fname, lname, email, phno)) {
var formdata = new FormData(this);
$.ajax({
url: "DbManipute.php",
type: "POST",
data: formdata,
processdata: false,
cache: false,
contentType: false,
success: function(response) {
//alert(response);
if (response == 'added') {
$("#show_user").trigger("click");
getusers();
$("#msg").html("user added");
}
},
});
}
});
And here is my "DbManipute.php" code:
function saveData($data,$con){
$imgfile=$_FILES['file']['name'];
$fname = $data['firstname'];
$lname = $data['lastname'];
$email = $data['email'];
$phno = $data['phno'];
//$fname = $_POST['firstname'];
//$lname = $_POST['lastname'];
//$email = $_POST['email'];
//$phno = $_POST['phno'];
$sql = "insert into tbl_employees(emp_name,emp_lname,emp_email,emp_phno,emp_pic) values('$fname','$lname','$email','$phno','$imgfile')";
if($con->query($sql)){
echo "added";
} else {
echo "error";
}
}
i didn't get any error and data also not inserted.
when i remove image upload and use serialize method then data is saved successfully but in serialize method image file name can not retrieve
please help me regarding this.
You need to append the type="file" separately.
$("#signup").on('submit', (function() {
var fname = $("#firstname");
var lname = $("#lastname");
var email = $("#email");
var phno = $("#phno");
if (validateform(fname, lname, email, phno)) {
var formdata = new FormData(this);
formdata.append( 'file', $("input[name='file']")[0].files[0] );
$.ajax({
url: "DbManipute.php",
type: "POST",
data: formdata,
processdata: false,
cache: false,
contentType: false,
success: function(response) {
//alert(response);
if (response == 'added') {
$("#show_user").trigger("click");
getusers();
$("#msg").html("user added");
}
},
});
}
});
Your client side error will not be shown in the page just like php.
You have some errors in your javascript code. You have missed an closing parenthesis at the end of js code: });
If you are using chrome or firefox browser, press F12 button and console will be shown and will show you your js errors.
Tip: you can debug your project by printing any variables in your code. For example try to use console.log('test'); in your js code to check if your ajax command is working. console.log() will print in console box of browser.
When i did this in your code i understood that your code is not running at all. Because you have set your code to be run on submit and you do not have any submit button. Then you need to change your button's type="submit".
After that you need to prevent form by submitting the form using browser and tell browser that you want to run your js code. For that you need need to prevent default action for form submit event like this:
$("#signup").on('submit', (function(evt) {
evt.preventDefault();
Another tip is that your php code is in a function that is never called. you need to call your php function in your php file or you should put your codes out of function.
Try changing your code like this. This should make your code work. And to check if your ajax request is working try to echo something in your code and in your js code alert the response.
Edit#1 One more thing to consider is that for cases that you want to upload files using ajax, you can not set data like FormData(this). For ajax uploading purpose you should create object of FormData (new FormData()) and append the data separately. (as Rejith R Krishnan said).

Processing forms with jQuery

I have some PHP code that generates out a bunch of store items from my database. Each item has a quantity text box and an add to cart submit button and a hidden value with the special ID.
Here is basically how my form is generated:
<form class='form-inline' id='addtocart_form' action='
additem.php?iid=$SaleItem_Id&u=".$_SESSION['id']." ' method='post' role='form'>
<div class='form-group'>
<div class='input-group'>
<input type='text' class='form-control' style= 'float: left; width:50%;' id='quantity'
name='quantity' value='0'></input>
<button type='submit' name='add_to_cart' id='add' class='btn btn-success'>Add to
Cart</button>
</div>
<input type='text' name='$SaleItem_Id' style='display: none;' id='$SaleItem_Id'
value='$SaleItem_Id'>
</form>
My cart works perfectly, except it refreshes and puts you back up to the top of the screen. So then I decided to implement jQuery. All of these generated forms have the same id: addtocart_form.
$(function() {
$("#addtocart_form").on('submit' , function(e) {
e.preventDefault();
var thisForm = $(this);
var quantity = $("#quantity").val();
var dataString = $("#addtocart_form").serialize();
$.ajax({
type: "POST",
url: thisForm.attr('action'),
data: dataString,
});
$("#quantity").val("0");
return false;
});
});
The first item that is displayed on the screen works perfectly. It adds the item to the cart without refreshing the screen.
All of the other forms on the page are being submitted without the jQuery. They add the item, but redirect to the URL of my action.
How can I fix this without rewriting my entire store? I assume it has something with which form is being told to submit.
The id attribute should be unique in same document so try to replace the id addtocart_form by class, and all the other id's by classes to avoid duplicated id.
HTML :
<form class='form-inline addtocart_form' action=...
JS :
$("body").on('submit', '.addtocart_form', function(e) {
e.preventDefault();
var quantity = $(this).find(".quantity").val();
var dataString = $(this).serialize();
var action = $(this).attr('action')
$.ajax({
type: "POST",
url: action,
data: dataString,
});
$(this).find(".quantity").val("0");
return false;
});
Hope this helps.
You should not have more than one element with the same id on a page. If all of your forms use the same id, that's a problem.
Since you are using JQuery with AJAX, there's really no need to use a form at all. Just use a regular button (type="button") and tie a click event to it. Find the parent div of the button and get the values of the inputs within that div.
If your markup looks like this:
<div class='form-group'>
<input type='text' class='form-control quantity' style='float: left; width:50%;' value='0'>
<button type='button' class='btn btn-success add'>Add to Cart</button>
<input type='text' style='display: none;' class='saleItem_Id'>
</div>
<div class='form-group'>
<input type='text' class='form-control quantity' style='float: left; width:50%;' value='0'>
<button type='button' class='btn btn-success add'>Add to Cart</button>
<input type='text' style='display: none;' class='saleItem_Id'>
</div>
You can iterate over the inputs within the div like so:
$(".add").on('click', function() {
var parentDiv = $(this).closest("div");
//in this example, you only have one element, but this is how you would iterate over multiple elements
parentDiv.children('input').each(function() {
console.log($(this).prop('class'));
console.log($(this).val());
});
//do your ajax stuff
});
JS Fiddle demo

jquery popup div on click an element in a form

i have a form with four elements. i need to open a jquery popup when click on image that i set as fourth element in my form. popup window contains another form and a submit button. herepopup not coming. what wil i do.
this is my form
echo "<div class=\"addform\">
<form method='GET' action=\"update_events.php\">\n";
echo " <input type=\"hidden\" name=\"column1\" value=\"".$row['event_id']."\"/>\n";
echo " <input type=\"text\" name=\"column2\" value=\"".$row['event_name']."\"/>\n";
echo " <input type=\"text\" name=\"column3\" value=\"".$row['description']."\"/>\n";
echo " <input type=\"image\" src=\"images/update.png\" id=\"update_event\" alt=\"Update Row\" class=\"topopup\" onClick=\"callPopup(".$row['event_id'].")\"; title=\"Update Row\">\n";
}
echo "</table></form><br />\n";
this is my jquery
<script type="text/javascript">
function callPopup(id) {
console.log(id);
var datastring = "&event_id="+id;
$.ajax({
url: 'event_edit_popup.php', //enter needed url here
data: datastring,
type: 'get', //here u can set type as get or post
success: function(data) {
$('.popupContent').html(data);
console.log(data);
$('.loader1').hide();
$("#popup_content").after(data);
// u can see returned data in console log.
// here, after ajax call,u can show popup.
}
});
};
</script>
and this is my popup div
<div id="toPopup">
<div class="close"></div>
<span class="ecs_tooltip">Press Esc to close <span class="arrow"></span></span>
<div id="popup_content"> <!--your content start-->
<p align="center">edit company</p>
</div> <!--your content end-->
</div> <!--toPopup end-->
<div class="loader"></div>
<div id="backgroundPopup"></div>
You just need to give the image an id.. say id="clickme"
and in the jquery script:-
$('document').ready(function(){
$('#clickme').click(function(){ $('#topopup').show(220);}); });
Again u can add in transitions in the css of the topopup to give it various effects.
Also to hide the pop up:-
$('document').ready(function(){
$('#backgroundPopup').click(function(){ $('#topopup,#backgroundPopup').hide(220);}); });
//This is assuming that you want the popup to be closed when u click on the background
First mistake in your form is not complete and second is there is no input type='image' if you want to display image than you use image tag.
Please follow the code I hope it will be helpful to you:
<div class='addform'>
<form method='GET' action='update_events.php'>
<input type='hidden' name='column1' value="123"/>
<input type='text' name='column2' value="456"/>
<input type='text' name='column3' value="789"/>
<img src='images/update.png' id='update_event' alt='Update Row' class='topopup' onClick='callPopup("1")' title='Update Row'/>
</form>
</div>
Now jQuery code:
$("#update_event").click(function() { alert('sdf'); });
Now instead of alert you can use your ajax call for pop up.

Categories