Submitting AJAx form in a php loop - php

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.

Related

i want to do some functions with button. i want when i click on button it will be show result. result comes from database

i'm new in PHP i don't know howto use this function...output is a button but when i click on button function not run. i want to get data from database.
<?php include('config.php');
if (isset($_POST['submit'])) {
$sql = "SELECT book_name from books";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "book name: " . $row["book_name"]. "<br>";
}
} else {
echo "0 results";
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<form action="check.php" method="post">
<input type="submit" name="btn">
</form>
</body>
</html>
Just change isset($_POST['submit']) by isset($_POST['btn']).
When you submit your form, you send all the input name with $_POST method.
Here you have only ONE input with name = 'btn'.
I do this test :
<?php
if (isset($_POST['btn'])) {
echo 'IT WORKS !';
}
?>
And it works for me, after clicking on "Valider" I got my echo :
Here is an example of how you can try to do it using jQuery and Ajax. I tried to explain how it works and made an example that edit your book list without reloading the page on submit. Hope it helps !
$(document).ready(function() {
// When the form with id 'get_book_list' is sumbit, I will do something :
$("#get_book_list").on('submit', function(e) {
e.preventDefault();
// This is how an ajax call looks like (one example) :
// $.ajax({
// type: "POST", // the method you will use to send the data
// url: "yourfile.php", // the php file you want to call
// data : /* the data you want to send in your php file */,
// dataType: "json", // the data type you want to receive from the php file
// success: function(response){
// // Do something if the ajax call works : here you will edit your book list
// // 'response' is what the php will return, here imagine it's a JSON (dataType = 'json')
// },
// error: function(x,e,t){
// // Do something if the ajax call return error
// }
// });
//I will do the same but without the Ajax :
// 1/ Imagine you are in the success part of the ajax call
// 2/ This is the "response" you get from the php after the select :
var response = [{"book_name" : "title1"}, {"book_name" : "title2"}, {"book_name" : "title3"}];
// 3/ Now just edit your book_list to get what you want :
// I will build a list with each title
var book_list = "<ul>";
$.each(response, function(key, book) {
book_list += "<li>"+book.book_name+"</li>";
});
book_list += "</ul>";
// I add my list in my div
$('.book-list').html(book_list);
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!DOCTYPE html>
<html>
<head>
<title>test</title>
</head>
<body>
<div class="book-list">
<!-- here you will update the list of book -->
</div>
<form action="" method="post" id="get_book_list">
<input type="submit" name="btn">
</form>
</body>
</html>
your form actions says "check.php". As a result, when you hit the submit button, you get redirected to check.php page.
your form should simply be like
<form action="" method="post">
<input type="submit" name="btn">
</form>
when action="", the if part of your php will get executed for your current case
isset($_POST['submit']) is false, you should submit some info. you can add <input type="text" name="submit" value="1" />, lets your form have info.

Submitting AJAx form with multiple inputs in a php loop

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.

How to get result from php to html use ajax?

Updated: It still not work after I add "#".
I am new to ajax. I am practicing to send value to php script ,and get result back.
Right now, I met one issue which I can not show my result in my html page.
I tried serves answers online, but I still can not fix this issue.
My index.html take value from the form and send form information to getResult.php.
My getResult.php will do calculation and echo result.
How do I display result into index.html?
Hers is html code
index.html
<html>
<body>
<form name="simIntCal" id="simIntCal" method="post"
>
<p id="Amount" >Amount(USD)</p>
<input id="amount_value" type="text" name="amount_value">
<p id="annual_rate" >Annual Rate of Interest
(%)</p>
<input id="rate_value" type="text" name="rate_value">
<p id="time_years" >Time (years)</p>
<input id="time_value" type="text" name="time">
<input id="calculate" type="submit" value="Calculate">
</form>
<p id="amount_inteCal" >The Amount (Acount
+ Interest) is</p>
<input id="result" type="text">
</body>
</html>
ajax script :
<script>
$('#simIntCal').on('submit', function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'getResult.php',
data: $('#simIntCal').serialize(),
success: function (result) {
$("#result").text(result);// display result from getResult.php
alert('success');
}
});
});
</script>
getResult.php
<?php
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
//do some calculation
$result=10;//set result to 10 for testing
echo $result;
}
?>
You are missing the '#' in front of your css selector for result.
$("result").text(result);// display result from cal.php
Should be
$("#result").text(result);// display result from cal.php
index.php
----php start---------
if(isset($_POST['name'])){
echo 'Thank you, '.$_POST['name']; exit();
}
----php end ---------
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
function test(){
var formDATA = {'name': $('#input_name').val()}
$.ajax({
type: 'POST',
url: 'index.php',
data: formDATA,
success: function(response){
$('#result').html();
}
});
}
</script>
<input id="input_name" type="text" value="">
<button onclick="test();">Test Ajax</button>
<div id="result"></div>
Try something simple, this is a very basic version of ajax and php all in one page. Since the button triggers the function you don't even need a form (doesn't mean you shouldn't use one). But i left it simple so you could follow everything.
Sorry when i added php open and closing tags it didn't show up as code.
Also don't forget to include your jquery resources.
In your html file where you want the result to display, you probably want to be using a div.
Currently your code is using an input field:
<input id="result" type="text">
And what you probably want is something like this:
<div id="result"></div>
Unless you were intending to have the result show up in an input field inside your form, and in that case, the input field isn't actually inside your form code.

$_POST for text in DIV elements

Because of my web style, i don't want to use input & textarea and get information by using $_POST[] and i need to get information that is in DIV element.
For example , I want to get information in this :
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
and :
$_POST[myname];
But i can't do it with $_POST , How can i do it ??
And if this method can't do this , do you know any other method to get information from DIV like this ?
you can call a onsubmit function and make a hidden field at the time of form submission like this
HTML
need to give a id to your form id="my_form"
<form action="submit.php" method="post" id="my_form">
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="submit" value="submit" name="submit" />
</form>
Jquery call on submit the form
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.mine').text();
$(this).append("<input type='hidden' name='myname' value=' " + hvalue + " '/>");
});
});
PHP : submit.php
echo $_POST['myname'];
You can use this method. First, with javascript get content of <div>
Code:
<script type="text/javascript">
var MyDiv1 = Document.getElementById('DIV1');
</script>
<body>
<div id="DIV1">
//Some content goes here.
</div>
</body>
And with ajax send this var to page with get or post method.
You would need some JavaScript to make that work, e.g. using jQuery:
$.post('http://example.org/script.php', {
myname: $('.mine').text()
});
It submits text found inside your <div> to a script of your choosing.
You can use following structure;
JS:
$(document).ready(function() {
$("#send").on("click", function() {
$.ajax({
url: "your_url",
method: "POST",
data: "myname=" + $(".mine").text(),
success: function(response) {
//handle response
}
})
})
})
HTML:
<div class="mine" name"myname">
this is information that i want to get and put into database by PHP !
</div>
<input type="button" name="send" id="send" value="Send"/>
You can see a simulation here: http://jsfiddle.net/cubuzoa/2scaJ/
Do this in jquery
$('.mine').text();
and post data using ajax.
Put the content of DIV in a variable like below:
var x = document.getElementById('idname').innerHTML;

How can I pass a variable I defined in a jquery script to a PHP script?

My requirement is fairly simple...I want to drill down on a table row to display more detailed data below. Thanks to several posts here and elsewhere, the jquery API site and various other resources I am sooooo close, but there seems to be one critical element I am missing.
I am able, in a single page to enter a value and submit that value as a variable to my PHP script. And I am able using JQuery to click on a row in a table and have that pop up an alert that displays that data as a variable. But I cannot pass the Jquery variable to my PHP script. I have read so many posts with similar requirements, but none quite like this.
In the code below I want to use the $data variable that I have created when I click on a table row and post that to my PHP script.
Any guidance would be most appreciated. Code below:
Thanks,
Rob
<?php
require("dbconn.php");
?>
<html>
<head>
<title></title>
<table border='1'>
<tr>
<th>user_name</th>
<th>sec_level</th>
</tr>
<tr>
<td><a u_name="test">test</td>
<td>test</td>
</tr>
<tr>
<td><a u_name="goat">goat</td>
<td>goat</td>
</tr>
</table>
<script src="jquery-1.10.2.js"></script>
<script>
$("tr").click(function() {
var $data = ( $(this).find("a").attr("u_name") )
alert( $data );
});
</script>
<form method="post" action="">
<dl>
<dt>Hobby No.
<dd><input id="field_" name="dynfields[]" type="text">
</dl>
<input type="submit" name="submit_val" value="Submit" />
</form>
<?php if (!isset($_POST['submit_val'])) { ?>
<?php } ?>
<body>
<?php
if (isset($_POST['submit_val'])) {
if ($_POST['dynfields']) {
foreach ( $_POST['dynfields'] as $key=>$value ) {
$values = mysql_real_escape_string($value);
}
}
$q = "select * from my_hobbies where hobbies = '$values'";
$r = mysql_query($q);
while ($row=mysql_fetch_array($r,MYSQL_NUM))
{
echo '<br>'.$row[1];
}
mysql_free_result($r);
mysql_close();
}
?>
</body>
</html>
AJAX..
$(function(){
$(":submit").click(function(){
$.ajax({
type:"POST",
url:"Ajax.php",
data:"WebName="+$("#WebName").val(),
success:function(data){
//...
}
});
});
});

Categories