user3160441
user3160441

Reputation: 163

AJAX post method from JS to PHP - variable null

I want to call the server function from client side via AJAX.

index.php:

<?php 
?>
<html>
<head>
...
 <script src="http://code.jquery.com/jquery-latest.min.js"></script>
...
        console.log(position); // there IS a value! good!
        console.log(result);   // there IS a value! good!
  jQuery.ajax({
        type: "POST",
        url: 'crud.php',
        data: {functionname: 'insertLocation', arguments: [position, result]}, 
         success:function(data) {
        alert(data); 
         }
    });

crud.php:

<?php 
    $position = $_POST["position"]; //NOTHING!
    $result = $_POST["result"];     //NOTHING!
    include ("insert.php");
    switch($_POST["functionname"]){ 
        case 'insertLocation': 
            insertLocation($position,$result);
            break;      
    }   
 ?>

insert.php

<?php 
function insertLocation($position,$result){
...
}
?>

I am losing the value when passing it to the server side. I am able to log the value from JS , but then when I am logging in php there is null (or empty string?). Also query to Database works but no value is inserted.

I am beginner with web programming so I apologise in advance for bad smells, etc.

Upvotes: 1

Views: 660

Answers (2)

davidkonrad
davidkonrad

Reputation: 85528

Yes, $_POST has your variables, but they are located in the array $_POST['arguments'] :

$_POST['arguments'][0] == position
$_POST['arguments'][1] == result

If you want to be able to do $result = $_POST["result"] you must change the params in your AJAX request to

...
data: {functionname: 'insertLocation', position: position, result: result}, 
...

Upvotes: 2

data: {
    functionname: 'insertLocation', 
    position: position,
    result: result
}

Upvotes: 0

Related Questions