i want to delete a row of data in my sql when delete button is pressed in xdk. i searched for some codes but still doesnt delete the data.
this is the php file (delete.php)
<?php
include('dbcon.php');
$foodid = $_POST['foodid'];
$query = "DELETE FROM menu WHERE id ='$foodid'";
$result=mysql_query($query);
if(isset($result)) {
echo "YES";
} else {
echo "NO";
}
?>
and now here is my ajax code.
$("#btn_delete").click( function(){
alert("1");
var del_id = $(this).attr('foodid');
var $ele = $(this).parent().parent();
alert("2");
$.ajax({
type: 'POST',
url: 'http://localhost/PHP/delete.php',
data: { 'del_id':del_id },
dataType: 'json',
succes: function(data){
alert("3");
if(data=="YES"){
$ele.fadeOut().remove();
} else {
alert("Cant delete row");
}
}
});
});
as you can see, i placed alerts to know if my code is processing, when i run the program in xdk. it only alerts up to alert("2"); . and not continuing to 3. so i assume that my ajax is the wrong part here. Im kind of new with ajax.
<?php
$sqli= "*select * from temp_salesorder *";
$executequery= mysqli_query($db,$sqli);
while($row = mysqli_fetch_array($executequery,MYSQLI_ASSOC))
{
?>
//"class= delbutton" is use to delete data through ajax
<button> Cancel</button>
<!-- language: lang-js -->
//Ajax Code
<script type="text/javascript">
$(function() {
$(".delbutton").click(function(){
//Save the link in a variable called element
var element = $(this);
//Find the id of the link that was clicked
var del_id = element.attr("id");
//Built a url to send
var info = 'id=' + del_id;
$.ajax({
type: "GET",
url: "deletesales.php",
data: info,
success: function(){
}
});
$(this).parents(".record").animate({ backgroundColor: "#fbc7c7" }, "fast")
.animate({ opacity: "hide" }, "slow");
return false;
});
});
</script>
//deletesales.php
<?php
$db_host = 'localhost';
$db_user = 'root';
$db_pass = '';
$db_database = 'pos';
$db = mysqli_connect($db_host,$db_user,$db_pass,$db_database);
$id=$_GET['id']; <!-- This id is get from delete button -->
$result = "DELETE FROM temp_salesorder WHERE transaction_id= '$id'";
mysqli_query($db,$result);
?>
<!-- end snippet -->
A couple of things:
You should be testing using console.log() instead of alert() (imo)
If you open up your console (F12 in Google Chrome) do you seen any console errors when your code runs?
Your code is susceptible to SQL Injection, you will likely want to look into PHP's PDO to interact with your database.
Does your PHP file execute correctly if you change:
$foodid = $_POST['foodid'];
To
$foodid = 1
If number 4 works, the problem is with your javascript. Use recommendations in numbers 1 and 2 to diagnose the problem further.
Update:
To expand. There are a few reasons your third alert() would not fire. The most likely is that the AJAX call is not successful (the success handler is only called if the AJAX call is successful). To see a response in the event of an error or failure, you can do the following:
$.ajax({
url: "http://localhost/PHP/delete.php",
method: "POST",
data: { del_id : del_id },
dataType: "json"
})
.done(function( msg ) {
console.log(msg);
})
.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
More information on AJAX and jQuery's $.ajax can be found here
My "best guess" is a badly formatted AJAX request, your request is never reaching the server, or the server responds with an error.
Related
I have a button which calls a modal box to fade into the screen saying a value posted from the button then fade off, this works fine using jquery, but I also want on the same click for value sent from the button to be posted to a php function, that to run and the modal box to still fade in and out.
I only have this to let my site know what js to use:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js" ></script>
I'm still new so sorry for a rookie question, but will that allow ajax to run, or is it only for jquery?
The current script I'm trying is: (Edited to be correctly formed, based on replies, but now nothing happens at all)
<script>
$('button').click(function()
{
var book_id = $(this).parent().data('id'),
result = "Book #" + book_id + " has been reserved.";
$.ajax
({
url: 'reservebook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
Though with this the modal box doesn't even happen.
The php is, resersebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['jqbookID']))
{
$bookID = $_POST['jqbookID'];
mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
}
?>
and to be thorough, the button is:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>"><button>Reserve Book</button></div>
I'm new to this and I've looked at dozens of other similar questions on here, which is how I got my current script, but it just doesn't work.
Not sure if it matters, but the script with just the modal box that works has to be at the bottom of the html body to work, not sure if for some reason ajax needs to be at the top, but then the modal box wouldn't work, just a thought.
Try this. Edited to the final answer.
button:
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button class="reserve-button">Reserve Book</button>
</div>
script:
<script>
$('.reserve-button').click(function(){
var book_id = $(this).parent().data('id');
$.ajax
({
url: 'reservebook.php',
data: {"bookID": book_id},
type: 'post',
success: function(result)
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
</script>
reservebook.php:
<?php
session_start();
$conn = mysql_connect('localhost', 'root', '');
mysql_select_db('library', $conn);
if(isset($_POST['bookID']))
{
$bookID = $_POST['bookID'];
$result = mysql_query("INSERT INTO borrowing (UserID, BookID, Returned) VALUES ('".$_SESSION['userID']."', '".$bookID."', '3')", $conn);
if ($result)
echo "Book #" + $bookId + " has been reserved.";
else
echo "An error message!";
}
?>
PS#1: The change to mysqli is minimal to your code, but strongly recommended.
PS#2: The success on Ajax call doesn't mean the query was successful. Only means that the Ajax transaction went correctly and got a satisfatory response. That means, it sent to the url the correct data, but not always the url did the correct thing.
You have an error in your ajax definitions. It should be:
$.ajax
({
url: 'reserbook.php',
data: "book_id="+book_id,
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
You Ajax is bad formed, you need the sucsses event. With that when you invoke the ajax and it's success it will show the response.
$.ajax
({
url: 'reserbook.php',
data: {"book_id":book_id},
type: 'post',
success: function(data) {
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
}
Edit:
Another important point is data: "book_id="+book_id, that should be data: {"book_id":book_id},
$.ajax
({
url: 'reservebook.php',
data: {
jqbookID : book_id,
},
type: 'post',
success: function()
{
$('.modal-box').text(result).fadeIn(700, function()
{
setTimeout(function()
{
$('.modal-box').fadeOut();
}, 2000);
});
}
});
});
Try this
I am trying to pass a variable from my ajax to my php script. I can't see to get it to work. It keeps on giving me NULL when I do a var_dump on the variable.
JQUERY:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: id
});
LinkUpload(id);
function LinkUpload(id){
$("#link-upload").dialog();
}
});
});
</script>
PHP:
$id = $_POST['id'];
$query = mysql_query("SELECT * FROM xcart_slideshow_slides where slideid='$id'")or die(mysql_error());
$sli = mysql_fetch_array($query);
$slide_id = $sli['slideid'];
$link = $sli['link'];
var_dump($id);
I need the $id variable to post so I can dynamically change the dialog box when the click function is activated.
EDIT:
So I have changed some of my coding:
Jquery:
$(document).ready(function() {
$('.trigger').click(function() {
var id = $(this).prev('.set-id').val();
$.post(
"slide-show-link.php",
{ id: id },
function(data,status){alert("Data: " + data + "\nStatus: " + status); }
);
// alert(id);
LinkUpload(id);
});
function LinkUpload(id){
$("#link-upload").dialog();
}
});
I wanted to see if the data was in fact being passed so I threw an alert in the .post. This is the error I'm getting now:
I have tried passing plain text and echoing it back on the page but it fails. It is just not passing.
Try this -
$.ajax({
type: "POST",
url: "../modules/Slide_Show/slide_show.php",
data: { id : id }
});
I am fiddling with jQuery.ajax() and php, and I need some pointers in order to make everything work:
Here is the php code:
if(!empty($_POST["fname"])){
$firstName = $_POST["fname"];
echo $firstName."<br />";
}
if(!empty($_POST["id"])){
$age = $_POST["id"];
echo $age;
}
Here is the jQuery code:
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
});
var result;
console.log(result);
});
The values from jQuery exist, I get the alert, telling me the data has been submitted, firebug shows the Ajax post as working.
Why doesn't php gets my data and echo it?
You need to get the returned data by the php and do something with it. See the added line of code below.
jQuery("#ajaxForm").submit(function(event){
event.preventDefault();
var firstName = jQuery("#firstName").val();
var age = jQuery("#age").val();
// jQuery.ajax() - Perform an asynchronous HTTP (Ajax) request.
jQuery.ajax({
type: "POST",
url: "http://localhost/profiling/index.php",
data: {fname:firstName, id:age}
}).done(function(result){
alert("Your data has been submitted!" + firstName);
alert("This is the data returned by the php script: " + result)
});
});
You have to use the success callback function to process the response from the POST to your Php page.
As stated in this thread
Your code could look similar to the following:
/* Send the data using post and put the results in a div */
$.ajax({
url: "test.php",
type: "post",
data: values,
success: function(returnval){
alert("success");
$("#result").html('submitted successfully:' + returnval);
},
error:function(){
alert("failure");
$("#result").html('there is error while submit');
}
});
So, you have to somehow append the response from your Php to an HTML element like a DIV using jQuery
Hope this helps you
The correct way:
<?php
$change = array('key1' => $var1, 'key2' => $var2, 'key3' => $var3);
echo json_encode(change);
?>
Then the jquery script:
<script>
$.get("location.php", function(data){
var duce = jQuery.parseJSON(data);
var art1 = duce.key1;
var art2 = duce.key2;
var art3 = duce.key3;
});
</script>
ive been trying for hours to get this to work and havent moved a budge.
What im trying to do is send an url when a button is click, but without refreshing the page
php code of button:
echo 'Send';
jquery code:
<script type="text/javascript">
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('approve-button').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
$.ajax({
url: "votehandler.php", //This is the page where you will handle your SQL insert
type: "POST",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
</script>
votehandler.php:
<?php
$data = $_POST['id'];
mysql_query("UPDATE `link` SET `up_vote` = up_vote +1 WHERE `link_url` = '$data'");
?>
Ive removed all the error checks from votehandler.php to try to get any response but so far nothing.
any advice is welcome, trying to understand jquery/ajax.
Two problems with your code:
The jquery selector isn't working. Correct is: 'a[class="approve-button"]'
The code should being wrapped within the jquery ready() function to make sure that the DOM (with the links) has already been loaded before the javascript code executes.
Here comes a working example:
$(function() { // wrap inside the jquery ready() function
//Attach an onclick handler to each of your buttons that are meant to "approve"
$('a[class="approve-button"]').click(function(){
//Get the ID of the button that was clicked on
var id_of_item_to_approve = $(this).attr("id");
$.ajax({
url: "votehandler.php", //This is the page where you will handle your SQL insert
type: "POST",
data: "id=" + id_of_item_to_approve, //The data your sending to some-page.php
success: function(){
console.log("AJAX request was successfull");
},
error:function(){
console.log("AJAX request was a failure");
}
});
});
});
i have some problems with collecting the data i fetch from database. Dont know how to continue.
What i did so far:
JQ:
$(document).ready(function(){
$('#submit').click(function(){
var white = $('#white').val();
$.ajax({
type:"POST",
url:"page.php",
data:{white:white}
});
});
});
PHP (requested page.php) so far:
$thing = mysql_real_escape_string($_POST["white"]);
..database connect stuff..
$query = "SELECT * FROM table1 WHERE parameter='$thing'";
if($row = mysql_query($query)) {
while (mysql_fetch_array($row)) {
$data[]=$row['data'];
}
}
What i dont know, is how to send out data and receive it with ajax.
What about errors when request is not succesful?
How secure is ajax call against database injection?
Thanks :)
You'll need a success parameter in $.ajax() to get a response once a call is made
$('#submit').click(function(){
var white = $('#white').val();
if(white == '')
{
// display validation message
}
else
{
$.ajax({
type:"POST",
url:"page.php",
data:{"white":white}
success:function(data){
$('#someID').html(data);
}
});
});
Whatever you echo (HTML tags or variables) in page.php will be shown in the element whose ID is someID, preferable to keep the element a <div>
In page.php, you can capture the value entered in the input element by using $_POST['white'] and use it to do whatever DB actions you want to
To send out data to you can write following line at the end :
echo json_encode($data);exit;
To receive response and errors when request is not successful in ajax :
jQuery.ajax({
type:"POST",
url:"page.php",
data:{white:white},
asyn: false,
success : function(msg){
var properties = eval('(' + msg + ')');
for (i=0; i < properties.length; i++) {
alert(properties[i]);
}
},
error:function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus);
}
For Feeling more safety do the following things:
1. Open a Session.
2. Detect Referrer.
3. Use PDO Object instead mysql_real_escape_string
4. Detect Ajax call :
if(empty($_SERVER['HTTP_X_REQUESTED_WITH']) ||
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) !='xmlhttprequest') {
//Is Not Ajax Call!
}