0

UPDATED AND SOLVED

Thanks to @Christofer Eliasson for the hint. Adding:

header("access-control-allow-origin: *");

to my PHP file solved the issue. Perhaps not the most beautiful way of dealing with the problem but this works.

To make it a bit better/safer:

$http_origin = $_SERVER['HTTP_ORIGIN'];

if ($http_origin == "http://domain1.com")
{  
    header('Access-Control-Allow-Origin: *');
}

Here is another cross-domain related question.

I have a simple HTML form on domain1.com where a user can add his/her email to a mailing list, here a simple json file, "mails.json", hosted on a second domain (domain2.com).

When the user submits his/her email, a JS script is called whose aim is to check the email and to send the data of the form (here the user's email) to the mails.json file hosted on domain2.com via ajax GET and JSONP.

Ajax calls a PHP script hosted on domain2.com that should get the user's email and write it to mails.json. Moreover, it should send back to domain1.com some messages regarding the success or errors, given that the user has already entered his email before.

Currently, the email is sent and saved to mails.json but I cannot manage to get my PHP script to send back messages to domain1 regarding its execution. Thanks for your advices and feel free to check and modify the code below.

The HTML form hosted on domain1.com

<div id="mail">
<form method="post" action="http://domain2.com/script.php" class="notifyme">
    <input type="email" value="" name="email" class="email" id="email" placeholder="Type your email here" required>
    <input type="submit" value="Get notified &raquo;" id="submit" name="submit">
    <div class="clear"></div>
</form>

<div class="errmail hide"><span class="uremail"></span> is not a valid email address. Try again :)</div>
<div class="error hide">Ouch :( <span class="uremail"></span> is already registered.</div>
<div class="success hide">Thank You :) <span class="uremail"></span> will be notified once we're ready.</div>

</div>

The Javascript file hosted on domain1.com

//jQuery Initialization
$(function(){

// Form
$('#submit').click(function () { //onSubmit

$('.error,.errmail,.success').hide();       
    var email = $('input[name=email]').val();

    //Email validation      

    var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);

    var valid = pattern.test(email);
    if (!valid && email !== 'undefined') {  
            $('.errmail').removeClass('hide').show('fast');

            if (!email){$('.uremail').append('This');}
            else{$('.uremail').append(email);}
            return false;
   } else {

        //start Ajax
        $.ajax({

            url: "http://domain2.com/script.php?json_callback=?",
            dataType: "jsonp text",       
            //GET method is used
            type: "GET",

            //pass the data         
            data: 'email=' + email,   

            //Do not cache the page
            cache: false,

            //Cross Domain
            crossDomain: true,

            //success
            success: function (html) {    

                //if list.php returned 1/true (send mail success)
               if (html==1) {                  
                $('.success').removeClass('hide').show('fast');$('.uremail').append(email);              

                } 
                else if (html == 0){
                $('.error').removeClass('hide').show('fast');$('.uremail').append(email); 
                }

                else { alert('Sorry, unexpected error. Please try again later.');  }           
            } 


        });
        }

        //cancel the submit button default behaviours
        return false;
    }); 
});

UPDATED

The PHP "script.php" file hosted on domain2.com

header('content-type: application/json; charset=utf-8');
$http_origin = $_SERVER['HTTP_ORIGIN'];

if ($http_origin == "http://domain1.com")
{  
    header('Access-Control-Allow-Origin: *');
}

$logname    = 'mails.json';
$logcontents = file_get_contents($logname);

//Retrieve form data.
$email = ($_GET['email']) ?$_GET['email'] : $_POST['email'];

//flag to indicate which method it uses. If POST set it to 1
if ($_POST) $post=1;


    if(strpos($logcontents,$email) !== false) {
    if ($_POST) {die('You are already subscribed.');}
    else{ $result = 0;echo $result; }
    } 

    else {
        $filecontents = $email.',';
        $fileopen = fopen($logname,'a+');
        $filewrite = fwrite($fileopen, json_encode($filecontents) );
        $fileclose = fclose($fileopen);
                if(!$fileopen or !$filewrite or !$fileclose) {
                    if ($_POST) {die('Error occured');}
                    else{ $result = 0;echo $result; }
                    } 
                else {
                    if ($_POST) {echo 'Your email has been added.';}
                    else{ $result = 1;echo $result; }
                    }

    }

2 Answers 2

1

As you set the proper content-type header at the beginning of your script, you can return the data with a regular echo. You will just have to prepare the data to match the JSONP-format first. Something like this:

<? 
    // Some data to return
    $data = array(1, 2, 3, 4, 5, 6, 7, 8, 9);
    // JSONP response
    echo $_GET['callback'] . '('.json_encode($data).')';
?>

// For this example, the response would be something like this:
// jsonp1277656587731([1,2,3,4,5,6,7,8,9])

When you do a JSONP ajax-request with jQuery, jQuery will automatically send a callback GET-variable for you to use on the server-side. As seen in the example.

Some additional reading: http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the hint and the link. I solved the problem by adding this header to the PHP script: header("access-control-allow-origin: *");
@Chritofer, I'm new on Stackoverflow and I do not have enough reputation to upvote your answer... But many thanks again, you saved me some precious time!
@flo No worries, just glad to be at help!
0

I faced a similar problem in the past and I did try to tinker around with cross domain settings on webserver(Apache2) but no luck. By hit and try I eliminated the hostname from the 'url' parameter of my ajax call and it worked for me. I still did not understand completely though.

Can you quickly check url parameter from :

 http://domain2.com/script.php?json_callback=?

to just:

 script.php?json_callback=?.

There may be additional web server configuration settings ..but just wanted to see if that worked....

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.