Reputation: 1153
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
}
});
Upvotes: 1
Views: 19176
Reputation: 11
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
Upvotes: 1
Reputation: 340
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 file
Upvotes: 0
Reputation: 1
url: 'deleteitem.php?task=deleteArtwork&id='+artworkObjectID
should be
url: 'deleteitem.php?task=deleteArtwork&id='.artworkObjectID,
Upvotes: -1
Reputation: 1029
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.
Upvotes: 1
Reputation: 1740
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.
Upvotes: 1
Reputation: 2851
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);
})
Upvotes: 0
Reputation: 41587
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.
Upvotes: 1
Reputation: 4849
Try something like .. passing data like below
$.ajax({
url: "deleteitem.php",
type: "POST",
data: {
'task': 'deleteArtwork',
'id': artworkObjectID
},
success: function (msg) {
}
});
Upvotes: 1
Reputation: 943108
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.
Upvotes: 1
Reputation: 6117
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.
Upvotes: 3