Ajax Submit using PHP and mysql - php

There are may button son php page. I want to submit value of button and the delete record from table using that value. Ajaxz code is
$('#product-table td #delete').live("click", function () {
var doDelete = confirm('Are you sure you want to delete this record?');
deleteLinkObj = $(this);
if (doDelete) {
var id = $(this).attr('accesskey');
$("#deleteid").val(id);
$.ajax({
url: "purchase.php",
data: {deleteid:id},
dataType: 'html',
success: function() {
}
});
}
else { return false; }
});
On PHP I am trying to use value of deleteid but its not coming
PHP code is
if(#$_POST['deleteid']!="")
{
$sql="delete from purchasedetails where purchaseid='".$_POST['deleteid']."'";
if(!mysql_query($sql))
{
die('Error: ' . mysql_error());
}
else
{
$msg="Data is deleted";
}
}
I have tried usinng isset($_POST['deleteid']) then also its showing error

In your ajax call you aren't setting the request method to POST, therefore it will default to GET, that is why your post var is never present:
$.ajax({
type: 'POST',
url: "purchase.php",
data: {deleteid:id},
dataType: 'html',
success: function() {
}
});
As a quick fix for your SQL Injection vulnerability you can cast the id as int, but you should consider upgrading to PDO or MySQLi because the library you're using is deprecated.
$sql="delete from purchasedetails where purchaseid='".(int)$_POST['deleteid']."'";
Storing your purchaseid as the elements accesskey is not the best place, it would be better as a data-myid attribute, so you can access it with $(this).data('myid').

By default $.ajax take type as GET, hence you need to define the type in you code
You can try like this $.ajax syntax-
$.ajax({
url: "purchase.php",
data: $("#deleteid").val(id),
type: POST
dataType: 'html',
success: function() {

Related

concat the two id came from database in ajax and codeigniter

i am having trouble in concating the value of my two ID's from database to generate a new ID and use it to save again in Database. I am using codeigniter and i want something a good technique/way to concat for better result or maybe faster.
Also i am having a problem, whenever there is a value in my database, i cannot increment my ID by having +1. I got an output of 1-undefine-1
Here is my ajax:
function getcheckupID() {
var init = 0;
var value = $('#clinicID').html();
$.ajax ({
url: siteurl+"myclinic/getcheckID",
type: "GET",
dataType: "JSON",
success: function(data) {
if(data.length>0) {
$('#checkID').text(value+"-"+data[0]['clinic_id']+1);
$("#checkID").css('visibility','visible');
}
else {
$('#checkID').text(value+"-"+init);
$("#checkID").css('visibility','visible');
}
}
})
}
function get_clinicID() {
$("#clinicID").empty();
$.ajax({
url: siteurl+"myclinic/get_clinicID",
type: "GET",
dataType: "JSON",
success: function(data) {
$('#clinicID').text(data[0]['clinic_id']);
}
});
}
i check the records in my DB using this if(data.length>0) then if i got record, i go get the data and +1 it. I got a value of undefined, but if it goes to else, it outputs bad, because whenever i refresh it. sometimes it only outputs - 0, where i want is 1-0. Then refresh it again. How can i concat safely ? Is it an issue in ajax ?. making slow ?
Here is my controller for it :
public function getcheckID() {
$checkID = $this->clinic_model->checkupID();
echo json_encode($checkID);
}
My Model :
public function checkupID() {
$query = $this->db->query('SELECT tbl_check_up.check_up_id FROM tbl_check_up');
return $query->result();
}

jquery ajax: how to keep record not dissapear when the page is refresh

i use this script
<script type="text/javascript">
$(function () {
$(".comment_button").click(function () {
var element = $(this);
var boxval = $("#content").val();
var dataString = 'content=' + boxval;
if (boxval == '') {
alert("Please Enter Some Text");
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="ajax.gif" align="absmiddle"> <span class="loading">Loading Update...</span>');
$.ajax({
type: "POST",
url: "update_data.php",
data: dataString,
cache: false,
success: function (html) {
$("ol#update").prepend(html);
$("ol#update li:first").slideDown("slow");
document.getElementById('content').value = '';
$("#flash").hide();
}
});
}
return false;
});
$('.delete_update').live("click", function () {
var ID = $(this).attr("id");
var dataString = 'msg_id=' + ID;
if (confirm("Sure you want to delete this update? There is NO undo!")) {
$.ajax({
type: "POST",
url: "delete_data.php",
data: dataString,
cache: false,
success: function (html) {
$(".bar" + ID).slideUp('slow', function () {
$(this).remove();
});
}
});
}
return false;
});
});
</script>
this script combine live update and delete record using jquery and ajax
the problem is when I refresh the page, the record will disappear .. how to keep records that show up are not dissapear when the page is reloaded?
First Check the comment list. Did you put any limit in query, if so then use Order by Primary ID desc.So it would display latest records first.
When you delete any record, check whether it is actually deleted from database or not. Because you are not checking whether record actually deleted or not as per the code you given.
Assuming you are using update_data.php and delete_data.php to manipulate some database, you could use PHP to render the page initially using the data that is currently on the database.
If that is not the case, and you don't have access to that database (it could be a third party web service, right?), or you don't want to do that for any reason, you could use cookie like Saeed answered.

ajax like/unlike button not switching back

I am trying to make a like button on a page and cant seem to get it to work right. Basically there are three function that use ajax to send the data to a php page that updates the database. Ive checked the db and all three update correctly. If the user doesnt originally like and clicks, it correctly shows the unlike button but then, if you click unlike it doesnt switch back (although it does update the database).
Is this the correct way to set this up? Im pretty new to ajax and am not sure if this is the right approach. THanks in advance
Steve
public function likesScript($p){?>
<script>
//display list of people who like this
function getLikes(){
$.ajax({
type: "POST",
url: "likelist.php",
data: { p: "<?php echo $_GET['p']?>"}
}).success(function(res) {
//check to see if current user likes this
if($('li#<?PHP echo $_SESSION['userId']; ?>').length){
$(".Like").addClass('hidden');
$(".UnLike").removeClass('hidden');
}
else{
$(".UnLike").addClass('hidden');
$(".Like").removeClass('hidden');
}
$("#likedBy").append(res);
console.log(res);
});
}
function removeLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "0" }
})
getLikes();
return false;
}
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" }
})
getLikes();
return false;
}
$(document).ready(function() { getLikes();
$(".UnLike").live('click',removeLike);
$(".Like").live('click',addLike);
});
</script>
likelist.php:
<?php
require $_SERVER['DOCUMENT_ROOT'].'/view.class.php';
$view = new view();
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$p = $_POST['p'];
$view->printLikes($profile->getLikes($p));
}
likedata.php:
<?php
include $_SERVER['DOCUMENT_ROOT'].'/profile.class.php';
include $_SERVER['DOCUMENT_ROOT'].'/init.php';
$profile = new profile($dbh);
if(isset($_POST)){
$liker = $_POST['arg1'];
$likee = $_POST['arg2'];
$likeYesNo = $_POST['arg3'];
$profile->insertLikes($liker, $likee, $likeYesNo);
}
?>
AJAX is ayshcronous so the getLikes functions will fire before the AJAX is completed in both addLike and removeLike. You definitely need to put getLikes into the success callback of $.ajax so it doesn't retrieve data that may not have been updated
function addLike() {
$.ajax({
type: "POST",
url: "likedata.php",
data: { arg1: "<?php echo $_SESSION['userId']?>", arg2: "<?php echo $p;?>", arg3: "1" },
success: getLikes
})
}
Ok... this is what I have learned from using ajax repeat calls...
IE hates them and sometimes they just don't work the way they should.
Try this
function addLike() {
var randnum = Math.floor(Math.random()*1001); //Add This Here on all Ajax Calls
$.ajax({
type: "POST",
url: "likedata.php",
cache: false, //Add This Here - Assists in helping Browsers not to cache the Ajax call
data: yourdata + '&random=' + randnum, // Add this to the end of your data you are passing along *'&random=' + randnum,*
success: function() {
getLikes();
}
})
}
Adding a random piece of data causes the browsers to think its a new call.
Also, the random=randnum wont effect anything on the php side.

Sending a global variable

I have a piece of Javascript that forwards a users' selected information to an external PHP file, and returns information. In the code below, you can see it sends {'report' : report} via POST to that file. That works fine.
Essentially I need to add another variable to be sent. It's called 'id', but it's in another function. Is there a way to make that variable global and then incorporate it so it's sent in my code snippet? (and when will the global variable be cleared?)I can also send it via the 'url' attribute, and use GET in my PHP...just not sure how to implement.
$('#adminSelectReport a').live("click", function () {
//Get id from clicked link:
var report = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': report
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
UPDATE: Here is the other snippet that sends 'id' to another page, getting information. I need to retain this ID, however, and use it on my original code.
$('#adminSelectCompany a').click(function() {
//Get id from clicked link:
var id = $(this).attr('id');
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg);
$('#adminSelectReport').fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
So it sounds like they select a Company via a link, then they select a Report via another link, and you need to remember which Company was selected.
In order to avoid global variables, I'd probably just add a class to the selected Company link, and then fetch that element by the selected class, and grab its ID. You could use the class for styling as well if that's needed.
var companies = $('#adminSelectCompany a');
companies.click(function () {
// remove class from previously selected, and add to new one
companies.filter('.selected').removeClass('selected');
$(this).addClass('selected');
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {
'id': this.id
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg)
.fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
$('#adminSelectReport a').live("click", function () {
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': this.id,
'company': $('.selected')[0].id
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
You can achieve this by assigning the value as a property of JavaScripts "global" namespace called window. Simply assign the id you want to make global to window.my_id, then refer to it in the click callback.
Note: If you're setting the global variable in another function, remember to check for its existance in the function that will use the variable, ie: var my_id = null; if (window.my_id != undefined) { my_id = window.my_id; }
Here's an implementation:
$('#adminSelectReport a').live("click", function () {
//Get id from clicked link:
var report = $(this).attr('id');
var company = window.report_company_id != undefined ? window.report_company_id : null;
$.ajax({
type: 'POST',
url: 'getReportInfo.php',
data: {
'report': report,
'company': company
},
success: function (msg) {
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminReportInfo').html(msg);
$('#adminReportInfo').fadeIn(400);
}
});
});
.
$('#adminSelectCompany a').click(function() {
//Get id from clicked link:
var id = $(this).attr('id');
window.report_company_id = id;
$.ajax({
type: 'POST',
url: 'getReports.php',
data: {'id': id},
success: function(msg){
//everything echoed in your PHP-File will be in the 'msg' variable:
$('#adminSelectReport').html(msg);
$('#adminSelectReport').fadeIn(400);
$('#adminReportInfo').fadeOut(300);
}
});
});
Lastly I would advise against global variables if possible, or at least minimize the usage by wrapping common function/purposes in objects and prefixing the names with the project name or something.
Change
data: { 'report': report },
To
data{ 'report': report, 'id': YOUR ID },
Why don't you send the second variable like that:
data: {'report': report, 'id': your_id },
edit: arf too slow!

Zend and Jquery (Ajax Post)

I'm using zend framework, i would like to get POST data using Jquery ajax post on a to save without refreshing the page.
//submit.js
$(function() {
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
url: 'http://localhost/myproject/public/module/save',
async: false,
data: 'id=' + id + '&details=' + details,
success: function(responseText) {
//alert(responseText)
console.log(responseText);
}
});
});
});
On my controller, I just don't know how to retrieve the POST data from ajax.
public function saveAction()
{
$data = $this->_request->getPost();
echo $id = $data['id'];
echo $details = $data['details'];
//this wont work;
}
Thanks in advance.
Set $.ajax's dataType option to 'json', and modify the success callback to read from the received JSON:
$('#buttonSaveDetails').click(function (){
var details = $('textarea#details').val();
var id = $('#task_id').val();
$.ajax({
type: 'POST',
dataType: 'json',
url: 'http://localhost/myproject/public/module/save',
async: false,
// you can use an object here
data: { id: id, details: details },
success: function(json) {
console.log(json.id + ' ' + json.details);
}
});
// you might need to do this, to prevent anchors from following
// or form controls from submitting
return false;
});
And from your controller, send the data like this:
$data = $this->_request->getPost();
echo Zend_Json::encode(array('id' => $data['id'], 'details' => $data['details']));
As a closing point, make sure that automatic view rendering has been disabled, so the only output going back to the client is the JSON object.
Simplest way for getting this is:
$details=$this->getRequest()->getPost('details');
$id= $this->getRequest()->getPost('id');
Hope this will work for you.

Categories