Mohammad Areeb Siddiqui
Mohammad Areeb Siddiqui

Reputation: 10189

jQuery Ajax is not getting posted to a PHP file

I am new to AJAX so I know there could be a silly mistake in my code but anyways I will go ahead.

I have a function created that is called when a button is clicked. The function calls .ajax() method of jquery. I send the data to a file named 'delete_post.php`.

HTML:

<button class="btn btn-primary" onclick="deletePost(<?php echo $_GET["id"]; ?>);">Yes</button>

The above code works.

JS:

function deletePost(postid) {
    $.ajax({
        type: 'post',
        url: "delete_post.php?id="+postid,
        success: function(data) {
            if(data.error == true) console.log('error');
                    else console.log('problem?');
        }
    });
}

The above code is calling the .ajax() function but is not logging 'problem?' into the console.

Here's the PHP file:

<?php
require_once '...';
if(isset($_GET["id"])) {
    $id = $_GET["id"];
    echo "YEAH!";
} else {
    header("location: index.php");
}
?>

What's the issue and how can I fix it?

Upvotes: 1

Views: 943

Answers (3)

mamdouh alramadan
mamdouh alramadan

Reputation: 8528

as we discussed in the chat side, you can use it like this:

JS:

function deletePost(postid) { 
$.post('delete_post.php', {id : postid}, function(data){ 
console.log(data); 
}, 'json'); 
}

PHP:

 <?php 

    require_once '...'; 
    if(isset($_POST["id"])) { 
    $data['res'] = 'yes'; 
    echo json_encode($data); 
    } else { 
    header("location: index.php"); 
    } 
    ?> 

Upvotes: 4

Sunil Kumar
Sunil Kumar

Reputation: 1391

Here is your working code, In your AJAX you are doing "POST" and in your PHP file your using "GET".

trigger.html

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script type="text/javascript" src="jquery-1.7.1.min.js"></script>
<script>
function deletePost(postid) {
    $.ajax({
        type: 'GET',
        url: "http://localhost/overflow/delete_post.php?id="+postid,
        success: function(data) {
           console.log('success:'+data);
        }, error: function(xhr, status, error){
            console.log(xhr.responseText);
        }
    });
}
</script>
</head>

<body>   

<button class="btn btn-primary" onclick="deletePost(9); return false;">Yes</button>
</body>
</html>

delete_post.php

<?php
//require_once '...';
if(isset($_GET["id"])) {
    $id = $_GET["id"];
    echo "YEAH!";
     //do something
} else {
   // header("location: index.php");
     echo "not set";
}
?>

Try this and let us know your problem in detailed and clear. good luck

Upvotes: 0

Rajesh
Rajesh

Reputation: 3778

There is an escape issue in the following part:

onclick="deletePost(<?php echo $_GET["id"]; ?>);"

It must be as below:

onclick="deletePost(<?php echo $_GET['id']; ?>);"

And, you are echoing 'YEAH!', so the if condition should be:

if(data == 'YEAH!')

Upvotes: 0

Related Questions