0

I call my API with following Code (as well for other Websites):

$(function () {

    $("#hb_api").load("http://api.site.de?apikey=71290473059");
    $("#hb_api").load("http://api.site.de/src/controller.js");

})

controller.js contains following Code:

    $(function () {

    $('#btn1').on('click', function () {

      var vars = {
        test:     $('#test').val(),
        action:     'POST'
      }
        $.ajax({
            url: "http://api.site.de/src/api_controller",
            data: vars,
            type: "POST",
            dataType: "json"
        }).done(function (d) {
            var outp = d.response.post;
            var outs = d.response.status;
            $('#outp').html(outp + ", " + outs);
        }).fail(function (xhr, textstatus) {
            console.log(xhr);
            console.log(textstatus);
        })
    })
})

And the index site this:

$api_key = $_GET['apikey'];

if (!isset($api_key)) {
  header('HTTP/1.0 404 Not Found', true, 404);
  exit();
}

require 'src/database.php';

$stmt_api = $pdo->query("SELECT `api_key` FROM `api` WHERE api_key = '{$api_key}'");
$q_api_key  = $stmt_api->fetch();

if (!$q_api_key >= 1) {
  header('HTTP/1.0 404 Not Found', true, 404);
  exit();
}

    <input type="text" id="test" value="test">
    <div class='btn' id="btn1">Senden</div>

I can bind in the HTML Structure, but when i click the button, nothing happens. No Network activity or error code.

Is there a restriction, if i click the button? So how can the button call the AJAX Event, when it's clicked?

Marcel
  • 381
  • 1
  • 5
  • 19
  • Your button doesn't exist when you bind events, so it doesn't get any. See the duplicate answer. – ceejayoz Mar 09 '17 at 21:55
  • 2
    `$('body').on('click', '#btn1', function () {` will probably fix your issue but it might not be the most efficient solution. Also, change `type: "POST",` into `type: "GET",` because that is what your PHP is listening for. Also, your PDO is open to SQL injection because you are not parameterizing your query. – MonkeyZeus Mar 09 '17 at 21:56
  • 1
    $("#hb_api").load("http://api.site.de/src/controller.js"); change this to $.getScript("http://api.site.de/src/controller.js"); Just so that I elaborate a little bit. The load method is used to load data from server, like your html markup. But this can't load and execute js file. So you need to use $.getScript instead to load the js file – Mujnoi Gyula Tamas Mar 09 '17 at 23:19

0 Answers0