Delete post using $.ajax - javascript

I am new to $.ajax and don't know so much and i have following button to delete user post by article ID
<button type="button" onclick="submitdata();">Delete</button>
When click this button then following $.ajax process running.
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
var datastring='post_id='+post_id;
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:datastring,
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
And delete.php is
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_GET['post_id']) && is_numeric($_GET['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_GET['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
This code not working post not deleted. Please how do I do?

You likely want to not only match the "GET" you use in your PHP but also add the ID to the button
<button class="del" type="button"
data-id="<?php echo $userIdRow['post_id']; ?>">Delete</button>
using $.get which matches your PHP OR use $.ajax({ "type":"DELETE"
$(function() {
$(".del").on("click", function() {
$.get("delete.php",{"post_id":$(this).data("id")},
function(html) {
alert(html);
}
);
});
});
NOTE: Please clean the var
Do htmlspecialchars and mysql_real_escape_string keep my PHP code safe from injection?
Using ajax DELETE with error handling
$(function() {
$(".del").on("click", function() {
$.ajax({
url: "delete.php",
method: "DELETE", // use "GET" if server does not handle DELETE
data: { "post_id": $(this).data("id") },
dataType: "html"
}).done(function( msg ) {
$( "#log" ).html( msg );
}).fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
});
In the PHP you can do
if ($_SERVER['REQUEST_METHOD'] === 'DELETE') {
$id = $_REQUEST["post_id"] ....
}

since you're sending a post request with ajax so you should use a $_POST iin your script and not a $_GET
here is how it sould be
<?php
// connect to the database
include 'conn.php';
$dbClass = new Database();
// confirm that the 'post_id' variable has been set
if (isset($_POST['post_id']) && is_numeric($_POST['post_id'])) {
// get the 'post_id' variable from the URL
$post_id = $_POST['post_id'];
// delete record from database
if ($userPostsQuery = $dbClass::Connect()->prepare("DELETE FROM user_posts WHERE post_id = :post_id")) {
$userPostsQuery->bindValue(":post_id", $post_id, PDO::PARAM_INT);
$userPostsQuery->execute();
$userPostsQuery->close();
echo "Deleted success";
} else {
echo "ERROR: could not prepare SQL statement.";
}
}
?>
for the JS code
<script>
var post_id="<?php echo $userIdRow['post_id']; ?>";
function submitdata() {
$.ajax({
type:"POST",
url:"delete.php",
data:{"post_id":post_id},
cache:false,
success:function(html) {
alert(html);
}
});
return false;
}
</script>
here i've supposed thqt the give you the real id post you're looking for !!

The reason is pretty simple. You should change your request type to GET/DELETE instead of POST. In PHP you expect GET request but in AJAX you send POST request
Change:
type:"POST",
url:"delete.php",
data:datastring,
to
type:"DELETE",
url:"delete.php?" + datastring,
in PHP
if ($_SERVER['REQUEST_METHOD'] === 'DELETE' && !empty($_REQUEST["post_id") {
$id = $_REQUEST["post_id"];
// perform delete
}
DELETE is actually the only valid method to delete objects. POST should create an object and GET should retrieve it. It may be confusing at first time but it's good practicet specially used in REST APIs. The other one would be UNLINK if you wanted to remove relationship between objects.

Follow #roberts advise and also:
You should have a way to handle errors eg.
to your ajax code add this:
error:function(e){
alert(e.statusText)// if you like alerts
console.log(e.statusText)// If you like console
}
You should also check your error logs. Assuming you use apache2 and linux
execute this in terminal:
tail -f /var/log/apache2/error.log
This gives you a very elaborate way to code. You also eliminate the problem of trial and error.

Related

unable to parse xml data with AJAX + Wordpress

Ok, I am officially stumped. I have been trying to find why my calls for specific items in a PubMed xml data file are not working... I can execute this one with my current coding:
$test = (string)$id_json->PubmedArticle->MedlineCitation->PMID;
but if I try to get a variable that is in a deeper array, it does not return a value. I have even tested with console.log(data) and I get my PMID returning but not my other, deeper values in the XML file. For example;
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
returns nothing for data in console.log(data)
Here is my function in wordpress:
function get_abstract(){
$id = $_POST['abstractid'];
$pubmed_api_call = 'https://eutils.ncbi.nlm.nih.gov/entrez/eutils/efetch.fcgi?db=pubmed&retmode=xml&rettype=abstract&id='.$id;
$id_wpget = wp_remote_get($pubmed_api_call, array('timeout' => 20));
if( is_wp_error( $id_wpget ) ) {
echo "Error Contacting PubMed, please refresh page and try again";
die();
}
$id_xml = wp_remote_retrieve_body($id_wpget);
$id_json = simplexml_load_string($id_xml);
$test = (string)$id_json->PubmedArticle->MedlineCitation->Article->Journal->ISSN;
if($test === ""){
echo "NOTHING";
die();
}
echo $test;
die();
}
and here is my javascript AJAX call:
jQuery(document).ready(function() {
jQuery('.reference_header').click(function(e) {
jQuery(this).find("i").toggleClass("arrow-down arrow-up");
jQuery(this).nextUntil('.reference_header').slideToggle('fast');
var abstractid = jQuery(this).data("id");
e.preventDefault();
jQuery.ajax({
url: get_abstract.ajaxurl,
type: 'POST',
dataType: 'json',
data: {
abstractid: jQuery(this).data("id"),
action: 'get_abstract'
},
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data);
console.log(data);
}
});
});
});
I cannot find out why it doesnt work... any help is greatly appreciated.
So I figured out the solution to the issue... you need to pass the string text as a json object to AJAX for it to read properly...
working code:
PHP:
echo json_encode(array("result" => "$test"));
die();
AJAX:
success : function(data){
jQuery('.'+abstractid).html("TESTING: "+data.result);
console.log(data.result);
}

Script return blank just in jQuery AJAX

I've got very frustrating problem. I send AJAX request to PHP file and when I see Chrome Network Tools, it donť return any JSON. But when I try post the same data via POSTMAN tool in Chrome, it return right. When I open script normally, it return right. Just when I sen request via AJAXm it return nothing.
This is my PHP file: (I know it's functionally useless at this time, i need fix this error before it can do what I need)
$stav = 2;
$ret = array();
$name = query_r("select * from users where username = 'admin'");
$ret['stav']=$stav;
$json = json_encode($ret);
echo $json;
At line 3 must be problem, because when I put it out, it works. But function is 100% exist, 'cause when i put nonsense name of function, it write an error. DB query is also right, i tried it in phpMyAdmin console.
This is my AJAX request:
$("#loginForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "../admin/scripts/login.php",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (vysledek){
if(vysledek.stav===1){
window.location.href("../index.php")
}
else if(vysledek.stav===2){
alertify.error('Špatné uživatelské jméno');
}
else if(vysledek.stav===3){
alertify.error('Špatné heslo');
}
},
error: function(vysledek){
alertify.error('Vyskytla se nějaká chyba');
}
});
});
How I wrote, if I open PHP file in browser, it echo {"stav":2}, when I try POSTman, it echo {"stav":2}. But when I run AJAX request, it makes nothing. I really don't know what is wrong.
EDIT
Firebug:
Here
can you please try with the following code
$("#loginForm").submit(function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "../admin/scripts/login.php",
data: $("#loginForm").serialize(),
dataType: "JSON",
success: function (vysledek){
if( parseInt(vysledek.stav) == 1 ){
window.location.href("../index.php")
}
else if( parseInt(vysledek.stav) == 2 ){
alertify.error('Špatné uživatelské jméno');
}
else if( parseInt(vysledek.stav) == 3 ){
alertify.error('Špatné heslo');
}
},
error: function(vysledek){
alertify.error('Vyskytla se nějaká chyba');
}
});
});
<?php
$stav = 2;
$ret = array();
$name = query_r("select * from users where username = 'admin'");
$ret['stav']=$stav;
$json = json_encode($ret);
print_r($json);
?>
Remember to parse JSON to the response
...
success: function (vysledek){
var vysledek = (vysledek);
if(vysledek.stav === 1){
window.location.href("../index.php")
}
...

AJAX take data from POST with PHP

i have a little problem with my script.
I want to give data to a php file with AJAX (POST).
I dont get any errors, but the php file doesn't show a change after AJAX "runs" it.
Here is my jquery / js code:
(#changeRank is a select box, I want to pass the value of the selected )
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success') },
error: function (err)
{ alert(err.responseText)}
});
});
});
PHP:
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
header('Location:/user/'.$user);
die();
When i run the script, javascript comes up with an alert "success" which means to me, that there aren't any problems.
I know, the post request for my data is missing, but this is only a test, so im planning to add this later...
I hope, you can help me,
Greets :)
$(function(){
$("#changeRank").change(function() {
var rankId = this.value;
//alert(rankId);
//$.ajax({url: "/profile/parts/changeRank.php", type: "post", data: {"mapza": mapza}});
//$("body").load("/lib/tools/popups/content/ban.php");
$.ajax({
type: "POST",
async: true,
url: '/profile/parts/changeRank.php',
data: { 'direction': 'up' },
success: function (msg)
{ alert('success: ' + JSON.stringify(msg)) },
error: function (err)
{ alert(err.responseText)}
});
});
});
require_once('head.php');
require_once('../../lib/permissions.php');
session_start();
$user = "test";
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
$_SESSION["user"] = $user;
echo json_encode($user);
This sample code will let echo the username back to the page. The alert should show this.
well your js is fine, but because you're not actually echoing out anything to your php script, you wont see any changes except your success alert. maybe var_dump your post variable to check if your data was passed from your js file correctly...
Just return 0 or 1 from your php like this
Your PHP :
if($_SESSION["user"] != $user && checkPermission("staff.fakeLogin", $_SESSION["user"], $mhost, $muser, $mpass, $mdb))
{
$_SESSION["user"] = $user;
echo '1'; // success case
}
else
{
echo '0'; // failure case
}
Then in your script
success: function (msg)
if(msg==1)
{
window.location = "home.php"; // or your success action
}
else
{
alert('error);
}
So that you can get what you expect
If you want to see a result, in the current page, using data from your PHP then you need to do two things:
Actually send some from the PHP. Your current PHP redirects to another URL which might send data. You could use that or remove the Location header and echo some content out instead.
Write some JavaScript that does something with that data. The data will be put into the first argument of the success function (which you have named msg). If you want that data to appear in the page, then you have to put it somewhere in the page (e.g. with $('body').text(msg).

Check all possible AJAX responses

I have an AJAX function which POST data to a PHP handler. I echo back either "success" or "failure" from PHP to determine if it was completed as intended. Unfortunately I am not used to JS/AJAX and have trouble finding documentation that answers my questions.
Do I need to JSON encode the response? I only check for .done() in my AJAX function, should I also check success and failed? My code inside of .done() which is just an alert box isn't working, despite the functionality in the PHP handler running without issue.
JS/AJAX:
<script type="text/javascript">
function powerSignal(device, signal)
{
var cfm = confirm("Do you wish to ___ the server?");
if (cfm==true)
{
$.ajax({ type: "POST", url: "https://domain.net/modules/power_functions.php", data: { device: device, 'power_signal': signal }}).done(function(result)
{
alert("success!");
});
}
}
</script>
PHP:
if ( isset($_POST["device"]) && isset($_POST["power_signal"]) )
{
$deviceid = $_POST["device"];
$signal = $_POST["power_signal"];
//API: Get Device Inventory
$url = 'http://domain.net/dp/api/set_device_power_status';
$fields = array('deviceid' => urlencode($deviceid), 'power_signal' => urlencode($signal));
$result = curl_get($url, $fields);
$json = json_decode($result);
$status = $json->{'status'};
if ($status == "success")
{
echo "success";
}
echo "failed";
}
the content of the result variable will be what the server sends back, you'll have to test it :
$.ajax({ type: "POST", url: "https://domain.net/modules/power_functions.php", data: { device: device, 'power_signal': signal }}).done(function(result)
{
if(result=='success'){
alert("success!");
}else{
alert("failure!");
});
To answer the comment below, here is how I do in my current project with a simple get request :
$.get( "/getResult/"+data, function( results ) {
$('.popin_content').html('<p>Vos documents ont bien été créés :</p><br/><ul><li>Plan PDF</li><li>Devis PDF</li></ul>');
});

JavaScript call PHP WebService

i just try to use javascript for build mobile apps. This apps required connection to sql server. I already create the javascript and php file, but whenever i try to call the function it gave me no results. this is the javascript function:
function getvoucher()
{
var result = jQuery.ajax({
type: "GET",
url: aurl,
data: "tag=getvoucher"
async: false
}).responseText;
if(result)
{
var obj = jQuery.parseJSON(result);
if(obj.success == 1)
{
var voucher=obj.name;
document.write(voucher);
}
}
}
this is my phpscript:
<?php
include("../includes/config.php");
if(isset($_REQUEST['tag']) && ($_REQUEST['tag']=='getvoucher'))
{
$success=0;
$query=mysql_query("select code from tbl_voucher")or die ("query issue");
#if(mysql_num_rows($query) > 0)
# {
if($query)
{
$success=1;
$code=$row['code'];
}
# }
$jsondata = array('tag'=>"getvoucher",'success'=>$success, 'code'=>$code);
echo json_encode($jsondata);
if($query){mysql_free_result($query);}
mysql_close($con);
die;
}
>?
The php and connection to sql is working because i already success in other script. And the tbl_voucher and column code is already exist.
Thanks
Perhaps the last die in your php script might be messing up. Loose it.
$jsondata = array( 'tag '=> 'getvoucher','success' => $success, 'code' => $code);
echo json_encode( $jsondata );
if( $query ){ mysql_free_result( $query ); }
mysql_close( $con );
die;
By the way, you are missing a coma here
data: "tag=getvoucher"
Also, your ajax call seems bit weired.
var result = jQuery.ajax({
type: "GET",
url: aurl,
data: "tag=getvoucher"
async: false
}).responseText;
if ( result )
{
var obj = jQuery.parseJSON( result );
if(obj.success == 1)
{
var voucher=obj.name;
document.write( voucher );
}
}
Instead, try this
$.ajax({
type: "GET",
url: aurl,
data: "tag=getvoucher",
async: false,
success: function( object ) {
document.write( object.name );
}
});
If you use google chrome and run the webpage/script, press F12 and look at network=>XHR.
Then you can look at what is submitted and you can even open the result-page.
This way you can see if your parameters are passed and you can see what gets returned.
If something is not passed, you need to fix it on the sender side.
If it is sent and return data is sent, it means reciever side is wrong :-)

Categories

Resources