0

I need to send data through AJAX to another domain. I use the following code which alerts error.

$(document).ready(function(){
                $('p').click(function(){    
            $.ajax({
             url:"http://tarjom.ir/demo/javascript/get.php?callback=?",
             dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
             type :  "GET",
             data: "username=mostafa&url="+window.location,
             success:function(json){
                 // do stuff with json (in this case an array)
                 alert(json);
             },
             error:function(){
                 alert("Error");
             },
            }); 
                });
    });

I want each click on <p> tag be reported to a file called get.php on another server. This file would save the click record+the time of the event into a DB.

Due to development stage, I have added an alert(); to the code, to alert whatever received from get.php, but I ONLY get alerted 'error'.

Here is the get.php code:

<?php
    if($_POST['username'] != "")
    {
        $site = new mysqli('localhost', 'tarjomir_mostafa', 'securefiction1916', 'demo');
        $stmt = $site->prepare("INSERT INTO demo (url) VALUES(?)");
        $stmt->bind_param('s', $a);
        $stmt->execute();
        $stmt->close();
        echo json_encode("success");
    }
?>
BenMorel
  • 34,448
  • 50
  • 182
  • 322

1 Answers1

-1

try this:

$(function(){

  $.ajax({
     url:"http://tarjom.ir/demo/javascript/get.php",
     dataType: 'jsonp',
     type :  "GET",
     data: "username=mostafa&url="+window.location,
     jsonpCallback:"myFunction"
  })
  .done(function(json){
         // do stuff with json (in this case an array)
         alert('done ' + json);
     })
  .fail(function(){
         alert("Error");
     });

});

And the response for http://tarjom.ir/demo/javascript/get.php be something like:

myFunction({"data": "mydata" })
andres descalzo
  • 14,887
  • 13
  • 64
  • 115