-2

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!

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
  • You're doing AJAX in a loop; are you seeing results and the notice for each iteration? – El_Vanja Apr 03 '20 at 12:16
  • Yes, the result is visible in loop. But when i run the php file separately, I get the error stated above. – Pari Deshpande Apr 03 '20 at 12:21
  • Does this answer your question? ["Notice: Undefined variable", "Notice: Undefined index", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-and-notice-undefined) – Alon Eitan Apr 03 '20 at 12:27
  • I tried using if( isset($_POST['vote_to_send'])), it always goes in the else part. – Pari Deshpande Apr 03 '20 at 12:29
  • 1
    Run separately? Meaning directly opening the page? Of course you get that notice since there is no post request then. – El_Vanja Apr 03 '20 at 12:32
  • You need to check the request body and see what is being sent to the server – Alon Eitan Apr 03 '20 at 12:35
  • Yes, because I'm trying to insert that value in my database, so when I tried doing that I got the error, so I started putting break points and noticed that the value is not getting accessed, and hence not getting entered into the db via php file – Pari Deshpande Apr 03 '20 at 12:37
  • A script made for an AJAX action is not meant to be accessed directly. If you had trouble inserting into the database, then you should have posted that. – El_Vanja Apr 03 '20 at 12:39
  • Alon, how do I do that? Checking the request body? – Pari Deshpande Apr 03 '20 at 12:39
  • But at least I should get the value I'm sending through ajax in that variable when I echo it – Pari Deshpande Apr 03 '20 at 12:40
  • Well, you said you are seeing it now in the console. Meaning something else was the problem if you had some other code before the echo. I suggest you edit the question with the code that was trying to insert because, at the moment, there is no problem with your script (outside of you trying to access that page directly, which makes no sense). – El_Vanja Apr 03 '20 at 12:43
  • I have added my database insertion code, you may have a look now – Pari Deshpande Apr 03 '20 at 12:55
  • 1
    And what is the issue with it? What do you get in the response, what does the console show? You're also wide open to [SQL injection](https://stackoverflow.com/questions/332365/how-does-the-sql-injection-from-the-bobby-tables-xkcd-comic-work). You should use [prepared statements](https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php) instead. – El_Vanja Apr 03 '20 at 13:00
  • Output : Result is
    Notice: Undefined index: vote_to_send in C:\xampp\htdocs\Election\EVoting\src\MegaProjectWebsite\generateResult.php on line 6
    – Pari Deshpande Apr 03 '20 at 13:15
  • Does `header('Access-Control-Allow-Origin:(http://localhost/Election/EVoting/src/MegaProjectWebsite/generateResult.php')` help? – Ayman Arif Apr 03 '20 at 14:00
  • I just used Get instead of post and it worked. Thanks for your help though! I don't know how it worked, but it did :D – Pari Deshpande Apr 03 '20 at 14:43
  • Did you change HTTP request to GET in both PHP and jQuery? – Ayman Arif Apr 04 '20 at 08:23
  • Yesss, it worked – Pari Deshpande Apr 05 '20 at 09:18
  • It is better to use POST requests. GET request is bad for security – Ayman Arif Apr 06 '20 at 09:24

1 Answers1

-1

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.

Ayman Arif
  • 1,456
  • 3
  • 16
  • 40
  • 1
    This has nothing to do with the error. You wrote it yourself, it defines what "jQuery is expecting from server", not the other way around. – El_Vanja Apr 03 '20 at 12:33
  • adding the data type doesn't make any difference! The error still persists. Thanks for the help, though! – Pari Deshpande Apr 03 '20 at 12:37