1

Im trying to trying to return a PHP variable which is made of a SQL query to the same database using jquery.

At the moment my method does not work but i cant figure out why. Currently getting the following messages on the PHP response along with the error alert configured in the js function:

Warning: Illegal offset type line 55

{"average":null} 

Im very new to PHP and server side programming, so an explanation of where i am going wrong would be really good. I am sure it is just a really simple misunderstanding i have with how i am going about this.. its baffling me so far though!

javascript function to make ajax call to PHP page

so here i have defined an array and added 2 values to it to post to the PHP page.

once recieved i want PHP to change the value to one it will get by doing an SQL query

var javascriptvalue = []
javascriptvalue["id"] = "the id";
javascriptvalue["name"] = "the name";

    function averageRecall() {
        $.ajax({
        type : 'POST',
url : 'recall.php',
        data: JSON.stringify(javascriptvalue),    
        dataType : 'json',
        success : function (result) {
      console.log(result); // see too what we get in the request
    console.log(result.average);
        },
        error : function () {
           alert("error");
        }

PHP:

Here PHP should run a query against the DB and return a single value into the variable $avg which will be passed to an array, coded to JSON and then echoed back into my JS callback function.

    <?php
$servername = "localhost";
$username = "user";
$password = "pass";
$dbname = "db";


// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

$avg = $conn->query("SELECT AVG(`Answer`) AS AvgAnswer
           FROM (
SELECT `multi1` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi2` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi3` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi4` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `multi5` AS Answer
FROM `zc_Answers`
UNION ALL
SELECT `radio1` AS Answer
FROM `zc_Answers`        
UNION ALL
SELECT `radio2` AS Answer
FROM `zc_Answers`
               UNION ALL
SELECT `radio3` AS Answer
FROM `zc_Answers`
               UNION ALL
SELECT `radio4` AS Answer
FROM `zc_Answers`
               UNION ALL
SELECT `radio5` AS Answer
FROM `zc_Answers`
           ) AS s1");

if (!$avg) {
    echo 'Could not run query: ' . mysql_error();
    exit;
}

header('Content-Type: application/json');
$avg2 = array('average' => $_POST[$avg]
 );
echo json_encode($avg2);
$conn->close();
?> 
9
  • What does console.log(result) return ? Commented Aug 8, 2015 at 15:48
  • @guest271314 "result is not defined" Commented Aug 8, 2015 at 15:51
  • Have you trierd the query? Is it working fine? Commented Aug 8, 2015 at 15:51
  • @HéctorE it is in SQL, im not sure how to test it through PHP other than inserting it into a return call like i have Commented Aug 8, 2015 at 15:52
  • 1
    $avgcalculation is just the query - $avgcalculation = mysql_query("SELECT AVG(Answer) AS AvgAnswer .... You need to do a fetch on that query - 'average' => mysql_fetch_assoc($avgcalculation)['AvgAnswer']. Commented Aug 8, 2015 at 15:58

2 Answers 2

1

First , try adding this to your php file because it doesn't return a JSON response :

header('Content-Type: application/json');
$avg = array(
    'average' => $avgcalculation // you can try sending just a number to see if the script works excluding your query
 );
echo json_encode($avg);

then , in your success function of javascript you have :

    dataType : 'json',//So we need to do the header() step in php
    success : function (result) {
       console.log(result['average'])// ???????
    },

You try to get an item of a javascript array by string index ... which is not possible.

1) You write dataType:json <<< So, the result variable is a object ! So you can access average value with :

success:function(result){
    console.log(result); // see too what we get in the request
    console.log(result.average); // thats all
}

UPDATE : in order to help you ._.

your php script is failing too because you are retrieving POST values that doesn't exist because you are not sending them !

Please read the documentation of $.ajax() here.

Try first with a simple script in php to see if your javascript works. Comment everything just let 2 lines.

header('Content-Type: application/json');
$avg = array(
'average' => $_POST["javascriptvalue"]
 );
echo json_encode($avg);

then in your javascript file add the data tag (because you need to retrieve data in your server !)

data:{
  javascriptvalue:"I'm sending this to php so it can be retrieved in my php script"
},

Finally your success javascript function should be executed without problem with :

  success:function(data){
     console.log(data);//an object with average property (data.average)
   }

It should work anyway this is not dificult, read the documentation

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

10 Comments

Im still getting "avg is undefined" in the console. Should i be using something else for my data: statement
you have in your ajax :" data : avg " , what is this value in your function ? could you update your question with this information ? Remember data is the post/get etc .. that you send to the php script and retrieve it there via $_POST or whatever method you use
this is the variable im defining in PHP. I thought this was needed in the POST request. Ive removed this piece of code and now its no longer giving the undefined error, however now its giving the error alert from the jquery error function. Would it be helpful if i posted the rest of my PHP file?
Yes , keep in mind you need to set in php the header as JSON, otherwise $.ajax will throw error because the response is not json format !
ive added the updated PHP file, which includes the other functions i am using to submit data back to the database. This request will come before the SQL data creation request
|
1

"data: avg" in the Ajax call is the data you want to send to the PHP (your page form values) that's why "avg" needs to be defined in the javascript before making the ajax call, that's why you get "avg is undefined". You need to create the variable and somehow fill it with the form values. For the PHP if it is on a server you need to work a little bit more like Carlos explained.

I give you some example code from a project I'm working on:

JS CLIENT SIDE

//jsonvar is an array

jsonvar["id"] = "the id";
jsonvar["name"] = "the name";

$.ajax({
    url: url_webservice,
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: JSON.stringify(jsonvar), //turn jsonvar into json to send to the php server
})
.done(function(result) {
    console.log("Show the result from the PHP in the console", result);
    // Do all you want with the result
})
.fail(function(err) {
    console.log(err.responseText);
    // Do all you want in case of error
    });
});

PHP SERVER SIDE

header('Content-Type: text/html; charset=utf-8');

//Get the data from the POST
$input_data = json_decode(file_get_contents("php://input"), FILE_USE_INCLUDE_PATH);

if(is_null($input_data)) 
{
    trigger_error('Error empty input data in server.php', E_USER_WARNING);
}

//Do what you want with input data, sorry not familiar with mysql code.

echo json_encode($result); //Back to the client

2 Comments

cheers for this. I think im slowly making progress! Would you mind posting your associated PHP for me to have a look at? Am i taking the correct approach here in passing a variable through to PHP in order to recall a variable of the same name with a different value? I feel im just missing something really simple in my understanding of the link between JS PHP and mySQL
@Ash Yes, you need to read a little bit more about Ajax, JS, PHP and My SQL interaction. jsonvar is a variable in the client side (browser), you use Ajax to send data (not variables) to the server side (PHP in this case) and you use whatever variable you want in the PHP and return some data (again not variables) to the client. I will edit with the PHP server side code.

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.