Submitting AJAx form with multiple inputs in a php loop - php

I am trying to learn how to use Ajax to submit a form in a php loop. Can anybody see why the below code won't write to my database? If I take out the sname parts it works but only allows one column to be updated. Thanks in advance for your help
<!DOCTYPE html>
<html>
<head>
<?php include 'dbconnection.php';?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
// Add the counter id as an argument, which we passed in the code above
function chk(id)
{
// Append the counter id to the ID to get the correct input
var name=document.getElementById('name' + id).value;
var name=document.getElementById('sname' + id).value;
var dataString='name='+ name + '&sname=' + sname;
$.ajax({
type:"post",
url: "dataInsert2.php",
data:dataString,
cache:false,
success:function(phtml){
// Instead of using the class to set the message, use the ID,
// otherwise all elements will get the text. Again, append the counter id.
$('#msg' + id).html(phtml);
}
});
return false;
}
</script>
</head>
<body>
<?php
$query=mysqli_query($connect,"SELECT distinct first_name from people " );
// Initiate a counter variable
$i = 1;
while ($row=mysqli_fetch_array($query))
{
?>
</br> <?php echo$row["first_name"]; ?>
<form>
<!-- Extra input added here
Append the counter to the ID -->
<input type="text" id="name<?= $i ?>">
<input type="text" id="sname<?= $i ?>">
<br/>
<!-- Send just the current counter to your method -->
<input type="submit" value="submit" onclick="return chk('<?= $i ?>')">
</form>
<!-- Append the counter to the message ID -->
<p id="msg<?= $i ?>" class="msg1"></p>
<?php
// Increment the counter
$i++;
}
?>
</body>
</html>
dataInsert2.php
<?php
include 'dbconnection.php';
$notes = $_POST['name'];
$class = $_POST['sname'];
mysqli_query($connect, "INSERT INTO people(class, notes)
VALUES ('$class','$notes')");
?>

Assuming your php loop is syntactically and grammatically correct,
The below function should be called whenever you click that Button.
function chk(id)
{
// Append the counter id to the ID to get the correct input
var name=document.getElementById('name' + id).value;
var name=document.getElementById('sname' + id).value;
var dataString='name='+ name + '&sname=' + sname;
$.ajax({
type:"post",
url: "dataInsert2.php",
data:dataString,
cache:false,
success:function(phtml){
// Instead of using the class to set the message, use the ID,
// otherwise all elements will get the text. Again, append the counter id.
$('#msg' + id).html(phtml);
}
});
return false;
}
In the third line, during variable declaration, you have variable name it should be sname according to your logic.
var sname=document.getElementById('sname' + id).value;
Since that variable will not be found in the 4th line(when you use it), It is facing an error. So your code after that line wont be executed.

Related

Submitting AJAx form in a php loop

I have been searching for 3 weeks and can't seem to solve this issue. I am new to Ajax but have figured out how to use it to submit a single form. I am trying to learn how to use Ajax to submit a form in a php loop however. I think it has something to do with individual id's but I'm not sure how to create them. My programming below only allows me to submit the first form. Does anybody know how to fix this so I can submit the forms in the loop? Thank you very much in advance for your help
Here is my code so far
<!DOCTYPE html>
<html>
<head>
<?php include 'dbconnection.php';?>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
function chk()
{
var name=document.getElementById('name').value;
var dataString='name='+ name;
$.ajax({
type:"post",
url: "dataInsert.php",
data:dataString,
cache:false,
success:function(phtml){
$('.msg1').html(phtml);
}
});
return false;
}
</script>
</head>
<body>
<?php
$query=mysqli_query($connect,"SELECT distinct first_name from people " );
while ($row=mysqli_fetch_array($query))
{
?>
</br> <?php echo$row["first_name"]; ?>
<form>
<input type="text" id="name">
<br/>
<input type="submit" value="submit" onclick="return chk()">
</form>
<p id="msg" class="msg1"></p>
<?php
}
?>
</body>
</html>
dataInsert.php
<?php
$name=$_POST['name'];
echo "Response: ".$name;
?>
<?php
include 'dbconnection.php';
$first_name = $_POST['name'];
mysqli_query($connect, "INSERT INTO people(first_name)
VALUES ('$first_name')");
?>
Any help would be really appreciated
Since id's must be unique through out the HTML-document, you need to give each field a different id. That goes for all id's on element (like the msg as well) When that's done, you can pass that id to your method, making your js-function reusable.
The loop (see the comments to see the changes):
<?php
$query=mysqli_query($connect,"SELECT distinct first_name from people " );
// Initiate a counter variable
$i = 1;
while ($row=mysqli_fetch_array($query))
{
?>
</br> <?php echo$row["first_name"]; ?>
<form>
<!-- Append the counter to the ID -->
<input type="text" id="name<?= $i ?>">
<br/>
<!-- Send just the current counter to your method -->
<input type="submit" value="submit" onclick="return chk('<?= $i ?>')">
</form>
<!-- Append the counter to the message ID -->
<p id="msg<?= $i ?>" class="msg1"></p>
<?php
// Increment the counter
$i++;
}
?>
The js-function (again, see the comments to see the changes):
// Add the counter id as an argument, which we passed in the code above
function chk(id)
{
// Append the counter id to the ID to get the correct input
var name=document.getElementById('name' + id).value;
var dataString='name='+ name;
$.ajax({
type:"post",
url: "dataInsert.php",
data:dataString,
cache:false,
success:function(phtml){
// Instead of using the class to set the message, use the ID,
// otherwise all elements will get the text. Again, append the counter id.
$('#msg' + id).html(phtml);
}
});
return false;
}
Now you should be able to send all forms seperate from eachother.

Alert id of contents fetched from php while loop using jquery

I am new to jquery and ajax. I have a PHP while loop which display contents from database. What I need is simply alert the "content_id" on click of each contents.
My script
<script type="text/javascript">
$(function() {
$(".show_id").click(function() {
var test = $(".contentid").val();
alert(test);
});
</script>
PHP Code
//code to fetch contents from database
foreach($stmt as $row)
{
echo $row['content'];
?>
<form action="" method="post">
<input type="hidden" class="contentid" value="<?php echo $row['content_id']; ?>">
<div class="show_id" ></div>
</form>
<?php
}
?>
It Alerts the id for each content, But only the first id always .
How to alert id for each contents respectively ?.
Thanks for any help...
This would work:
$(function() {
$(".show_id").click(function() {
var cur = $(".show_id").index($(this)); // get the index of the clicked button within the collection
var test = $(".contentid").eq(cur).val(); // find the input with the contentid class at the same index and get its value
alert(test);
});
});
Note that this assumes that the two classes are always paired together like you show and not used elsewhere in your html, which seems a reasonable assumption here
<script type="text/javascript">
$(function() {
$(".show_id").click(function() {
var test = $(this).prev(".contentid").val();
alert(test);
});
})
</script>

posting array of text fields using jquery and ajax

i dont want to use serialize() function please help me with this. I am a beginner
html
<input type='button' value='Add Tier Flavor' id='Add'>
<input type='button' value='Remove Tier Flavor' id='Remove'>
<div id='batch'>
<div id="BatchDiv1">
<h4>Batch #1 :</h4>
<label>Flavor<input class="textbox" type='text' id="fl1" name="fl[]" value=""/></label></br>
<label>Filling<input class="textbox" type='text' id="fi1" name="fi[]" value="" /></label></br>
<label>Frosting<input class="textbox" type='text' id="fr1" name="fr[]" value=""/></label></br>
</div>
</div>
<br>
</div>
this is a dynamically added fields using javascript the code is:
javascript
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#Add").click(function () {
if(counter>5){
alert("Only 5 Tiers allow");
return false;
}
var newBatchBoxDiv = $(document.createElement('div')).attr("id", 'BatchDiv' + counter);
newBatchBoxDiv.html('<h4>Batch #'+ counter + ' : </h4>' +
'<label> Flavor<input type="text" name="fl[]" id="fl' + counter + '" value=""></label><br>'+
'<label> Filling<input type="text" name="fi[]" id="fi' + counter + '" value=""></label><br>'+
'<label> Frosting<input type="text" name="fr[]" id="fr' + counter + '" value=""></label><br>' );
newBatchBoxDiv.appendTo("#batch");
counter++;
});
$("#Remove").click(function () {
if(counter==1){
alert("No more tier to remove");
return false;
}
counter--;
$("#BatchDiv" + counter).remove();
});
});
</script>
i am trying to post the values in an array to post it onto next .php page
i am using this
var user_cupfl = $('input[name^="fl"]').serialize();
var user_cupfi = $('input[name^="fi"]').serialize();
var user_cupfr = $('input[name^="fr"]').serialize();
serialize is not passing the values. :(
on second page i am trying to mail it using
$message .= "<tr><td><strong>Cake Flavors(according to batches):</strong> </td><td><pre>" .implode("\n", $user_cupfl). "</pre></td></tr>";
$message .= "<tr><td><strong>Filling type (Inside the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfi). "</pre></td></tr>";
$message .= "<tr><td><strong>Frosting type (top of the cake):</strong> </td><td><pre>" .implode("\n", $user_cupfr). "</pre></td></tr>";
i m posting array like this
$user_cupfl=filter_var($_POST["userCupfl"], FILTER_SANITIZE_STRING);
$user_cupfi=filter_var($_POST["userCupfi"], FILTER_SANITIZE_STRING);
$user_cupfr=filter_var($_POST["userCupfr"], FILTER_SANITIZE_STRING);
your replies will be highly appreciated
Just because you name a variable user_* doesn't mean that is what the name of the field is in the serialized POST data. You would still be looking for $_POST['fl'], $_POST['fi'] etc.
I don't understand why you think you need to serialize sets of input groups individually. You should just serialize the whole form at once.
I also see no reason why you need to have all this logic around unique id's with the counter and what not. If you are not using id's at all, just drop them altogether.
You might also consider simply using clone techniques to generate your dynamically added fields. You could greatly simplify all that javascript code by doing these things.
A more reasonable implementation may look like this.
HTML (cleaning up your code - consistent use of double quotes around properties, better strategy for class and id usage, etc.)
<div id="batch">
<div class="batchDiv">
<h4 class="batchLabel">Batch #1 :</h4>
<label>Flavor</label>
<input class="textbox" type="text" name="fl[]" value=""/>
</br>
<label>Filling</label>
<input class="textbox" type="text" name="fi[]" value="" />
</br>
<label>Frosting</label>
<input class="textbox" type="text" name="fr[]" value=""/>
</br>
</div>
</div>
Javascript:
$(document).ready(function() {
$('#Add').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
if (count < 5) {
// get last batch div
var $newBatch = $existingBatches.last().clone();
// reset input values to empty string
$newBatch.find('input').val('');
// change batch label
count++;
$newBatch.find('.batchLabel').html('Batch #' + count + ' :');
// append to document
$newBatch.appendTo('#batch');
} else {
// alert or whatever
}
});
$('#Remove').click(function(){
var $existingBatches = $('.batchDiv');
var count = $existingBatches.size();
// delete last batch item if more than 1 exists
if(count > 1) {
$existingBatches.last().remove();
} else {
// alert or whatever
}
});
});
Now you haven't shown your AJAX code, but all you would need to do is something like:
var url = '/some/url';
var postData = $('[some form selector]').serialize();
var dataType = '...'; //whatever dataType you are expecting back
$.post(url, postData, function(){
// success handler
}, dataType));
Your data when then be available in PHP script at $_POST['fl'], etc.

How To Pass PHP Variables On jQuery Load?

I have code like this :
<?php
$username = 'johndoe';
?>
<head>
<script>
...
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});
...
</script>
</head>
<body>
...
<li><input type="hidden" value="001" class="block-hidden-input" />
<a href="#" id="manage-1" class="manage-content-link">
<img src="images/web-block/web-block1.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
<li><input type="hidden" value="002" class="block-hidden-input" />
<a href="#" id="manage-2" class="manage-content-link">
<img src="images/web-block/web-block2.jpg"/>
<span class="orange-notice">Click to Edit Content</span>
</a>
</li>
...
</body>
as you can see there, every time user click "manage-content-link" class, either manage-1, manage-2, ... or even manage-X (multiple li tags) jQuery will load "file-XXX.php". which XXX is actually value of hidden input in li tag.
but that "file-XXX.php" requires $username from PHP tags and ID itself, that is "manage-X". how to pass this 2 variables needed by "file-XXX.php", one from PHP and other from ID's?
Use jQuery's .ajax() instead of .load(): http://api.jquery.com/jQuery.ajax/
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val(),
this_id = self.attr('id');
$.ajax({
url: "file-" + file + ".php",
data: { username: "<?php echo $username;?>", id: this_id },
context: this,
success: function(data) {
$(this).next(".manage-content-wrap").find(".manage-content").html(data);
}
});
e.preventDefault();
});
If you want to keep the script external, you couldn't rely on php to echo the $username inside the script. So, you could add the username a few ways. You can make a hidden input somewhere in the page with the value equal to the username; you could attach the username to an element (like the body) as a data-username attribute; or you could just have a script block in the header that purely defined the username. For example:
<input type="hidden" name="username" value="<?php echo $username;?>>
Or:
<body data-username="<?php echo $username;?>">
Or:
<head>
<script>
var username = "<?php echo $username;?>";
</script>
</head>
In your <body> you can add a hidden field
<input type="hidden" value="<?=$username?>" id="username" />
and in your jquery,
$('a.manage-content-link').click(function (e) {
var self = $(this),
file = self.siblings('input[type="hidden.block-hidden-input"]').val();
var username = $("username").val(); //use this variable where ever you want
var ids = $(this).attr('id'); // this is the id
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php?id="+ids+"&username="+username); //and in php file usee $_GET
e.preventDefault();
});
$('a.manage-content-link').click(function (e) {
var self = $(this);
file = self.prev('.block-hidden-input').val();
self.next(".manage-content-wrap").find(".manage-content").load("file-" + file + ".php");
e.preventDefault();
});​
Instead of passing username from script, i would suggest you store username in a session and get that value inside php using $_SESSION['username'] otherwise it will cause you security issue in the future.
DEMO

Ajax Id Auto Incrementing

I will probably sound or look dumb by this but I need to learn. Check out the following part of a code:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
var yes = $("input#yes").val();
if (yes == "") {
return false;
}
var id = $("input#id").val();
if (id == "") {
return false;
}
var dataString = 'yes='+ yes + '&id=' + id;
//try insted this //alert (dataString);return false;
$.ajax({ type: "POST", dataType:'HTML',
//or the appropiate type of data you are getting back
url: "http://www.edshaer.com/EdinburgCISD/Gorena/Gorena.php", data: dataString,
//in the php file do $email = $_POST['email'];
//not a good practice but you can try with it and without it
success: function(data) {
$("#div").hide(data).fadeOut();
$("#div").html(data);
$("#div").show(data).fadeIn();
// Change the content of the message element
// Fade the element back in
} });
//ajax ends
return false; });
//click ends
});//document ready ends
My button ID that is being submitted in my html page is sending random numbers. For example
It can be:
$("#383").click(function() {
or it can be:
$("#521").click(function() {
My question is, how do I do it to auto increment the ID of the button clicked so that no matter what ID number is clicked it will still run the run the code smoothly... Right now I have this:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
Hopefully someone can help me... let me know if you need more info... Thank you in advanced...
Here is part of my HTML code... Hopefully it will be a little more understandable...
<?php
$data3 = mysql_query("SELECT * FROM `EdinburgCISDGorenamessage`
ORDER BY `ID` DESC LIMIT 0, 100")
or die(mysql_error());
echo "<div id=\"div\"> <table align=\"center\" width=\"570\">";
while($info3 = mysql_fetch_array( $data3 ))
{
$id = $info3['ID'];
}
?>
<form name="contact" id="post" method="post" action="">
<input id="id" value="<?php echo $id?>"/>
<input type="submit" class="buttonclass" id="<?php echo $id?>" name="<?php echo $id?>" value="Yes" />
<input type="submit" id="no<?php echo $id ?>" name="no<?php echo $id ?>" value=" No " /> </form>
I don' want to provide the whole code because its too messy and it doesn't go with the question... Let me know if you need anything else.
Use a class instead. Add a class to the button, and an incremental id you give it while printing it out in your html (I suppose you echo buttons in a loop?), and then just use one snippet:
$('.buttonclass').click(function(){
var button_id = $(this).attr('id');
$('#'+button_id).click(function(){
// your function here
alert(button_id); // just to see if ID is retrieved
)};
});
So, if you have
<button id="325" class="buttonclass" type="button">BUTTON 325</button>
<button id="150" class="buttonclass" type="button">BUTTON 150</button>
The ID of the button you click is retrieved only when you press it

Categories