user2330619
user2330619

Reputation: 23

Passing a variable from JavaScript to PHP through AJAX

I'm trying to pass the a variable from JavaScript to PHP using AJAX, but I'm unable to do so. Whenever I try to var_dump($_POST['winner_id']) it returns NULL. I've tried to check the AJAX call with Developer Tools in Chrome and it showed winner_id:0 - which is right.

Here is my code:

JavaScript

 function ajaxCall() {

   alert("To AJAX: the winnerid is: "+winner_id);

        $.ajax
        (   {


                type: "POST",
                url: "ajax.php",
                data: {winner_id : winner_id}, 
                success: function(response)
                { alert("The winner was passed!")}
            }
        );
};
ajaxCall();

PHP Code

<?php 
session_start();

if(isset($_POST['winner_id']))

{
    $winner_id = $_POST['winner_id']."";
    var_dump($winner_id);
}

var_dump($_POST['winner_id']);

?>

If I do a var_dump($_POST) in the beginning of the PHP script then it gives me array(0) { }

I'm new to web development and have been trying to figure this out for hours now. Any hints would be much appreciated. Thanks!

Upvotes: 0

Views: 7162

Answers (3)

Charlene Lauron
Charlene Lauron

Reputation: 1

i guess you have to convert your winner_id to a string because php read zero (0) as null

function ajaxCall() {

   alert("To AJAX: the winnerid is: "+winner_id);

        $.ajax
        (   {


                type: "POST",
                url: "ajax.php",
                data: {winner_id : winner_id.toString()}, 
                success: function(response)
                { alert("The winner was passed!")},
                dataType: "json"
            }
        );
};
ajaxCall();

Upvotes: 0

웃웃웃웃웃
웃웃웃웃웃

Reputation: 11984

Where are you intializing the winner_id.Either you have to pas it as an argument or intitialize it as aglobal variable.

function ajaxCall(winner_id) {

   alert("To AJAX: the winnerid is: "+winner_id);

        $.ajax
        ({
                type: "POST",
                url: "ajax.php",
                data: {"winner_id" : winner_id}, 
                success: function(response)
                  { 
                     alert("The winner was passed!");
                  }
        });
};
ajaxCall(winner_id);

Upvotes: 2

Amir
Amir

Reputation: 4111

Where did you initiate value to winner_id? like

function ajaxCall() {
var winner_id = '123';
...

or if you initiated winner_id before calling ajaxCall() ,you should call ajaxCall() with parameters like ajaxCall($winnerid), which $winnerid is from your PHP and then

function ajaxCall(winner_id) {
...

Upvotes: 0

Related Questions