pass PHP variable from form handling generated json to javascript ajax -
i'm learning php , javascript. have little extraction project reading json url. form serves building url user inputting keyword.
i want output json parsed specific fields when works , simple message when there no results.
but can't pass sending json php object html javascript variable use (json.parse(myjsvar))
ajax stuck. code above doesn't seem respond using $.post ('button").click, neither when tried give id , call id. perhaps following should in php , have include or require existing php page above :
$newsearch= new progsearch(); $found= json_encode($newsearch->search($search_string)); echo $found; // json expected
so if correct use shorter 1 in ajax call json output.
i tried tutorial using ajax nothing got return here's original+edited code process form data url , parse retrieve json response in php.
extract.php
<?php class progsearch { public $search_string; public function __construct() { if(isset($_post["searchstring"])) { $this->search_string= $_post["searchstring"]; } } static function curl_helper($url){ // returns json $curl = curl_init(); curl_setopt($curl, curlopt_returntransfer, true); curl_setopt($curl, curlopt_url, $url); curl_setopt($curl, curlopt_httpget, true); curl_setopt($curl, curlopt_httpheader, array( 'content-type: application/json', 'accept: application/json')); $json = curl_exec($curl); curl_close($curl); return $json; } public function search($url){ $string= $this->search_string; $url= "http://www.bbc.co.uk/radio/programmes/a-z/by/".$string."/current.json"; $json= self::curl_helper($url); $results=json_decode($json, true); return $results; } } // run class! $newsearch= new progsearch(); $found= json_encode($newsearch->search($search_string)); echo $found; // json expected ?>
index.html
<html> <head> <title>prog extractor</title> <script type="text/javascript" src="js/jquery-1.9.0.min.js"></script> <meta http-equiv="content-type" content="text/html; charset=utf-8"> </head> <body> <div class="search_box"> <form action="extract.php" method="post"> search: <input type="text" name="searchstring" /><br> amongst programmes on bbc radio. <button type="submit" name="submit" value="search"> </form> </div> <div id="results"> // placeholder </div> <script type="text/javascript" src="ajaxfunction.js"></script>
ajaxfunction.js
$("button").click(function(){ var search= $('#search').val(); $.post('extract.php', { search: search }, function(data){ success:function(data){ $.('#results').html(data); }, error:function(){ $.('#results').html("sorry it's failure"); } }); });
Comments
Post a Comment