简体   繁体   中英

Errors when attempting an ajax POST call to PHP to return SQL query variable to jquery

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();
?> 

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

"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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM