0

This is something a user helped me with, he told me to use json and it seems smart. But it doesn't work correctly i'm not sure how json and ajax truly work.

<?php
$rx=$_GET["rx"];
$ry=$_GET["ry"];
$arr=array();
session_start();
if($rx==$_SESSION['randomx'] and $ry==$_SESSION['randomy']){
     $arr['good'] = "Cestitam, zadeli ste pravilno celico! rabili ste samo:".$_SESSION['poskus'];
}
    else{
    $razdalija=sqrt(($rx-$_SESSION['randomx'])*($rx-$_SESSION['randomx'])+($ry-$_SESSION['randomy'])*($ry-$_SESSION['randomy']));
    $arr['bad'] = $_SESSION["poskus"].". Zgresili ste za: ".round($razdalija);
    $_SESSION["poskus"]++;
}
    echo json_encode($arr);
?>  //php

    function test(celica,i,j){ //this is the js function with ajax
        $.ajax({
            type: "get",
            url: "preveri.php",
            data: { rx: i, ry: j}
            }).success(function(data){
            if(data.hasOwnProperty('good')){ //comparing which array json sent
                    celica.className="zelena"; //cell name green
                    $('#tekst').val($('#tekst').val()+ data.good + "\n"); //data should be the text that returns from php
                 }
            else{ 
            celica.className="rdeca"; 
            $('#tekst').val($('#tekst').val()+ data.bad + "\n");}
            });
    }    

I need to get the "good" and "bad" array so i can compare them in ajax and know which came back so i can change the cell style.

user3617642
  • 27
  • 1
  • 7
  • 2
    Since you're not outputting a `Content-type: application/json` header then you need to specify the type using `dataType: 'json'` inside of your ajax call. – h2ooooooo Jan 23 '15 at 10:06
  • Also, in the spirit of json response, the json should look like `{'status':'ok','error':0}` or `{'status':'bad','error':20}`. Than you check `if (data.status=='ok') { ... }` – skobaljic Jan 23 '15 at 10:08
  • You can find json headers for php [here](http://stackoverflow.com/questions/20620300/http-content-type-header-and-json) – skobaljic Jan 23 '15 at 10:10

0 Answers0