CoffeMug
CoffeMug

Reputation: 37

Cant get PHP variables using AJAX

I can't seem to figure out what's the problem. For my next little project I'm creating dynamic web page with database and etc. I need to get all the necessary variables from PHP file. But for some reason I cannot do it if I include another PHP file. (I need it for database queries).

main.php

include ('databaseQueries.php');

    if (isset($_POST["points"])){
        $points = json_decode($_POST["points"]);
        if($_POST["execute"] == 1){

        }
    }

    $advert= array(
        'Hello' => 'Hello world!',
        'bye' => 'Why bye?',
     );

    echo json_encode($advert, $another);

pageJs.js

$.ajax({
        url : 'php/main.php',
        type : 'POST',
        dataType : 'json',
        success : function (result) {
            console.log(result);
        },
        error : function (err) {
           console.log("Failed");
        }
    })

databaseQueries.php

$another = "another string";

If I remove the include and $another variable from json_encode. Everything works and I get object in console log. But if I leave the those two things, Ajax call fails.

What I'm doing wrong and how can I get both the $test array and $another variable?

Thank's in advance!

Upvotes: 0

Views: 270

Answers (2)

Greg Borbonus
Greg Borbonus

Reputation: 1384

Unless I'm completely wrong, I can't see where you're sending anything TO your post

$.ajax({
    url : 'php/main.php',
    type : 'POST',
    dataType : 'json'
    // I would expect a data call here, something like:
    data: $(form).serialize(), // OR { points: 3, execute: 1 }
    success : function (result) {
        console.log(result);
    },
    error : function (err) {
       console.log("Failed");
    }
})

I assume that you want to spit back some results with the format of result->key;

So Keeleon's answer above is good:

$ret = array($advert, $another);
echo json_encode($ret);

But you can also do:

//Adding everything to array, and asking json_encode to encode the array is the key. Json_encode encodes whatever is in the first argument passed to it.
$ret = array('advert'=>$advert, 'another'=>$another,'test'=>$test);
echo json_encode($ret);

Hopefully, this answers your questions.

Upvotes: 2

Keeleon
Keeleon

Reputation: 1422

You are using json_encode incorrectly. From the documentation:

string json_encode ( mixed $value [, int $options = 0 [, int $depth = 512 ]] )

You are trying to send $another to the function as the options parameter.

You could do something like this:

$ret = array($advert, $another);
echo json_encode($ret);

Upvotes: 6

Related Questions