简体   繁体   中英

Calling php script with ajax

I've got this simple page to understand the workings of ajax, but I haven't been able to execute the specified php file and get a success. Here's the code, extra points for explanation:

html page:

<html>
<head>
  <meta charset="utf-8">
</head>
<body>
  <button onclick="addToDb()">click me!</button>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1./jquery.min.js"></script>
  <script src="js/addtodb.js"></script>
</body>
</html>

js script:

function addToDb()
{
    var source = "SoundCloud";
    var partyKey = "4";
    var id = "0987654321";
    //window.alert("check your db"); // this is called as expected
    jQuery.ajax({
        type: 'POST',
        // correctly finds the script but never executes it
        url: 'PHP/functionFilter.php',
        dataType: "json",
        data: {functionname: 'addSong'},
        success: function(response) { window.alert(response); }
    });
};

php file:

<?php
echo "".$_POST['functionname'];
?>

note I do not get any errors.

You are sending your data with dataType "json". You will need to encode your data when you echo out.

$array = array("success" => true, "message" => "hello world");
echo json_encode($array);

try this on your php code,

<?php 
    echo json_encode(array(isset($_POST['functionname']) ? $_POST['functionname'] : "error" ));
?>

The cumulative solution(s) to my problem(s)

$anArray;
if (isset($_POST['functionname']))
{$anArray = array('message' => $_POST['functionname']);}
else
{$anArray = array('message' => "error");}
echo json_encode($anArray);

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