Cross Domain Writing to a JSON File via Ajax/JSONP calling an external PHP file -
updated , solved
thanks @christofer eliasson hint. adding:
header("access-control-allow-origin: *");
to php file solved issue. perhaps not beautiful way of dealing problem works.
to make bit better/safer:
$http_origin = $_server['http_origin']; if ($http_origin == "http://domain1.com") { header('access-control-allow-origin: *'); }
here cross-domain related question.
i have simple html form on domain1.com user can add his/her email mailing list, here simple json file, "mails.json", hosted on second domain (domain2.com).
when user submits his/her email, js script called aim check email , send data of form (here user's email) mails.json file hosted on domain2.com via ajax , jsonp.
ajax calls php script hosted on domain2.com should user's email , write mails.json. moreover, should send domain1.com messages regarding success or errors, given user has entered email before.
currently, email sent , saved mails.json cannot manage php script send messages domain1 regarding execution. advices , feel free check , modify 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 email here" required> <input type="submit" value="get notified »" id="submit" name="submit"> <div class="clear"></div> </form> <div class="errmail hide"><span class="uremail"></span> not valid email address. try again :)</div> <div class="error hide">ouch :( <span class="uremail"></span> registered.</div> <div class="success hide">thank :) <span class="uremail"></span> 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 used type: "get", //pass data data: 'email=' + email, //do not cache 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 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 indicate method uses. if post set 1 if ($_post) $post=1; if(strpos($logcontents,$email) !== false) { if ($_post) {die('you 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; } } }
as set proper content-type header @ beginning of script, can return data regular echo
. have prepare data match jsonp-format first. this:
<? // data return $data = array(1, 2, 3, 4, 5, 6, 7, 8, 9); // jsonp response echo $_get['callback'] . '('.json_encode($data).')'; ?> // example, response this: // jsonp1277656587731([1,2,3,4,5,6,7,8,9])
when jsonp ajax-request jquery, jquery automatically send callback get-variable use on server-side. seen in example.
some additional reading: http://www.geekality.net/2010/06/27/php-how-to-easily-provide-json-and-jsonp/
Comments
Post a Comment