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");
    }
?>
6
  • stackoverflow.com/questions/5648590/…
    – Alvaro
    Sep 19, 2013 at 15:49
  • error: function(a,b,c){ alert(c) }
    – Kevin B
    Sep 19, 2013 at 15:49
  • 1
    The URL you provide doesn't appear to be returning JSONP … or anything.
    – Quentin
    Sep 19, 2013 at 15:59
  • I have changed the URL
    – user2746959
    Sep 19, 2013 at 16:07
  • You're returning JSON, not JSONP. modify your php to instead return JSONP.
    – Kevin B
    Sep 19, 2013 at 16:14

1 Answer 1

-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" })
1
  • @MostafaTalebi -1??? Does your service returns or not what I comment that returned? Sep 19, 2013 at 18:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.