Passing two variables via AJAX/PHP? - php

EDITED with UPDATED CODE: Im missing something here; the jQuery is working, but the variables arent passing to the query. Below is all of the updated code:
<span class="accepted"><input type="button" title="accept" value="Accept" /></span>
AJAX Script
<script type="text/javascript">
$(function() {
$(".accept").click(function(){
var element = $(this);
var del_id = element.attr("id");
var order_id = element.attr("data-order");
//if(confirm("Are you sure you want to delete this?"))
//{
$.ajax({
type: "POST",
url: "accept.php",
//data: info,
data: {id:del_id,order_id:order_id},
success: function(){}
//
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
//}
//return false;
});
});
</script>
new php file
include('db.php');
$id = $_POST['id'] ;
$name = $_POST['order_id'] ;
$sql = "UPDATE mgap_orders SET mgap_status = 1 WHERE mgap_ska_id = :id AND mgap_ska_report_category = :name";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':id' => '$id',
':name' => '$name'
));

Instead of using var info = 'id=' + del_id; and data: info, You should send variables like below:
data: {id:del_id}
Future more, if you want to pass more variables you can go like below:
data: {id:del_id,order:ORDER_ID}
Hope this helps.

do like this
$.ajax({
type: "POST",
url: "delete.php",
data: {id:del_id,order:order_variable},
success: function(){
}

Specify your Data as an object. Should be separated by comma for each variable.
data: {variablename1: value1, variablename2: value2}
So you code should look like:
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
//var info = 'id=' + del_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: { id: del_id, var2: var2, var3: var3 },
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>

<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("data-id");
var order_id = element.attr("data-order");
var info = 'id=' + del_id;
var order = 'order' + order_id;
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "mod_accept.php", //Changed the processor file
data: {info, order},
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>
Then in your html:
<span class="accepted"><input type="button" title="accept" value="Accept" /></span>

do something like
<span class="accepted">
<a href="#" class="delete" id="<?php echo $id1; ?>"
data-order="<?php echo $order_id;?>">
<input type="button" title="accept" value="Accept" /></a>
</span>
<script type="text/javascript">
$(function() {
$(".delete").click(function(){
var element = $(this);
var del_id = element.attr("id");
var order_id = element.attr("data-order");
if(confirm("Are you sure you want to delete this?"))
{
$.ajax({
type: "POST",
url: "delete.php",
data: {id:del_id,order_id:order_id},
success: function(){
}
});
$(this).parents(".show").animate({ backgroundColor: "#003" }, "slow")
.animate({ opacity: "hide" }, "slow");
}
return false;
});
});
</script>

Related

I can not click again remove or add button

I want to create an Add and Remove from ordered lists button for my site.
But I can not click again when I click add button or remove button.
<script>
$(document).ready(function () {
$('.order-lists div #add').click(function(e) {
$('.order-lists div').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.cookie(ids, name);
$.cookie(name, mov_size);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).append('<a class="btn btn-danger" id="remove" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Remove </a>');
});
}
e.preventDefault();
});
$('.order-lists div #remove').click(function(e) {
$('.order-lists div').removeClass('remove');
var $parent = $(this).parent();
if (!$parent.hasClass('remove')) {
$parent.addClass('remove');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.removeCookie(ids, null);
$.removeCookie(name, null);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).removeClass('remove');
$("#" + ids).append('<a class="btn btn-danger" id="add" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Add Order List </a>');
});
}
e.preventDefault();
});
});
</script>
use on function for dynamically added elements.
$(document).ready(function () {
$('.order-lists').on('click', '#add' , function(e) {
$('.order-lists div').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.cookie(ids, name);
$.cookie(name, mov_size);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).append('<a class="btn btn-danger" id="remove" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Remove </a>');
});
}
e.preventDefault();
});
});
same for remove.

Submit autocomplete with enter button without refreshing the page

I am trying to get the query results by hitting the enter button on the drop down of the autocomplete results. It works fine if I use the mouse to click the result i want but wont work if i use the enter key.
The first function gets the autocomplete results and the second submits the result to get the data from that particular id.
JQUERY
$(document).ready(function () {
$("#equipment").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
$('#eq_id').val(ui.item.id);
}
});
$(document).off("keypress", "#equipment");
$(document).on("keypress", "#equipment", function(event) {
//if (!e) e = window.event;
if (event.keyCode == '13'){
$('#loading').show();
var eq_id = $("#eq_id").val();
var dataString = 'eq_id=' + eq_id;
$.ajax({
type: "POST",
url: "updateForm.php",
data: dataString,
success: function(html){
$("#formAddEquip").hide();
$("#showuserresult").show();
$("#showuserresult").html(html);
$("#equipment").val("");
$('#loading').hide();
}
});
return false;
}
});
});
And here is the form
<form action="" method="post" id="#somesearch">
<label for="equipment" id="eq_id_label">Search Equipment</label>
<input type="text" id="equipment" name="equipment" />
<input type="hidden" id="eq_id" name="eq_id" />
</form>
Start with these improvements
$(function() { // only one "load"
$("#equipment").autocomplete({
source: "search.php",
minLength: 2,
select: function(event, ui) {
$('#eq_id').val(ui.item.id);
}
});
$("#somesearch ").on("submit", function(e) {
e.preventDefault(); // stop submission
});
$(document).on("keypress", "#equipment", function(event) {
//if (!e) e = window.event;
if (event.keyCode == '13') {
$('#loading').show();
var eq_id = $("#eq_id").val();
var dataString = 'eq_id=' + eq_id;
$.ajax({
type: "POST",
url: "updateForm.php",
data: dataString,
success: function(html) {
$("#formAddEquip").hide();
$("#showuserresult").show();
$("#showuserresult").html(html);
$("#equipment").val("");
$('#loading').hide();
}
});
}
});
});

insert values of clicked buttons into array

I am trying to get the values of the first 9 clicked buttons and put them into an array named $u_input. I actually found this, but its in javascript.
my html:
<div>
<button name="btn1" type="submit" id="btn1" value="1" style="width:50%;height:40%;margin-left: auto;margin-right: auto; float:left" class="ui-btn"></button>
<button name="btn2" type="submit" id="btn2" value="2" style="width:50%;height:40%;margin-left: auto;margin-right: auto;float:right" class="ui-btn"></button>
</div> // I have up to 9 buttons, thats only a piece
my javascript:
$(document).ready(function(){
$('.ui-btn').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'escreen.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
});
});
});
my php:
if (isset($_POST['action'])) {
$u_input = array($_POST['action'](1), $_POST['action'](2), $_POST['action'](3), $_POST['action'](4));
echo $u_input;
}
Just loop through the buttons with the following code:
jQuery(document).ready(function($){
var ajaxurl = 'escreen.php',
$values = [];
$('button').each(function(){
$values.push($(this).val());
});
$.ajax({
url: ajaxurl,
type: 'post',
data: {
buttons: $values,
},
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
});
An even nicer way to do it would be to set a name for each property in your array:
jQuery(document).ready(function($){
var ajaxurl = 'escreen.php',
$values = [];
$('button').each(function(){
$values[$(this).attr('name')] = $(this).val();
});
$.ajax({
url: ajaxurl,
type: 'post',
data: {
buttons: $values,
},
success: function (result) {
console.log('Yay it worked');
},
error: function (xhr, ajaxOptions, thrownError) {
console.log('Something went wrong');
}
});
});
The array $values should contain the following:
[button1: "value1", button2: "value2", button3: "value3"]
So in your PHP file you can retreive it by using:
$_POST['buttons']['button1']

Removing appended div box using jquery ajax

I have to implement two functions, append and delete on set of comments. The insertion and deletion are working properly unless in one case.
When i try to remove newly added comment (before refreshing page), it wont remove. But when i refresh the page that comment removes swiftly.
Here's some code.
Following ajax is appending and removing the comment div.
<script type="text/javascript">
$(function() {
$(".commentbutton").click(function()
{
var element = $(this);
var postid = element.attr("id");
var commenttext = $("#commenttext"+postid).val();
var dataString = 'commenttext='+ commenttext+'&postid='+postid;
var postseq='#post'+postid;
if(commenttext=='')
{
alert("Please enter your comment");
}
else
{
//$("#flash").show();
//$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
$(postseq).append(html);
$(postseq).slideDown();
document.getElementById('commenttext'+postid).value='';
}
});
}
return false;
});
$('.delcombutton').click(function()
{
var commid = $(this).attr("id");
var dataString = 'delcomm=1&commid='+commid;
var delcomment = '#comment'+commid;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
cache: false,
success: function(html){
$(delcomment).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});
</script>
Structure of my div
echo "<div id='post{$postseq}'>";
while($commentonpost=mysql_fetch_array($resultcomm)){
if($commentonpost['visible']==1){
echo '
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;" id="comment'.$commentonpost['commentid'].'">
<div style="width:10%;float:left;"><a href="profile.php?user='.$commentonpost['usernick'].'" >'.$commentonpost['fname']." ".$commentonpost['lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;">'.$commentonpost['comment'].'</div>
<div style="width:8%;float:right;margin-left:2%;">
';
if($commentonpost['usernick']==$_SESSION['user_nick']){
echo ' <form action="" method="post">
<input type="submit" name="delcomm" value="X" class="delcombutton" id="'.$commentonpost['commentid'].'">
</form>
';
}
echo '<h5 class="msg">'.datetime($commentonpost['date']).'</h5>
</div>
<br/>
</div>
';
}
}
echo "</div>";
echo '
<form name = "form'.$postseq.'" method = "post" action="" onsubmit="return validateform()" style="width:100%">
<div style="width:90%;float:left;margin-left:5%;margin-right:15%;margin-top:10px;">
<div style="width:10%;float:left;"><a href="profile.php?user='.$_SESSION['user_nick'].'" >'.$_SESSION['user_fname']." ".$_SESSION['user_lname'].'</a></div>
<div style="width:78%;float:left;margin-left:2%;"><textarea placeholder="Comment..." name="commenttext" id="commenttext'.$postseq.'" class="inputcomment" ></textarea></div>
<br>
<input type="submit" id="'.$postseq.'" name="SubmitComment" value="Comment " class="commentbutton" style="font-size:1em;width:100px;float:right;margin-top:4px;margin-right:9%;">
</div>
</form>
</div>
';
PS: Sorry for such a raw code, i have very limited internet now.
You have to use delegation for dynamically added elements:
$(document).on('click','.delcombutton',function(){...});
Use event delegation model with .on() for dynamically added elements
$(function() {
$(document).on('click', '.commentbutton', function() {
var element = $(this);
var postid = element.attr("id");
var commenttext = $("#commenttext"+postid).val();
var dataString = 'commenttext='+ commenttext+'&postid='+postid;
var postseq='#post'+postid;
if(commenttext=='') {
alert("Please enter your comment");
}
else {
//$("#flash").show();
//$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
dataType:'html',
cache: false,
success: function(html){
$(postseq).append(html);
$(postseq).slideDown();
document.getElementById('commenttext'+postid).value='';
}
});
}
return false;
});
$(document).on('click', '.delcombutton', function() {
var commid = $(this).attr("id");
var dataString = 'delcomm=1&commid='+commid;
var delcomment = '#comment'+commid;
if(confirm("Sure you want to delete this update? There is NO undo!"))
{
$.ajax({
type: "POST",
url: "insdelcomment.php",
data: dataString,
cache: false,
success: function(html){
$(delcomment).slideUp('slow', function() {$(this).remove();});
}
});
}
return false;
});
});

json jquery post request

<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var content = $('#content').html();
var data = {"content":content};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: {content:content},
success function (data) {
alert('Hello!');
}
});
});
});
</script>
<div id="content"><?php echo $content; ?></div>
ajax.php
echo json_encode($_POST['content']); ?>
Nothing happens... WhatI really want to achieve is to get that alert box and get the return data, but I am lost since I don't get any errors or nothing.
You miss " : " after success
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function() {
var content = $('#content').html();
var data = {"content":content};
$.ajax({
type: "POST",
dataType: "json",
url: "ajax.php",
data: {content:content},
success: function (data) {
alert('Hello!');
}
});
});
});
</script>
<div id="content"><?php echo $content; ?></div>
As #sofl said, if you change it to success:function (data) { it will work!
Just remember that the $("a") from $("a").click(function() { called when click in a link tag like <a href"">.
If you are using an input ou button with a class="a" you should change the code to $(".a").click(function() {
(just add a . before a)
PS: If you're using a link, you should set the href="" to href="#" to work.

Categories