I have several advertisements. Each of them has a 'garage' button. If I click this button, it should insert his own userid and motorcycle id into the database. I think the insert method is good but something isn't good with the ajax. I get the success message back, but the data doesn't get inserted to my database.
<form action="" method="POST" id="upload-to-garage<?php echo $row['id']; ?>">
<div class="float-right">
<input type="hidden" value="<?php echo $row['id']; ?>" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage"></i></button>
</div>
</form>
$(document).ready(function() {
$("#upload-to-garage<?php echo $row['id']; ?>").submit(function(e) {
e.preventDefault();
$.ajax({
url: "upload-to-garage.php",
method: "post",
data: $("form").serialize(),
dataType: "text",
success: function() {
alert('success');
}
});
});
});
upload-to-garage.php
<?php
session_start();
require_once("config.php");
// Add to garage
if (isset($_POST['garage'])) {
$advertId = $_POST['advert-id'];
$userid = $_SESSION['id'];
$stmt = $link->prepare("INSERT INTO garage (userid, motorcycleid) VALUES (?, ?)");
$stmt->bind_param('ii', $userid, $advertId);
$stmt->execute();
$stmt->close();
}
?>
Just checked and if I skip the AJAX part and using the simple PHP, it works fine. So the problem is with the AJAX for sure, but can't see what.
You can change your event handler like this $("form[id*=upload-to-garage]") instead of using php code for ids and then use $(this) to refer current form.Also, when you use serialize function submit button value doesn't get send so you can attach that as well using ¶metername=somevalue
Demo Code :
$(document).ready(function() {
//form when submit
$("form[id*=upload-to-garage]").submit(function(e) {
console.log($(this).serialize() + "&garage=somevalue")
e.preventDefault();
$.ajax({
url: "upload-to-garage.php",
method: "post",
data: $(this).serialize() + "&garage=somevalue", //use this here
dataType: "text",
success: function() {
alert('success');
}
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="POST" id="upload-to-garage1">
<div class="float-right">
<input type="hidden" value="1" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage">i</i></button>
</div>
</form>
<form action="" method="POST" id="upload-to-garage2">
<div class="float-right">
<input type="hidden" value="2" name="advert-id">
<button type="submit" class="btn bg-transparent" name="garage"><i class="fas fa-warehouse fa-lg" data-toggle="tooltip" title="Place to my garage">i</i></button>
</div>
</form>
Related
Hello I am running a form using ajax submit functions using PHP and JS
bellow is my code
submit.php
<?php
if(isset($_POST['add_data'])){
echo "add id";
}
if(isset($_POST['update_data'])){
echo "update_id";
}
?>
Form.js
$('form.data').on('submit',function(){
var info = $(this),
url = info.attr('action'),
method = info.attr('method'),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
form.php
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button name="add_data" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>
<button name="update_data" value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
however the result I am getting is not correct if I click one of the button the console replies:
add idupdate_id
instead of one of the following
add id
or
update_id
On submit you are going to have the value set so isset will always return true. What you must do is:
if(!empty($_POST['add_data'])){
echo "add id";
}
The problem is that your form contains both add_data and update_data, so they will be always set in $_POST. If you want different action for each button, you could assign a function to the onClick event to both buttons, check which caused the event and pass it to your AJAX data.
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button name="add_data" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>
<button" name="update_data" value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
Then in your JS:
$("button").click(function(){
var info = $(this),
url = info.attr('action'),
method = info.attr('method'),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
data["action"] = ($(this).attr("name") === "add_data") ? 0 : 1; //If add_data -> 0 else -> 1
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
And then in your PHP, you look for $_POST["action"] variable
if($_POST["action"] == 0) {
echo "add_data";
} else {
echo "update_data";
}
EDIT: If you would like to, you don't have to check it in a condition, and just past the name attribute to data["action"] and then check in PHP, if $_POST["action"] is equal to add_data or update_data
Use next code for separating your button actions:
HTML:
<form method="POST" action="submit.php" class="data">
<input type="hidden" name="id" value="<?php echo $row['id']; ?>">
<button value="add" class="btn btn-label-success btn-sm mg-y-5"><i class="fa fa-link"></i>Add</button>
<button value="update" class="btn btn-label-warning btn-sm mg-y-5"><i class="fa fa-link"></i> Update</button>
</form>
JS:
$('form.data > button').on('click',function(){
var info = $(this).parent(),
url = info.attr('action'),
method = info.attr('method'),
task = $(this).val(),
data = {};
info.find('[name]').each(function(index, value){
var info= $(this),
name = info.attr('name'),
value = info.val();
data[name] = value;
});
data['task'] = task;
$.ajax({
url: url,
method: method,
data: data,
success: function(response){
console.log(response);
//refresh total
}
});
return false;
});
PHP:
if(isset($_POST['task']) && $_POST['task'] == 'add'){
echo "add id";
}
if(isset($_POST['task']) && $_POST['task'] == 'update'){
echo "update_id";
}
A form within for loop, in this form user add a excel file using input type file,
for ($i = 0; $i < 4; $i++) {
<form id="TypeValidation" method="" enctype="multipart/form-data">
<input type="hidden" id="pii_categoryid" name="pii_categoryid" value="<?php echo $i;?>" />
<div>
<span class="btn btn-rose btn-round btn-file">
<span class="fileinput-new">Select File</span>
<span class="fileinput-exists">Change</span>
<input type="file" name="<?php echo $i;?>_attachment" id="<?php echo $i;?>_attachment" accept=".xlsx, .xls, .csv" />
</span>
<i class="fa fa-times"></i> Remove
<button type="submit" name="add_file" id="add_file" value="<?php echo $i;?>_file" class="btn btn-success btn-round fileinput-exists">Upload</button>
</div>
</form>
}
This form is submit using jquery here is code
$("#TypeValidation").on('submit',(function(e)
{
var pii_categoryid = $(this).find('input[name="pii_categoryid"]').val();
var fileUploadID = $(this).find('button[name="add_file"]').val();
e.preventDefault();
$.ajax({
url: "fn_dsr_wizard_submit.php?submitid="+fileUploadID,
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
dataType: "html",
success: function (result) {
alert(result);
//prompt("Copy to clipboard: Ctrl+C, Enter", result);
location.reload();
if(result=='1'){
location.replace("ds_dashboard.php");
}else {
location.replace("ds_dashboard.php");
}
}
});
}
));
My form show like this
When user add client excel file then it is submitted but issue is that when user add donor file or other except client excel then its not submitted.
Try assign different ID and add a class name for each form like:
<form id="TypeValidation<?php echo $i; ?>" class="my-form" method="" enctype="multipart/form-data">
In javascript:
$(".my-form").on('submit',(function(e) { ...
Hey Everyone here is my question .
The code below gets data from my database and displays it both in an input field and a button. I want it to be in such a way that if i click the button it should get the value(which is imported from the db).But the problem i am facing is that all the inputs and buttons have the same ids so it only captures the value of the first button(or so i think). How can i make it in such a way that for every button i click it should have its own separate value.
<?php
$dbcon=mysqli_connect("localhost","root","");
mysqli_select_db($dbcon,"codex");
require('config/server.php');
?>
<table class="table table-striped">
<th>ID</th>
<?php
$view_users_query="select * from users";//select query for viewing
users.
$run=mysqli_query($dbcon,$view_users_query);//here run the sql
query.
while($row=mysqli_fetch_array($run))//while look to fetch the result
and store in a array $row.
{
?>
<!--here showing results in the table -->
<form id="loginForm" method="" action="" novalidate>
<tr>
<div class="panel2">
<main class="content">
<td><input name="hanis" id="hanis" type="text" value="<?php echo
$row['email']?>" autofocus /></td>
<td><button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata()" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button><</td>
</main></div>
</div>
</div>
</form>
<?php } ?>
</tr>
<script type="text/javascript">
function hanisdata() {
var hanis=$("hanis").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
NOTE :- Don't use same id for elements
You can get values by passing this with onclick function like onclick="hanisdata(this)"
Example
<button type="button" class="btn btn-success btn-block"
name="hanis" id="hanis" onclick="hanisdata(this)" value="<?php echo
$row['email']?>" ><?php echo $row['email']?></button>
Then you can get specific element in js and then can find parent and search for input field in that like below example.
JS CODE
<script type="text/javascript">
function hanisdata(el) {
var hanis=$(el).parent().find("input").val();
alert(hanis);
// AJAX code to send data to php file.
$.ajax({
type: "POST",
url: "hanis.php",
data: {hanis:hanis},
dataType: "JSON",
success: function(data) {
$("#message").html(data);
$("p").addClass("alert alert-success");
},
error: function(err) {
alert(err);
}
});
}
</script>
I'm trying to make an update status button which it's submited by ajax, but every single time when I update the status I get redirected on base_url().'/Admin/Jobs/'. It's possible to update the status without getting that redirect?
Code:
<?php if ($key['status'] === '1'): ?>
<?php echo form_open('Admin/update_job_status'); ?>
<input type="hidden" name="id" value="<?= $key['id'] ?>">
<input type="hidden" name="status" value="0">
<button class="btn btn-success btn-simple" id="submit" rel="tooltip" title="Status Active">
<i class="fas fa-eye"></i>
</button>
<?php echo form_close(); ?>
<script>
$(document).ready(function(){
$('#submit').on('click', function(){
var formData = {
'id' : $('#id').val(),
'status' : $('#status').val()
}
$.ajax({
type: 'post',
data: formData,
url: '<?php echo base_url().'/Admin/Jobs/' ?>',
success: function(data){
alert(id);
},
});
});
});
</script>
<?php endif ?>
<?php if (is_null($key['status']) || $key['status'] === '0'): ?>
<?php echo form_open('Admin/update_job_status'); ?>
<input type="hidden" name="id" value="<?= $key['id'] ?>">
<input type="hidden" name="status" value="1">
<button class="btn btn-warning btn-simple" rel="tooltip" title="Status Inactive">
<i class="fas fa-eye-slash "></i>
</button>
<?php echo form_close(); ?>
<script>
$(document).ready(function(){
$('#submit').on('click', function(){
var formData = {
'id' : $('#id').val(),
'status' : $('#status').val()
}
$.ajax({
type: 'post',
data: formData,
url: '<?php echo base_url().'/Admin/Jobs/' ?>',
success: function(data){
alert(id);
},
});
});
});
</script>
<?php endif ?>
You submit event is sent, because it is not stopped. You have to use event.stopPropagation() to prevent "natural" form submit.
$('#submit').on('click', function(event) { // add event parameter
event.preventDefault(); // stop form submit
//...
A button in a form by default is a submit button and if you click on it it will post your form back to the specified url.
You can explicitly set your button to be a normal button by setting the type attribute to button
<button type="button"...
or you can prevent the form from submitting via JavaScript in the event handler
$('#submit').on('click', function(event){
event.preventDefault();// prevents the default action, which is submitting the html form
...
Try this
$(document).ready(function(){
$('#submit').on('click', function(){
var formData = {
'id' : $('#id').val(),
'status' : $('#status').val()
}
$.ajax({
type: 'post',
data: formData,
url: '<?php echo base_url().'/Admin/Jobs/' ?>',
success: function(data) { alert(id); },
});
return false; // disable form submit
}); });
I have a column in Database with name URL and ID(PK) i'm using PHP/MYSQL
Im displaying values from db now i want to perform EDIT(update) operation Using Jquery/Ajax.
When i click on Edit link it is replaced with Update/Cancel links Which is working fine and im able to perform update operations.
My requirement is when i click on edit Url data which im using lable tag should replace with input textbox and i should perform update operation
HTML Code
<div class='col-md-4'>
<label class="feed_label" id="feed_label" idl='<?php echo $row->id;?>'><?php echo $row->url; ?></label>
<input name="url1" class="form-control url1 feed_text" value="<?php echo $row->id;?>" id="url1" type="text" placeholder="enter url" style="display:none;">
</div>
<div class='col-md-2'>
<a ide='<?php echo $row->id;?>' id="edit" class='edit' href="#" style="display:block-inline;">EDIT</a>
<a idu='<?php echo $row->id;?>' id="update" class='update btn btn-primary btn-sm' href='#' style='display:none;'>UPDATE</a>
<a idd='<?php echo $row->id;?>' id="delete" class='delete' href="#" style="display:block-inline;">DELETE</a>
<a idc='<?php echo $row->id;?>' id="cancel" class='cancel btn btn-warning btn-sm' href='#' style='display:none;'>CANCEL</a>
</div>
JQUERY CODE
JQUERY CODE
//EDIT,DELETE TO UPDATE,CANCEL
$('body').delegate('#edit','click',function(){
//alert();
$(this).siblings('#delete').hide();
$(this).siblings('#update,#cancel').show();
$(this).hide();
$('#feed_label').removeClass('feed_label').addClass('feed_url');
});
$('body').delegate('#cancel','click',function(){
//alert();
$(this).siblings('#edit,#delete').show();
$(this).siblings('#update').hide();
$(this).hide();
$("#update_url")[0].reset();
});
//ENDS
//Edit Code
$('body').delegate('.edit','click',function(){
var IdEdit = $(this).attr('ide');
//alert(IdEdit);
//return false;
$.ajax({
url:"pages/feeds.php",
type:"post",
datatype:"json",
data:{
editvalue:1,
id:IdEdit
},
success:function(show)
{
//alert('success');
$('#id').val(show.id);
$('#url1').val(show.url);
//$('#add_feed_form')[0].reset();
//$('#showdata').load('pages/feeds.php');
}
});
});
//Ends
//Update Starts
$('.update').click(function(){
//alert('update');
var id = $('#id').val()-0;
var urls = $('#url1').val();
$.ajax({
//alert();
url:"pages/feeds.php",
type:"post",
async:false,
data:{
update:1,
id:id,
upurls:urls
},
success:function(up)
{
//alert('updated');
$('input[type=text]').val('');
showdata();
$('#add_feed_form')[0].reset();
$('#showdata').load('pages/feeds.php');
}
});
});
//UPdate Ends
PHP Code
//Edit Starts
if(isset($_POST['editvalue']))
{
$sql = "select * from deccan where id='{$_POST['id']}'";
$row = mysql_query($sql);
$rows = mysql_fetch_object($row);
header("Content-type:text/x-json");
echo json_encode($rows);
exit();
}
//Ends
//UPdate Starts
if(isset($_POST['update']))
{
$sql = "
update deccan
set
url='{$_POST['upurls']}'
where id='{$_POST['id']}'
";
$result = mysql_query($sql);
if($result)
{
//alert('success');
echo 'updated successfully';
}
else
{
//alert('failed');
echo 'failed to update';
}
}
//Ends
Any help Is appreciated Thanks!!
Here i give sample for your case :
HTML
<div class="container">
<label>John</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
<hr/>
<div class="container">
<label>John Who</label>
<input type="button" class="edit" value="Edit"/>
<input type="button" class="delete" value="delete"/>
</div>
JS (you can simplified below code into one handler)
$(document).on('click', '.edit', function(e){
var data = $(this).prev();
if ( data.is('label') ) data.replaceWith('<input value="'+data.text()+'">');
});
$(document).on('click', '.delete', function(e){
var data = $(this).prev().prev();
if ( data.is('input') ) data.replaceWith('<label>'+data.val()+'</label>');
});
DEMO