Fale1994
Fale1994

Reputation: 77

Ajax call - PHP return value

I want php file to return data (from the database) on ajax call. Ajax call returns an error alert everytime. I tried everything, but have no idea how to return array from PHP to ajax call

So far, I made this..

ajax call

function dohvatiPrveTriAkcije(id){
var url = 'http://localhost/ljekarna/model/akcija.php';
$.ajax({
    type: "POST",
    url: url,
    cache: false,
    data: { "kategorija": id},
    dataType: "json",
    success: function (data) {
        document.getElementById("kat_id").innerHTML += 'aaa';
    },
    error: function () {
        alert('Pojavila se greška pri dohvacanju akcija za odabranu kategoriju');
    }
});
return null;
}

php class

<?php

 require_once 'baza_model.php';

 $akcija = new Akcija();

if (isset($_GET['kategorija'])) {
echo $_GET['kategorija']; 
$akcije = $akcija->dohvatiPrveTriAkcijeZaKategoriju($_GET['kategorija']);
echo $akcije;
}

class Akcija{
private $baza;   

static function dohvatiPrveTriAkcijeZaKategoriju($kategorija){

    $baza = new Baza();
    $akcije = array();

    $upit = 'SELECT lijek.naziv, akcija.postotak, akcija.datum_zavrsetka FROM akcija join lijek on akcija.lijek = lijek.id 
            join kategorija on lijek.kategorija = kategorija.id 
            where akcija.datum_zavrsetka > CURDATE() AND kategorija.id = ' . $kategorija . ' AND akcija.status = 1 
            ORDER BY akcija.datum_zavrsetka ASC LIMIT 3';

    $rez = $baza->selectDB($upit);
    while($red = $rez->fetch_assoc()){
        echo "id: " . $red["id"];
        $akcije[] = $red;
    }
    return $akcije;
}

}

I also tried this...

enter image description here

Upvotes: 1

Views: 1403

Answers (1)

georaldc
georaldc

Reputation: 1940

You need a json formatted string returned by the server. Use json_encode() instead of trying to echo out your array (which is what's giving you your array to string error).

Upvotes: 1

Related Questions