div id refresh on ajax success - javascript

I have a div at index.php which i want to refresh as the ajax call succeeds. I tried this. But it is not refreshing the div unless i refresh the whole page.
here is the code.
Div
<div id="cartContainer">
<div id="cart">
<li style="color: #515151">
<img id="cart_img" src="images/cart.png"> Cart <span class='badge' id='comparison-count'>
<?php
if(isset($_SESSION['cart'])&& !empty($_SESSION['cart']))
{
$cart_count=count($_SESSION['cart']);
echo $cart_count;
} else {
$cart_count=0;
echo $cart_count;
}
?>
</span>
</li>
<div id="sidebar">
<?php if(isset($_SESSION[ 'cart'])&& !empty($_SESSION[ 'cart'])){ ?>
<table id="s_table">
<?php foreach($_SESSION[ 'cart'] as $id=> $value){ ?>
<form class="product" method="get" action="index.php?">
<tr id="tr_s">
<input type="hidden" name="action" value="remove">
<input type="hidden" name="id" value="<?php echo $value['id'] ?>">
<td class="s_th">
<?php echo $value[ 'name']; ?>
<input type="hidden" name="name" value="<?php echo $value['name'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'quantity'] ?>
<input type="hidden" name="quantity" value="<?php echo $value['quantity'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'color']; ?>
<input type="hidden" name="color" value="<?php echo $value['color'] ?>">
</td>
<td class="s_th">
<?php echo $value[ 'size'] ?>
<input type="hidden" name="size" value="<?php echo $value['size'] ?>">
</td>
<td>
<button type="submit" id="btn_submit">Remove</button>
</td>
</tr>
</form>
<?php } ?>
<tr>
<td class="cart_btn" colspan="2">GO TO CART
</td>
<td class="cart_btn" colspan="2">CHECK OUT
</td>
</tr>
</table>
<?php } else { ?>
<p id="p_s"><i> "Your Cart is Empty"</i>
</p>
<?php } ?>
</div>
</div>
</div>
Ajax
<script>
$(document).ready(function() {
$('#addtocart').click(function(e) {
e.preventDefault();
var page = $("#page").val(),
action = $("#action").val(),
name = $("#name").val(),
id = $("#id").val(),
color = $("#color").val(),
size = $("#size").val(),
cat_id = $("#cat_id").val(),
s_cat_id = $("#s_cat_id").val(),
category = $("#category").val();
var proceed = true;
if (proceed) {
post_data = {
'Page': page,
'Action': action,
'Name': name,
'Cat_id': cat_id,
'S_cat_id': s_cat_id,
'Category': category,
'Id': id,
'Color': color,
'Size': size
};
$.post('add_cart.php', post_data, function(response) {
//load json data from server and output message
if (response.type == 'error') {
//output=$('.alert-error').html(response.text);
} else {
output = $("#cartContainer").load();
}
$(".alert-error").delay(3200).fadeOut(300);
}, 'json');
}
});
});
</script>

If you want to update the div with the return from you AJAX you would do something like this:
$.post('add_cart.php', post_data, function(response) {
$("#cartContainer").html(response);
}
Of course this depends on many things: the kind of data you're returning, what you wish to update, etc. It is hard to tell, from what you have posted, what your intent is.

Related

Get form ID and it's fields values dynamically from multiple forms

Inside a table, I've created multiple forms using a loop based on data inside database.
Now I am not getting a way to implement a logic by which I wanted to identify of which form submit button is pressed so that I can update data accordingly in database.
What I did is putted an ID of that particular row as submit button id, but I am not getting how to put the same ID in javascript file (separate file) to fetch the field details, can someone help?
<?php
foreach ($get_subscribed_data as $filtered_items) { ?>
<tr>
<form id="<?php echo $filtered_items->id; ?>" method="POST">
<td><input type="text" class="form-group" id="user_account_name" value="<?php echo $filtered_items->user_account_name; ?>"><?php echo $filtered_items->user_account_name; ?></td>
<td><input type="text" class="form-group" id="user_project_name" value="<?php echo $filtered_items->user_project_name; ?>"><?php echo $filtered_items->user_project_name; ?></td>
<td><input type="text" class="form-group" id="start_date" value="<?php echo $filtered_items->start_date; ?>"><?php echo $filtered_items->start_date; ?></td>
<td><input type="text" class="form-group" id="due_date" value="<?php echo $filtered_items->due_date; ?>"><?php echo $filtered_items->due_date; ?></td>
<td><input type="submit" id="<?php echo $filtered_items->id; ?>" class="btn-primary btn-sm">Submit</button></td>
</tr></form>
<?php } ?>
UPDATE:
jQuery code I am using:
$(document).ready(function() {
$('.row-submit').on('click', e => {
alert('test');
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
type: "POST",
url: ajaxurl,
action: "send_modification_training_data",
data: {
user_account_name: $tr.find('.user_account_name').val(),
user_project_name: $tr.find('.user_project_name').val(),
start_date: $tr.find('.start_date').val(),
due_date: $tr.find('.due_date').val(),
},
success: response => {
console.log(response);
}
});
});
});
I'm presuming that you're using AJAX to send the form data, otherwise you wouldn't need to know which form was submit as the browser will collate the data for you.
To retrieve the data related to the clicked submit button you need to correct your HTML. Firstly, you need to remove all id attributes from the HTML you generate in the PHP loop as it will create duplicate values which is invalid, they must be unique. Change them to classes instead. Secondly, you cannot place a form element as a child of a tr.
In fact, given that you're using a table here you cannot use a form at all, as there's no way to make the HTML valid. You need to collate the input data on each row. To do this you can use closest() to find the tr related to the button and retrieve the input values using find(). Something like this:
<?php foreach ($get_subscribed_data as $filtered_items) { ?>
<tr>
<td>
<input type="text" class="form-group user_account_name" value="<?php echo $filtered_items->user_account_name; ?>">
<?php echo $filtered_items->user_account_name; ?>
</td>
<td>
<input type="text" class="form-group user_project_name" value="<?php echo $filtered_items->user_project_name; ?>">
<?php echo $filtered_items->user_project_name; ?>
</td>
<td>
<input type="text" class="form-group start_date" value="<?php echo $filtered_items->start_date; ?>">
<?php echo $filtered_items->start_date; ?>
</td>
<td>
<input type="text" class="form-group due_date" value="<?php echo $filtered_items->due_date; ?>">
<?php echo $filtered_items->due_date; ?>
</td>
<td>
<button type="button" class="btn-primary btn-sm row-submit">Submit</button>
</td>
</tr>
<?php } ?>
$('.row-submit').on('click', e => {
e.preventDefault();
let $tr = $(e.target).closest('tr');
$.ajax({
url: 'your-handler.php',
type: 'POST',
data: {
user_account_name: $tr.find('.user_account_name').val(),
user_project_name: $tr.find('.user_project_name').val(),
start_date: $tr.find('.start_date').val(),
due_date: $tr.find('.due_date').val(),
},
success: response => {
console.log(response);
}
});
});

How to sent id from one page to another when click on submit?

I have a database which consists of question_id, question, and options. Where I'll display the question and options. When the user clicked on submit I want to store the option they clicked and the question_id.
I am able to store the option they clicked but want to know how to store the question_id.
$user_email = $_SESSION['email'];
$query1="SELECT * FROM votes WHERE user_email='$user_email'";
$query2="SELECT * FROM poll_question WHERE status='1'";
$fetch2 = mysqli_query($con,$query2);
<html>
<head>
<body>
<div class="container">
<br />
<br />
<br />
<div class="row">
<div class="col-md-6">
<?
while( $row2 = mysqli_fetch_array($fetch2))
{
?>
<form method="post" class="poll_form">
<h3><?echo $row2['question']?>?</h3>
<br />
<div class="radio">
<label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /><?echo $row2['option1']?></h4></label>
</div>
<div class="radio">
<label><h4><input type="radio" name="poll_option" class="poll_option" value=<?echo $row2['option1']?> /> <?echo $row2['option2']?></h4></label>
</div>
<br />
<?php
if( $count >0)
{ ?>
<button disabled="disabled" alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
<h>You selected : <? echo $row1['vote_option']; ?></h>
<br>
<p id="demo"></p>
<?php
}
else
{ ?>
<button alt="<?php echo $row2['question_id']; ?>" rel="<?php echo $user_email; ?>" class="btn btn-primary poll_option" title="<?php echo $ip; ?>">Submit</button>
<?
}
?>
</form>
<? }
} ?>
<br />
</div>
</div>
<br />
<br />
<br />
</div>
</body>
<script type="text/javascript">
$(document).ready(function(){
$(".poll_form").submit(function(event){
event.preventDefault(); //prevents the form from submitting normally
var poll_option = '';
$('button.poll_option').each(function(){
if($(this).prop("checked"))
{
poll_option = $(this).val();
var option=poll_option;
}
var url = '<?php echo SITE_URL; ?>';
});
$.post("poll_vote.php",$('.poll_form').serialize(),
function(data)
{
if(data=="User Created Success"){
window.setTimeout(function () {
location.href ="<?php echo SITE_URL; ?>poll.php";
}, 100);
}
else{
$("#result").html(data);
}
}
);
//to reset form data
});
});
<? } ?>
</script>
</html>
Using th below function I am sending the poll_option to other where I kept the inset operation. Now I want to send the question_id also
Create a hidden input filed in your form
<input type="hidden" name="question_id" value="<?php echo $row2['question_id']; ?>">
Create a hidden input field in your form.
<input type="hidden" id="question_id" name="question_id" value="<?= $row2['question_id'] ?>">
PHP solution:
In this case your question_id will be included in the POST.
You can then access it by calling $_POST['question_id'].
Jquery solution:
In Jquery you can also access it by:
$("#question_id").val();

Delete row in html table with checkbox using php and ajax

I need delete each row in html table using checkbox
Currently can delete row using link
I am using switch in my code in case delete query exist
Code php
<tr class="<?php if($i%2 == 0) { echo 'even'; } else { echo 'odd'; }
?>">
<td><div class="grid_content sno"><span><?php echo $i; ?>
</span> </div></td>
<td><div class="grid_content editable"><span><?php echo
$records['name_ar']; ?></span><input type="text"
class="gridder_input"
name="<?php echo encrypt("name_ar|".$records['id']); ?>"
value="<?php echo $records['name_ar']; ?>" /></div></td>
<td><div class="grid_content editable"><span>
<?php echo $records['name_en']; ?>
</span><input type="text" class="gridder_input"
name="<?php echo encrypt("name_en|".$records['id']); ?>"
value="<?php echo $records['name_en']; ?>" /></div></td>
<td>
<a href="<?php echo encrypt($records['id']); ?>"
class="gridder_delete"><img src="images/delete.png"
alt="Delete" title="Delete" /></a>
<input type="checkbox" name="delete[]"
value="<?php echo encrypt($records['id']); ?>" />
</td>
</tr>
case "delete":
$value = decrypt($_POST['value']);
$query = mssql_query("DELETE FROM Job_creation WHERE id = '$value' ");
break;
code ajax
// Function for delete the record
$('body').delegate('.gridder_delete', 'click', function(){
var conf = confirm('Are you sure want to delete this record?');
if(!conf) {
return false;
}
var ThisElement = $(this);
var UrlToPass = 'action=delete&value='+ThisElement.attr('href');
$.ajax({
url : 'ajax.php',
type : 'POST',
data : UrlToPass,
success: function() {
LoadGrid();
}
});
return false;
});
Many thanks in advance for those who help me :)

Submit PHP form does not pass php variable to javascript function

In a php application with I inherited (I am a php newbie) I have a php form with multiple includes. One of the includes has two tables set up and within each table is a form. The first form displays records retrieved from a MySQL database, so there could be 1 or more records returned. A while loop goes through the records and populates the controls with the data for each record (name, phone, email). The controls are named [fieldname<?php echo $line; ?>] - where $line starts at 1 and is incremented as the while loop goes through the records. This is working fine!
The problem comes when someone wants to edit one of the fields and submits the change. The form has an onsubmit="return validateForm(<?php echo $line; ?>);" I have checked to ensure that the $line variable does increment, but when it is sentto the javascript function "validateForm" the variable is not defined in the javasscript function. Originally I did I not pass the $line variable but the javascript function kept telling me that it could not get the value of the undefined element.
FIRST FORM CODE
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
<table border="0" cellspacing="0" cellpadding="0" class="forms">
<col width="20%"/>
<col width="80%"/>
<?php
if($user_access == 'National'){
$result = mysql_query("SELECT * FROM Profile ORDER BY profile_name");
}else{
$result = mysql_query("SELECT * FROM Profile WHERE profile_parent_region = '$user_profile' ORDER BY profile_name");
}
$line = 1;
while ($row_profile = mysql_fetch_array($result)){
$field_id = "_" . $line;
?>
<!-- LINE -->
<tr><td colspan="11"><hr class="view_line"></td></tr>
<!-- LINE -->
<tbody id="region<?php echo $field_id; ?>" >
<input class="field_long" name="profile_id<?php echo $field_id; ?>" id="profile_id<?php echo $field_id; ?>" type="hidden" value="<?php echo $row_profile[profile_id]; ?>"/>
<tr>
<td>
<label class="field_label" for="profile_parent_region<?php echo $field_id; ?>">Profile: </label>
</td>
<td align="left">
<select name="profile_parent_region<?php echo $field_id; ?>" id="profile_parent_region<?php echo $field_id; ?>" class="drop_med" >
<option></option>
<?php
if($user_access != 'National'){
$result_profile = mysql_query("Select Distinct profile_parent_region FROM profile where profile_parent_region = '$user_profile' ");
}else {
$result_profile = mysql_query("Select Distinct profile_parent_region FROM profile ORDER BY profile_parent_region ASC");
}
while($row = mysql_fetch_array($result_profile)){
echo '<option value ="'.$row['profile_parent_region'].'"';
if($row['profile_parent_region'] == $user_profile){
echo ' selected="selected"';
}
echo ' > ' . $row['profile_parent_region'] . '</option>';
}
?>
</select>
<span class="must_fill">* </span>
<label class="form_des" for="profile_parent_region<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td>
<label class="field_label" for="profile_name<?php echo $field_id; ?>">Region: </label>
</td>
<td align="left">
<select name="profile_name<?php echo $field_id; ?>" id="profile_name<?php echo $field_id; ?>" class="drop_med" >
<option></option>
<?php
$parent_region = $row_profile['profile_name'];
if($user_access != 'National'){
$result_region = mysql_query("Select Distinct region FROM regions where parent_region = '$user_profile' ");
}else {
$result_region = mysql_query("Select Distinct region FROM regions ORDER BY region ASC");
}
while($row = mysql_fetch_array($result_region)){
echo '<option value ="'.$row['region'].'"';
if ($row['region'] == $parent_region){
echo ' selected="selected"';
}
echo ' >' . $row['region'] . '</option>';
}
?>
</select>
<span class="must_fill">* </span>
<label class="form_des" for="profile_name<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_manager<?php echo $field_id; ?>" >Region's Manager's Name: </label></td>
<td>
<input class="field_long" name="profile_manager<?php echo $field_id; ?>" id="profile_manager<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_manager]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_manager<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_phone<?php echo $field_id; ?>" >Region's Contact Number: </label></td>
<td>
<input class="field_long" name="profile_phone<?php echo $field_id; ?>" id="profile_phone<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_phone]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_phone<?php echo $field_id; ?>"></label>
</td>
</tr>
<tr>
<td><label class="field_label" for="profile_email<?php echo $field_id; ?>" >Region's Contact E-mail: </label></td>
<td>
<input class="field_long" name="profile_email<?php echo $field_id; ?>" id="profile_email<?php echo $field_id; ?>" type="input" value="<?php echo $row_profile[profile_email]; ?>"/>
<span class="must_fill">*</span>
<label class="form_des" for="profile_email">This email address will also be used to advise of files added to a submitted order.</label>
</td>
</tr>
<tr align="center">
<td colspan="2" class="loginrow">
<br />
<input name="Login <?php echo $field_id; ?>" id="Login<?php echo $field_id; ?>" value="Update Profile" type="submit" class="submit_button"/>
<br />
<br />
</td>
</tr>
</tbody>
<?php
$line++;
}
?>
</table>
</form>`
JAVASCRIPT FUNCTION - location in "parent" php form
function validateForm(lineNum) {
if (lineNum == null) {
var x = document.forms["submit_order"]["file_name"].value;
if (x == null || x == '') {
alert("Missing File Name.");
return false;
}
var x = document.forms["submit_order"]["file_for"].value;
if (x == null || x == '') {
alert("Missing File Type.");
return false;
}
var x = document.forms["submit_order"]["OrderForm"].value;
if (x == null || x == '') {
alert("Missing File to Upload.");
return false;
}
}
Your code
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
is outside the loop of linenumbers - so what should $line be, but null?
You either need to move the form into the loop of linenumbers, generating a form per row, or apply the logic on the submit button in question.
If you go with a form per row, you don't even need the linenumber thingy, cause then there would be exactly one value per variable in the submitted array. This would be the preferable way, cause you don't need to submit all values, when you want to modify one row.
And for the validation itself, you also wouldn't need it, cause you could refer to the form in question.
<?php
$line = 0;
while ($row_profile = mysql_fetch_array($result)){
$field_id = "_" . $line;
?>
<form action="admin_profiles_main_update.php" method="post" name="submit_order" enctype="multipart/form-data" onsubmit="return validateForm(<?php echo $line; ?>);">
<!-- do all the row stuff -->
</form>
<?$line++; }?>

Can only post first result of while loop

I am using a while loop to display results from a query. The while loop is working fine. In hidden fields I would like to post the values of userID and accessID to the user details page. I am submitting the form using javascript to submit from a link. My problem is that regardless of the username I click I can only post the values for the first displayed record. What am I doing wrong?
The code:
<?php
while($row = $result->fetch_array()) { ?>
<form method="post" action="edit_user.php" id="userForm">
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
</form>
<?php } ?>
The javascript used for submitting the form:
function submitForm() {
var form = document.getElementById("userForm");
form.submit();
}
Thank you.
EDIT - I don't want to pass the values in the url.
you are generating multiple <form>s inside loop, move your <form> outside while loop, like:
<form method="post" action="edit_user.php" id="userForm">
<?php
while($row = $result->fetch_array()) { ?>
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID[]" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID[]" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
<?php } ?>
Submit
</form>
You're running into trouble because of this line
var form = document.getElementById("userForm");
In Javascript and HTML, an ID is supposed to be unique to a certain DOM element. In this case, you've got a whole load of form tags that have the same ID. You need to give each form a different ID, and then pass that ID to the submitForm function.
For example:
<?php
$id = 0;
while($row = $result->fetch_array()) { ?>
$id++;
<form method="post" action="edit_user.php" id="<?php echo "userForm".$id ?>">
<tr>
<td>
<?php echo $row['firstname'].' '.$row['surname']; ?>
<input type="hidden" name="userID" value="<?php echo $row['userID']; ?>" />
<input type="hidden" name="accessID" value="<?php echo $row['accessID']; ?>" />
</td>
</tr>
</form>
<?php } ?>
and then
function submitForm(id) {
var form = document.getElementById(id);
form.submit();
}
edit: how do I php? :D

Categories