My goal is to submit a set of variables to my AJAX function from with in a while loop in php. This is my first shot at using AJAX, so please excuse if it is messy, and not close to correct. I appreciate any assistance.
PHP FORM:
x=0;
while($row = mysql_fetch_array($retval, MYSQL_ASSOC))
{
$id = $row['col1'];
$ad = $row['col2'];
cho '<form id="msu_form">';
echo "<tr><td>{$ad}</td>";
echo "<td>";
$query2 = "SELECT col1,col2 FROM table WHERE notes = 'x'";
$result2 = mysql_query($query2);
$count2 = mysql_num_rows($result2);
if($count2 > 0)
{
echo '<select class="Primary" name="primary" onchange=doAjaxPost()>';
while($row2 = mysql_fetch_array($result2))
{
echo "<option value=".$row2['col1'].">".$row2['col2']."</option>";
}
echo "</select>";
}else
{
echo "Blah";
}
echo "</td>";
echo "<td>";
$query3 = "SELECT col1,col2 FROM table2 WHERE notes = 'y'";
$result3 = mysql_query($query3);
$count3 = mysql_num_rows($result3);
if($count3 > 0)
{
echo '<select class="Secondary" name="secondary">';
while($row3 = mysql_fetch_array($result3))
{
echo "<option value=".$row3['col1'].">".$row3['col2']."</option>";
}
echo "</select>";
}else
{
echo "Bah";
}
echo "</td>";
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
//echo '<td>'."<input type='submit' name='btnupdate' value='UPDATE' /></td>";
echo '</form>';
$x = $x+1;
}
So what happens is every time I change any of the "primary" select boxes on the screen, I get the value of the variables on the first line only. I want to receive the values of the form from the select box. I have tested it via a button, that submits the form it is commented out, but that button submits all the correct information to the page, but I don't want to submit the data every time. Is there a way to accomplish my goal?
Thanks - below the ajax if it helps with an answer.
<script>
function doAjaxPost() {
// get the form values
var primary = $(this).val();
var secondary = $(this).parent().next().child('.Secondary').val();
var hidden = $(this).parent().nextAll('.ID').val();
//var desc = $(this).parent().nextAll('#desc').val();
$.ajax({
type: "POST",
url: "functions/database_write.php",
data: $('#msu_form').serialize(),
//data: "Primary="+primary+"&Hidden="+hidden+"&Secondary="+secondary,
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
First, in your php code change the following 4 lines (using id)
echo "<select id=Primary name=primary onchange=doAjaxPost()>";
echo "<select id=Secondary name=secondary>";
echo '<input type="hidden" id="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" id="desc" name="desc" value="'.$ad.'"/>';
to (using class) edited
echo '<select class="Primary" name="primary" onchange="doAjaxPost(this)">'; //added (this)
echo '<select class="Secondary" name="secondary">';
echo '<input type="hidden" class="ID" name="ID" value="'.$id.'"/>';
echo '<input type="hidden" class="desc" name="desc" value="'.$ad.'"/>';
Then, in your javascript code, change
function doAjaxPost() {
var primary = $('#Primary').val();
var secondary = $('#Secondary').val();
var hidden = $('#ID').val();
var desc = $('#desc').val();
to edited
function doAjaxPost(sel) { // added (sel)
var primary = $(sel).val(); //changed to $(sel)
var secondary = $(sel).parent().next().children('.Secondary').val(); //changed to $(sel) and changed to children()
var hidden = $(sel).parent().nextAll('.ID').val(); //changed to $(sel) and changed to nextAll()
var desc = $(sel).parent().nextAll('#desc').val(); //changed to $(sel) and changed to nextAll()
If everything works fine when submitting normally, then probably you are generating the ajax data wrong, instead give your form an id:
echo '<form id="myform">';
Then serialize the form to get the correct data:
function doAjaxPost() {
$.ajax({
type: "POST",
url: "functions/data.php",
data: $('#myform').serialize(),
success: function(resp){
//we have the response
alert("'" + resp + "'");
},
error: function(e){
alert('Error: ' + e);
}
});
}
EDIT Ok you edit has cleared things up a bit, I didn't notice you have multiple forms.
Using the same doAjaxPost function as above, change the data property to:
data: $(this).parents('form').serialize();
Related
I have two buttons in html which are back and next.
If i click those buttons a variable gets incremented or decremented.
This variable is getting sent to a function.php where there is an sql statement.
The statement is:
select * from x where dimension is = value
How do I refresh the page to show my new table out of my query?
That is my php right here:
function tbl_showPage($page){
global $mysqlhost, $mysqluser, $mysqlpwd, $mysqldb;
$connection=mysqli_connect($mysqlhost, $mysqluser, $mysqlpwd) or die ("Verbindungsversuch fehlgeschlagen");
mysqli_select_db($connection, $mysqldb) or die("Konnte die Datenbank nicht waehlen.");
if($page<1)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='1'";
}
elseif($page>9)
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension='9'";
}
else
{
$sql_tbl_questions = "SELECT * FROM `questions` where istAktiv='1' && dimension=$page";
}
$quest_query = mysqli_query($connection, $sql_tbl_questions) or die("Anfrage nicht erfolgreich");
$i = 0;
while ($question = mysqli_fetch_array($quest_query)) {
$i++;
echo '<tr>';
echo '<th>'.$i.'</th>';
echo '<th>'.$question['question'].'</th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="0" required></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="2.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="7.5"></th>';
echo '<th class="text-center"><input type="radio" name="'.$question['dimension'].'_question_'.$question['id'].'" value="10"></th>';
echo '</tr>';
$dimensions = $question['dimension'];
}
echo '<tr>';
echo '<th></th>';
echo '<th>Kommentar/Ihre Anmerkung</th>';
echo '<th class="text-center" colspan=5><textarea rows=3 cols=50 name="Kommentar"></textarea></th>';
echo '</tr>';
echo '<input type="hidden" name="gesamt" value="'.$i.'">';
echo '<input type="hidden" name="dimensions" value="'.$dimensions.'">';
echo '<input type="hidden" name="size" value="'.$_POST['size'].'">';
echo '<input type="hidden" name="branche" value="'.$_POST['branche'].'">';
}
maybe my var is not beeing passed probably?
The javascript function is looking like that:
<script type="text/javascript">
var ki = kd = 1;
function increase()
{
ki++;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:ki}),
success: function(data){
console.log(data);
}
});
window.location.reload();
}
function decrease()
{
kd--;
$.ajax({
type: "POST",
url: 'inc/functions.php',
data: ({page:kd}),
success: function(data){
console.log(data);
}
});
window.location.reload();
}
</script>
I can't really figure out my problem, is my variable which I am generating in the function not passed properly, or is there another problem?
Seems as if you are mixing PHP and javascript here.
Do you have a onClick-function on your button? If you do, and a javascript function is called you can just add window.location.reload(); at the bottom of your javascript function to reload the page.
Tips: Use the edit function on your post and add code related to your problem, then it is easier to get help.
It is easy to make in JavaScript,
function myFunction() {
window.location.reload();
}
And then you just add the function to your button,
<button class="myButton" onclick=myFunction()">Click to reload</button>
Here, I am using session to store multiple textbox value.
But when I am going to fetch from session, I am getting the same value for all textbox which is in session.
My code:
if ($order_list) {
$i = $start +1;
foreach ($order_list as $row)
{
?>
<input type="text" name="<?php echo $row['id']; ?>" class="txt" autocomplete="off" id="txtid_<?php echo $row['id']; ?>" value="<?php if(isset($_SESSION['txtval'])) { echo $_SESSION['txtval'];} ?>">
<?php } ?>
In javascript:
$(document).on('blur','.txt',function(){
var myVar = $(this).val();
//alert(myVar);
$.ajax({
type: "GET",
url: "view_orders_checked_array.php",
data: {account: myVar, task: 'alltxt'},
async: false
});
});
In view_orders_checked_array.php :
$task = $_GET['task'];
if($task == "alltxt")
{
$_SESSION['txtval'] = $account;
}
Here, I am not getting the value of particular textbox. I am getting the value which I have last inserted.
Where I am going wrong?
Check below working code, if you just pass the id with your txtval and create session for each id key and value . Now when you print session array you will get all key values in session array. Please ask if difficult to understand.
Javascript
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<?php
session_start();
$_SESSION['txtval'] = '';
$order_list[0] = array('id'=>'1');
$order_list[1] = array('id'=>'2');
$order_list[2] = array('id'=>'3');
$order_list[3] = array('id'=>'4');
$start = '';
if ($order_list) {
$i = $start + 1;
foreach ($order_list as $row) {
?>
<input type="text" name="<?php echo $row['id']; ?>" class="txt" autocomplete="off"
id="txtid_<?php echo $row['id']; ?>" value="<?php if (isset($_SESSION['txtval'])) {
echo $_SESSION['txtval'];
} ?>">
<?php }
}?>
<script type="text/javascript">
$(document).on('blur','.txt',function(){
var myVar = $(this).val();
var myVarid = this.id;
$.ajax({
type: "GET",
url: "view_orders_checked_array.php",
data: {account: myVar, task: 'alltxt', id: myVarid },
async: false,
success:function(data){
console.log(data);
}
});
});
</script>
PHP file view_orders_checked_array.php
<?php
session_start();
$task = $_GET['task'];
if ($task == "alltxt") {
$_SESSION['txtval'][$_REQUEST['id']] = $_REQUEST['account'];
}
echo '<pre>';print_r($_SESSION['txtval'] );echo '</pre>';
die('Call');
you have to maintain array in session also so that you can do with the help of ids
var id=your loop id;
data: {account: myVar, task: 'alltxt',id:id },
and in your view_orders_checked_array page
$task = $_GET['task'];
$id=$_GET['id'];
if($task == "alltxt")
{
$_SESSION['txtval'][$id] = $account;
}
and in your code
<input type="text" name="<?php echo $row['id']; ?>" class="txt" autocomplete="off" id="txtid_<?php echo $row['id']; ?>" value="<?php if(isset($_SESSION['txtval'])) { echo $_SESSION['txtval'][$row['id']];} ?>">
i suggest you to use POST method for passing values
Problem is that you are putting the same value in all text fields
$_SESSION['txtval']
in your loop is always the same.
Edit
And also I think you getting same last inserted value because instead to store all text fields in array $_SESSION['txtval']['another_id_key'] you storing it in $_SESSION['txtval'] which is only one value
I am trying to delete rows from my sql database using checkbox. This is working fine as long as there is only one checkbox marked. But I also want it to be possible to delete multiple rows. I have seen many example, but I cant get it to work. Hope anyone here can help me.
So first the result.php file (here is all the rows / table created):
while ($row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_BOTH)) {
echo "<tr>";
echo "<td><input type='checkbox' name='id[]' class='toedit' value='" . $row[0] . "'></td>";
echo "<td>" . $row[1] . "</td>";
echo "<td>" . $row[2] . "</td>";
echo "</tr>";
}
echo "</table>";
This file is included in my main html (main.html) file, here is the Jquery as well.
Jquery sending chechbox variables to delete.php file:
<script type="text/javascript">
$(".deletelogg").on('click', function(){
$.ajax({
type: 'POST',
url: "php/delete.php",
data: {id:$('.toedit:checked:first').val()},
success: function(data) {
alert(data);
$("p").text(data);
}
});
});
</script>
Last in my delete.php file:
include 'connect-database.php';
for ($i = 0; $i < count($_POST['id']); $i++) {
if ($_POST['id'][$i] != "") {
echo $_POST['id'] ;
$sql = "DELETE FROM Logg Where LoggID LIKE '".$_POST['id']."'";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}
}
I was trying to make an array containing all id from the checkbox, but it didn't work.. any help pleas?
A working example: http://jsfiddle.net/Twisty/1y4zy5mn/
You should iterate over your checkboxes and collect the values. Given the following HTML:
<table>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="1" />
</td>
<td>One</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="2" />
</td>
<td>Two</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="3" />
</td>
<td>Red</td>
<td>Fish</td>
</tr>
<tr>
<td>
<input type="checkbox" name="id[]" class="toedit" value="4" />
</td>
<td>Blue</td>
<td>Fish</td>
</tr>
</table>
<button class="deletelogg">Delete</button>
<p></p>
Your JQuery will need to do a little more work. This should work for 1 or many:
$(".deletelogg").on('click', function () {
var ids = [];
$(".toedit").each(function () {
if ($(this).is(":checked")) {
ids.push($(this).val());
}
});
if (ids.length) {
$.ajax({
type: 'POST',
url: "php/delete.php",
data: {
id: ids
},
success: function (data) {
alert(data);
$("p").text(data);
}
});
} else {
alert("Please select items.");
}
});
With this, you can switch to a foreach() loop too:
include 'connect-database.php';
foreach ($_POST['id'] as $id) {
echo $id;
$sql = "DELETE FROM Logg Where LoggID = $id";
$stmt = sqlsrv_query( $conn, $sql);
if ($stmt == false) {
die( print_r(sqlsrv_errors(), true) );
}
}
I'd do it like this way: first make a "checkAll" checkbox, and when is checked, check all your check-boxes. Then at the end of your form, put the "delete" button. When this one is pressed, all the checked check-boxes are deleted. I think this works even for some of the check-boxes (if you only check some of them, not all of them).
<div id="content"></div>
<input type="checkbox" id="checkAll">
//get all the rows from db here, or make them manually
<input type="checkbox" class="check" name="checkbox" value="<?php echo $row->id;?>">
//...
Then, with this piece of js code, you can check them all, or some of them, and "send" them to a server-side script which will grab them, and delete them from the db.
var checkBoxes = document.getElementsByTagName('input');
var param = "";
var params = [];
for (var counter=0; counter < checkBoxes.length; counter++) {
if (checkBoxes[counter].type.toUpperCase()=='CHECKBOX' && checkBoxes[counter].checked == true) {
param += checkBoxes[counter].value+' ';
params = param;
}
}
$.ajax({
type: "POST",
url: "path/to/server/side/script",
data: { params:params },
success: function(resp){
$('#content').html(resp);
}
});
And for checking them all:
$("#checkAll").click(function(){
$(".check").prop('checked', $(this).prop('checked'));
});
I don't know if this is the best way, but is a point to start. Also, don't forget to secure your app.
I have some javascript that pulls some mysql data using xmlhttp.responsetext. I've been using it to populate form data for a drop down box and it has been working well. However, I have a need to add a second dropdown menu in the form and it is not working right.
What is happening is both dropdowns are populating with data from 2 different tables when each dropdown should only be getting its data from its respective table.
Could use some help figuring this out, thanks.
Here is the javascript code.
<script type="text/javascript">
var counter = 1;
function addInput(div){
xmlhttp=new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
var newdiv = document.createElement(div);
newdiv.innerHTML = "<table><tr><td>Line Item " + (++counter) + "</td></tr><tr><td width='190'>Item: <select name='item[]'>" + xmlhttp.responseText.split( "[BRK]" ) + "</select></td><td width='100'>Qty: <input name='quantity[]' type='text' size='2' /></td><td width='500'>Description: <input name='description[]' type='text' size='60' /></td><td width='150'>Amount: <input name='amount[]' type='text' size='6' /></td><td>Tax Rate: <select name='taxrate[]'>" + xmlhttp.responseText.split( "BRK" ) + "</select></td></tr></table><br />";
}
document.getElementById(div).appendChild(newdiv);
}
xmlhttp.open("GET", "dropdownquery.php", false);
xmlhttp.send();
}
</script>
And here is php.
<?php
include $_SERVER['DOCUMENT_ROOT']."/connect.php";
$result = mysql_query("SELECT * FROM salesitem");
$result2 = mysql_query("SELECT * FROM salestax");
while($row = mysql_fetch_array($result)) {
echo "<option value=\"".$row['name']."\">".$row['name']."</option>";
}
echo "[BRK]";
while($row2 = mysql_fetch_array($result2)) {
echo "<option value=\"".$row2['amount']."\">".$row2['name']."</option>";
}
echo "[BRK]";
?>
When you split a string, you get an array. I suppose you want to do this:
var splitResponse = xmlhttp.responseText.split( "[BRK]" );
var firstDropdownContent = splitResponse[0];
var secondDropdownContent = splitResponse[1];
Then use the two new variables to build your HTML.
What i have is a array of items from my mySQL database and each item has a checkbox. i am trying to make it so when you click on the checkbox it will submit the information to the database for the item that got checked or unchecked. have i have it is unchecked = 1 and checked = 0. this is for where i want to display the item.
Now my issue is I can't seem to get anything to submit into my database, I don't understand jQuery enough to be able to write a function for it, so i need some help. here is what i got for my code.
if(isset($_POST['submit'])){
foreach($_POST['id'] as $id){
$value = (isset($_POST['location'][$id]) && $_POST['location'][$id]=="0" ? '0' : '1');
$insert = mysql_query("UPDATE items SET location='$value' WHERE id='$id'") or die('Insert Error: '.mysql_error());
}
}
echo '<form id="form1" method="post"><input type="submit" name="submit" value="Submit">';
$result = mysql_query("SELECT * FROM items")
or die("Query Failed: ".mysql_error());
$counter = 0;
echo '<div class="specialcontainer">';
while($row = mysql_fetch_array($result)){
list($id, $item_info, $item_img, $price, $sale, $location) = $row;
if($location == '0'){
$set_checked = ' checked="checked" ';
}else{
$set_checked = '';
}
if($counter % 5==0) {
echo '</div>';
echo '<div class="specialcontainer">';
}
echo '<div class="special"><img src="../images/items/'.$item_img.'" width="130" /><br />';
echo $item_info.'<br />';
echo 'Reg. $'.$price.'<br />';
echo 'Sale $'.$sale.'<br />';
echo 'Slide Show: <input type="checkbox" id="ch" value="0" name="location['.$id.']"'.$set_checked.' /><br />';
echo '<input type="button" value="Edit" name="edit" onclick="window.location.href=\'specials.php?action=edit&id='.$id.'\'">';
echo '<input type="button" value="Delete" name="Delete" onclick="window.location.href=\'specials.php?action=delete&id='.$id.'\'">';
echo '<input type="hidden" name="id[]" value='.$id.' />';
echo '</div>';
$counter++;
}
echo '</div>';
echo '<input type="submit" name="submit" value="Submit"></form>';
so as you can see, i do have the submit button there, but my plan is to remove it for the onChange submit. I've tried the onchange="this.form.submit();" in the checkbox parameter but it don't work properly. so i just want it to submit anytime a checkbox gets clicked on kinda thing.
Would an Ajax solution like this work?
$('ch').click(function() {
//this is what goes into $_POST
var data = 'id='+ $(this).attr('name') +'&checked=' + $(this).is(':checked');
$.ajax({
//This would be the url that would handle updating the MySQL Record
url: my_mysql_handler.php,
cache: false,
type: 'POST',
data: data,
success: function(response) {
alert(response); //or whatever you want to do with the success/fail notification
}
});
});
You should try document.getElementById('form1').submit() in the onchange method of your checkbox