Search code examples
phpjqueryjsonpostgetjson

$_POST not picking up value (getJSON)


I am trying to use getJSON to pull data from a PHP file however when I pass in "data" it the $_POST call doesn't seem to be retrieving any data.

function runJSON(network,searchType){
        var URL     = returnURL(network,searchType,$('#song_field').val().split(' ').join("+"));

    var val = $('#song_field').val();
    var data = {val: val}

    $.getJSON(URL, val, function(data){
        if(document.getElementById("box") !== "undefined"){
            clearScreen();
            createCols();
        }

        songList = [];
        console.log(data);
        eval(network + "(data);");

        for(i = 0; i < songList.length; i++)
        {   
            displayTrack(i);
        }

        done = true; 

    });
}

php file:

<?php
    $input = $_POST["val"];
    $url   = "http://api.7digital.com/1.2/track/search?q=" . $input . "&oauth_consumer_key=myconsumerkey&country=GB&pagesize=2";

    $data = simplexml_load_file($url);
    $json = json_encode($data);
    echo ($json);
?>

Solution

  • your $.getJSON call should pass in data not val:

    $.getJSON(URL, val, function(data){
    

    should be

    $.getJSON(URL, data, function(data){
    

    And your php should use $_GET not $_POST

    $input = $_POST["val"];
    

    should be

    $input = $_GET["val"];