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";
}
Related
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>
I have this Ajax function:
$(document).ready(function() {
$('.view_data2').click(function() {
var employee_id2 = $(this).attr("id");
$.ajax({
url: "includes/accomUser.inc.php",
method: "post",
data: {
employee_id2: employee_id2,
button_value: $(this).val()
},
success: function(data) {
$('#employee_detail2').html(data);
$('#adddata2').modal("show");
}
});
$('#addmodal2').modal("show");
});
});
It takes this button properties(value and id) and sends them to the modal via post:
<button type="button" class="btn btn-outline-primary view_data2" id=" <?php echo $row['idFuncionarios']; ?>" value = "<?php echo $row['dia']; ?>" name = "envio">Ver</button>
Now, I need to take a data that has nothing to do with the button ($row['nomeDepartamento'];):
<td><?php echo $row['nomeDepartamento']; ?></td>
and send it via the same ajax function to the modal.
How would I do this?
Thank you!
This is how your button will look like
<button data-field-name="<?php echo $row['nomeDepartamento']; ?>" type="button" class="btn btn-outline-primary view_data2" id="<?php echo $row['idFuncionarios']; ?>" value="<?php echo $row['dia']; ?>" name="envio">Ver</button>
and retrive the $row['nomeDepartamento']; & after click funciton declare variable
var nomeDepartamento = $(this).attr("data-field-name");
and send this in data:{} and after success change html of any element like $("element").html(nomeDepartamento)
and there you go.
I have a form and it have 2 submit button.
<form name="posting" id="posting" method="post" action="posting_bk.php" role="form">
<input type="text" name="title" id="title" class="form-control" required="required">
....some form fields...
<input class="btn btn-home" type="submit" name="publish" id="publish" alt="Publish" value="Preview and Post" />
<input class="btn btn-home" type="submit" name="save" id="save" onclick="return confirm('Are you sure you want to Submit.')" alt="Save" value="Save as Draft" /></center>
</form>
i am using ajax to send/receive data.
$('#posting input[type="submit"]').on("click", function(e) {
e.preventDefault;
var btn = $('#publish');
var el = $(this).attr('id');
$.ajax({
type: 'post',
url: $('form#posting').attr('action'),
cache: false,
dataType: 'json',
data: {
data: $('form#posting').serialize(),
action: el
},
beforeSend: function() {
$("#validation-errors").hide().empty();
},
success: function(data) {
if (data.success == false) {
var arr = data.errors;
$.each(arr, function(index, value) {
if (value.length != 0) {
$("#validation-errors").append('<div class="alert alert-danger"><strong>' + value + '</strong><div>');
}
});
$("#validation-errors").show();
btn.button('reset');
} else {
$("#success").html('<div class="alert alert-success">Basic details saved successfully. <br> If you want to edit then please goto Edit. <div>');
$('#title').val('');
}
},
error: function(xhr, textStatus, thrownError) {
alert('Something went to wrong.Please Try again later...');
btn.button('reset');
}
});
return false;
});
this is my php file. posting_bk.php
if ($_POST['action'] == 'publish') {
if($title == 'test'){
array_push($res['errors'], 'data received by php.');
}else{
array_push($res['errors'], 'No data received by php.');
}
$res['success'] = true;
echo json_encode($res);
}
elseif ($_POST['action'] == 'save') {
array_push($res['errors'], 'Save button clicked.');
$res['success'] = true;
echo json_encode($res);
}
All the time if i click on publish button i am getting
No data recived by php
When I check in firebug it is showing data under post.
Like this
action publish
data title=test&
I am not sure what am i doing wrong here. Please advise.
Change the AJAX call to use:
data: $('form#posting').serialize() + '&action=' + el,\
Then access the parameter using
$title = $_POST['title'];
The way you're doing it, the form data is being nested a level down in the POST data, so you would have had to do:
$data = parse_str($_POST['data']);
$title = $data['title'];
I have a form that can delete records from a MySql database using ajax and jQuery. I'm trying to get the jQuery to only select the relevant record passed to it and not just delete the top row of records which it does at the moment. I think I need to get
<div class="'.$id.'">
from my form and make it a data attribute that can be selected. Hope I'm making myself clear. Many thanks.
<script type="text/javascript">
//Delete Review
$(document).ready(function(){
//Need to get $id here.
$(".deleteReview").click(function (e) {
e.preventDefault();
var username = $("#username").val();
var film_id = $("#film_id").val();
var id = $("#id").val();
$.post('ajax_deleteReview.php', {
username: username,
film_id: film_id,
id: id
}, function(data) {
$("#message").html(data);
$("#message").hide();
$("#message").fadeIn(500);
$("#message").fadeOut(2500);
});
return false;
});
});
</script>
<form>
<div class="'.$id.'">
<input type="hidden" id="username" name="username" value="'. $username.'">
<input type="hidden" id="film_id" name="film_id" value="'.$film_id .'">
<input type="hidden" id="id" name="id" value="'.$id .'">
<button type="submit" id="" class="btn btn-danger btn-xs pull-right">delete</button>
</form>
</div>
I would recommend you to use data-* prefixed attributes to persists your data.
HTML
<div data-id="'.$id.'" data-username="'. $username.'" data-filmid="'.$film_id .'" class="deleteReview">
<button type="submit" id="" class="btn btn-danger btn-xs pull-right">delete</button>
<div >
Then you can fetch it using .data(key)
Return the value at the named data store for the first element in the jQuery collection, as set by data(name, value) or by an HTML5 data-* attribute
Script
//Delete Review
$(document).ready(function(){
//Need to get $id here.
$(".deleteReview").click(function (e) {
e.preventDefault();
var username = $(this).data("username");
var film_id = $(this).data('filmid');
var id = $(this).data('id');
......
return false;
});
});
First in your PHP do something like this, you add the data attributes to your delete button since you are not actually submitting a real form. I also moved the deleteReview class to the button.
print '<button type="submit" class="deleteReview" data-id="'.$id.'" data-film-id="'.$film_id.'" data-username="'.htmlentities($username).'" class="btn btn-danger btn-xs pull-right">delete</button>';
Then, in your jQuery, update click event callback like so:
$(".deleteReview").click(function (e) {
e.preventDefault();
var username=$(this).data('username');
var film_id=$(this).data("film-id");
var id=$(this).data('id');
/* the rest of your code */
The data attributes become accessible easily with jQuery using $(this).data('some-attribute-name')
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