1

I am trying to call a PHP script using AJAX. I have put a simple echo alert in my deleteitem.php script to check whether it is getting called, but whatever I do, it does not get called. The PHP script is in the same folder as the js script that is calling it

Can someone tell me why that would be? What are the possible causes?

$.ajax({
    url: 'deleteitem.php?task=deleteArtwork&id='+artworkObjectID,
        type: "POST",
        dataType: "html",
        success: function(data)
        {
           //do something here
        }
});
2
  • 4
    Load the URL directly in the browser first Commented Oct 28, 2012 at 10:39
  • 1
    Isnt that a get request.. passing parameters in url? Commented Oct 28, 2012 at 10:43

10 Answers 10

3

How would you know if it's calling it? Add a javascript alert statement to your callback. E.g

alert(data);

It will show what you echoed from the PHP script, if you got everything right.

Sign up to request clarification or add additional context in comments.

Comments

1

As Amitd said, you shouldn't combine GET and POST requests. The code should look like:

$.ajax({
    url: 'deleteitem.php?task=deleteArtwork&id='+artworkObjectID,
        type: "GET",
        dataType: "html",
        success: function(data)
        {
           alert(data); // alert on success
        }
});

If you still don't get any response, there might be a server error, so you should put lines like this one in the .php script, at the beggining of the script:

error_log("script was called, processing request...");
error_log("passed artworkObjectId is: " . $_GET["artworkObjectID"]);

You can then check in your .log file (it can be found in the apache log file/folder if it's running on apache server) if there are any messages.

5 Comments

thanks @mike-johnson. This helped get me started with troubleshooting.
i have a followup question (I am a noob btw) can I print the value in $_GET["artworkObjectID"] using an echo statement in my PHP script? It doesn't seam to work?
Yes, it works this way - ajax request is sent from the client to the server. If request was successful, defined function is called (in this case it is 'function(data){ alert(data);}'. 'data' variable is the response from server (whatever server returns or echoes). Server can echo something (in this case $_GET["artworkObjectID"] and that will be the value of 'data'.
You most certainly can POST data to a url with querystring and access $_GET and $_POST, or combined (plus $_COOKIE) as $_REQUEST
Yup, my bad, you can do that, updating my answer, but it is generally very bad practice to actually do that - from conceptual point of view, as well as security one.
1

The output of the PHP script will be placed in data (assuming that the request is successful).

It won't do anything until you replace the comment //do something here with some code that does something.

Comments

1

Try something like .. passing data like below

 $.ajax({
                    url: "deleteitem.php",
                    type: "POST",
                     data: { 
                          'task': 'deleteArtwork', 
                          'id': artworkObjectID
                     },              
                    success: function (msg) {

                    }
                });

Comments

1

The first thing I would be doing is checking the results of the success callback.

$.ajax({
    url: 'deleteitem.php?task=deleteArtwork&id='+artworkObjectID,
        type: "POST",
        dataType: "html",
        success: function(data)
        {
           alert(data); // Alert the results
        }
}); 

Most times (with myself anyway) when I notice things aren't being updated by ajax is usually a PHP error with my script im calling. This method will alert any errors that PHP throws on that page :)

Also, try and check your browser console and see if there are any errors from your javascript.

1 Comment

thanks @brendan-scarvell - this helped me get started with troubleshooting
1

To check whether the server code is called or not, you can check passed parameters and the AJAX response in Firebug. It would be handy I guess.

Comments

1

index.php

<?php
    session_start();
    
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>
    <title>Document</title>
</head>
<body>
    <center>
    <h1> VISER twitter</h1><br><br>
    <input type="text" id="username"><br><br>
    <input type="password" id="password"><br><br>
    <button id="dugme">Log in</button>
    <div id="odgovor"></div>
    </center>
</body>
</html>
<script>
$("#dugme").click(function(){
    let username=$("#username").val();
    let password=$("#password").val();
    $.post("ajax/ajax_index.php",{username:username, password:password}, function(response){
        if(response=="OK"){
            window.location.assign("posts.php");
        }else{
           $('#odgovor').html("<div class='alert alert-danger'>"+response+"</div>");
        }
    })
})
</script>




ajax_index.php


<?php
    session_start();
    require_once("../funkcije.php");
    require_once("../klase/classLog.php");
    if(!$db=konekcija()){
        echo "Neuspela konekcija bazu!";
        exit();
    }
    
    $username=$_POST['username'];
    $password=$_POST['password'];
    if($username!="" and $password!=""){
        $upit="SELECT * FROM korisnici WHERE email='{$username}' AND lozinka='{$password}'";
        $rez=mysqli_query($db,$upit);
        if(mysqli_num_rows($rez)==1){
            $red=mysqli_fetch_assoc($rez);
            $_SESSION['email']=$red['email'];
            $email=$red['email'];
            $_SESSION['podaci']=$red['ime']." ".$red['prezime']. ' ('.$red["status"].")";
            //echo $_SESSION['podaci'];
            Log::upis("Prijava korisnika '{$email}'");
            echo "OK";
        }
        else{
            echo "Ne postoji korisnik sa unetim podacima";
        }
    }
    else{
        echo "Morate uneti podatke u oba polja";
    }
?>



funkcije.php



<?php
    function konekcija(){
        $db=mysqli_connect("localhost","root","","pva_k2");
        return $db;
    }
?>




logout.php


<?php
    session_start();
    session_unset();
    session_destroy();
    header("Location:index.php");
?>





posts.php




<?php
    session_start();
    require_once("funkcije.php");
    if(!isset($_SESSION['podaci'])){
        echo"Niste ulogovani! <br> <a href='index.php'>Prijava</a>";
        exit();
    }
    if(!$db=konekcija()){
        echo "Neuspela konekcija bazu!";
        exit();
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>

    <title>Document</title>
</head>
<body>
    <center>
    <h1 >Stranica Posts.php</h1><br><br><br>
    <p> Trenutni korisnik <?php echo $_SESSION['podaci'];?></p>
    <a href="posts.php">Sve objave</a>
    <a href="logout.php">Odjava</a>
    <a href="admin.php">Administracija</a>
    </center>
    <h3>Postovi</h3>
    <input type="text" id="post"><button id="dodaj" onclick="dodajPost()">Dodaj post</button>
    <div id="postovi" class="alert alert-success"></div>
</body>
</html>
<script>
    $(document).ready(function(){
        prikaziPostove();
    })
    function prikaziPostove(){
        $.get("ajax/ajax_posts.php?akcija=prikazi",function(response){
            $("#postovi").html(response);
        })
    }
    function dodajPost(){
        let post=$("#post").val();
        if(post==""){
            alert("Svi podaci su obavezni!!!!");
            return false;
        }
        $.post("ajax/ajax_posts.php?akcija=dodajPost",{post:post}, function(response){
            alert(response);
            prikaziPostove();
        })
    }
    function obrisi(idPosta){
        if(!confirm("Da li ste sigurni?")) return false;
        $.post("ajax/ajax_posts.php?akcija=obrisi",{id:idPosta}, function(response){
            alert(response);
            prikaziPostove();
        })
    }
</script>




ajax_posts.php





<?php
    session_start();
    require_once("../funkcije.php");
    require_once("../klase/classLog.php");
    if(!$db=konekcija()){
        echo "Neuspela konekcija bazu!";
        exit();
    }
    $akcija=$_GET['akcija'];
   
    if($akcija=="prikazi"){
        $upit="SELECT * FROM veza_korisnici_post";
        $rez=mysqli_query($db,$upit);
        while($red=mysqli_fetch_assoc($rez)){
            $pos=$red['vremeK'].' '.$red['post'].' '.$red['ime']. " -". $red['prezime']."
            <button onclick='obrisi({$red['id']})'>Obriši</button>"."<br><br>";
            echo $pos;
        }
    }
    if($akcija=="dodajPost"){
        $post=$_POST['post'];
        $sql="INSERT INTO postovi (idKorisnika, post) VALUES ({$_SESSION['id']}, '{$post}')";
        $rez=mysqli_query($db,$sql);
        if(mysqli_error($db)) echo "Greška!!!!!";
        else {
            Log::upis("Kreiranje novog posta sa id=".mysqli_insert_id($db)." od strane korisnika '{$_SESSION['email']}'");
            echo "Uspešno dodat post.";
        }
            
    }
    if($akcija=="obrisi"){
        $id=$_POST['id'];
        $sql="DELETE FROM postovi WHERE id={$id}";
        $rez=mysqli_query($db,$sql);
        if(mysqli_error($db)) echo "Greška!!!!!";
        else echo "Uspešno obrisan post.";
            
    }


?>




admin.php



<?php
    session_start();
    require_once("funkcije.php");
    if(!isset($_SESSION['podaci'])){
        echo"Niste ulogovani! <br> <a href='index.php'>Prijava</a>";
        exit();
    }
    if(!$db=konekcija()){
        echo "Neuspela konekcija bazu!";
        exit();
    }
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.7.1.min.js" integrity="sha256-/JqT3SQfawRcv/BIHPThkBvs0OEvtFFmqPF/lYI/Cxo=" crossorigin="anonymous"></script>

    <title>Document</title>
</head>
<body>
    <center>
    <h1 >Administrator.php</h1><br><br>
    <p> Trenutni korisnik <?php echo $_SESSION['podaci'];?></p>
    <a href="posts.php">Sve objave</a>
    <a href="logout.php">Odjava</a>
    <a href="admin.php">Administracija</a>
   
    <br><br><br>
    <input type="date" id="datum"><br><br>
    <button onclick='prikaziLog()'>prikazi log</button>
    </center>
</body>
</html>
<script>
    $(function(){
        
    })
    function prikaziLog(){
        let datum=$("#datum").val();
        $.get("ajax/ajax_admin.php?akcija=prikaziLog", {datum:datum},function(response){
            $("#odgovor").html(response);
        })
    }
   
</script>




ajax_admin.php




<?php
    session_start();
    require_once("../funkcije.php");
 
    if(!$db=konekcija()){
        echo "Neuspela konekcija na bazu!!!!";
        exit();
    }
    $datum=$_GET['datum'];
    if($datum!=""){
        $file="../logovi/".$datum."_log.txt";
        //echo $file;
        if(file_exists($file)){
            $odg=file_get_contents($file);
            $odg=nl2br($odg);
            echo $odg;
        }
        else echo "Nema podataka {$datum}!!!!";
    }else echo "Svi podaci su obavezni!!!!";
?>





klase/classLog.php




<?php
    class Log{
        public static function upis($tekst){
            $datum=date("Y-m-d");
            $file="../logovi/".$datum."_log.txt";
            $file=fopen($file, "a");
            fwrite($file, date("H:i:s")." - ".$tekst."\n");
            fclose($file);
        }
    }
?>


logovi folder

1 Comment

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
0

First of all, you're not outputting the returned data, stored in (your case) data Also, you're parsing along some GET variables, although your AJAX-request is POST. If you're working with variables over AJAX, i recomend using GET:

$.get('deleteitem.php?task=deleteArtwork&id='+artworkObjectID, function (data) {
    //On success, perhaps print the returned data:
    alert(data);
})

Comments

0

Make sure the file you has created is having valid file Type like PHP file or just copy paste the existing valid working php file and write you ajax code in it. It will work now. myAjax file shown in below image is invalid file and material is valid PHP fileenter image description here

Comments

-1
url: 'deleteitem.php?task=deleteArtwork&id='+artworkObjectID 

should be

url: 'deleteitem.php?task=deleteArtwork&id='.artworkObjectID,

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.