简体   繁体   中英

Not able to access data sent through ajax in php

So I am sending a variable through ajax in my php file. Here's my code

getVoteCount: function(){
    App.contracts.Election.deployed().then(function(instance) {
        for(i=0; i<4; i++){
        instance.candidates(i).then(function(candidate) {
            var vName = candidate[1];
            var vCount = candidate[2];
            var x = (vCount+" ");
            var y = vName;
                $(document).ready(function() {
                $.ajax({
                    method: 'POST',
                    url: 'http://localhost/Election/EVoting/src/MegaProjectWebsite/generateResult.php',
                    data: {'vote_to_send' : x},
                }).done(function(result) {
                    result1 = JSON.parse(JSON.stringify(result));
                    **console.log("Result is "+result1);**
                })
            })

Now my php code is as follows:

<?php

    header('Access-Control-Allow-Origin: *');
    echo "hello";
        $x =  $_POST['vote_to_send'];
        echo $x;
    $con = mysqli_connect('localhost', 'root', '', 'letsvote');
    $sql = "insert into result (vote_count) values (".$_POST['vote_to_send']. ")";
    if(mysqli_query($con, $sql))
    {echo "done";}
    else{
      echo mysqli_error($con);
}

The problem is, I cannot access the variable ($_POST['vote_to_send']) . It gives the error:

Notice: Undefined index: vote_to_send in C:\xampp\htdocs\Election\EVoting\src\MegaProjectWebsite\generateResult.php on line 4

Because of this, the insert operation also fails. However the result is visible in the console in result1 (given in bold above) in the .done() function. I am unable to understand why this is happening!

You forgot to mention dataType in your AJAX call. PHP server-side does not get data type information, hence it is spitting out an error.

$(document).ready(function() {
                $.ajax({
                    method: 'POST',
                    url: 'http://localhost/Election/EVoting/src/MegaProjectWebsite/generateResult.php',
                    data: {'vote_to_send' : x},
                    dataType: 'json'
                }).done(function(result) {
                    result1 = JSON.parse(JSON.stringify(result));
                    **console.log("Result is "+result1);**
                })

dataType specifies what is the type of data is jQuery is expecting from server. If it is JSON, do dataType:'json' or something else accordingly.

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