Jump to content

Search the Community

Showing results for tags 'json'.

  • Search By Tags

    Type tags separated by commas.
  • Search By Author

Content Type


Forums

  • Welcome to PHP Freaks
    • Announcements
    • Introductions
  • PHP Coding
    • PHP Coding Help
    • Regex Help
    • Third Party Scripts
    • FAQ/Code Snippet Repository
  • SQL / Database
    • MySQL Help
    • PostgreSQL
    • Microsoft SQL - MSSQL
    • Other RDBMS and SQL dialects
  • Client Side
    • HTML Help
    • CSS Help
    • Javascript Help
    • Other
  • Applications and Frameworks
    • Applications
    • Frameworks
    • Other Libraries
  • Web Server Administration
    • PHP Installation and Configuration
    • Linux
    • Apache HTTP Server
    • Microsoft IIS
    • Other Web Server Software
  • Other
    • Application Design
    • Other Programming Languages
    • Editor Help (PhpStorm, VS Code, etc)
    • Website Critique
    • Beta Test Your Stuff!
  • Freelance, Contracts, Employment, etc.
    • Services Offered
    • Job Offerings
  • General Discussion
    • PHPFreaks.com Website Feedback
    • Miscellaneous

Find results in...

Find results that contain...


Date Created

  • Start

    End


Last Updated

  • Start

    End


Filter by number of...

Joined

  • Start

    End


Group


AIM


MSN


Website URL


ICQ


Yahoo


Jabber


Skype


Location


Interests


Age


Donation Link

  1. Evening everyone and Merry X-Mas (Happy Holidays) or whatever fits you best.... I have been trying over and over for about 12 hours to figure out how to get data from a specific JSON response and assign the specific values to a new array key/value pair. The various ways I have tried to figure this out are numerous so i'm going to avoid the runnig list of "I trieid this...and this...and this... etc etc." just understand I have reached a dead end point where I need help badly. Here is what our end goal is: "The company" is a "service industry" provider (plumbing, electrical etc. etc.) who wants to dispatch its technicians to new jobs based on which technician has the shortest travel time from any existing address where they already have a scheduled appointment that day and has available time in there schedule. Thus the dispatching system when a new service call is entered is going to give "recommended" technicians (up to 4) to be assigned the new service call based on the above mentioned criteria. (Efficient routing to save company gas cost) 1.) We have a "New service" street address assigned to the $to variable: $to = "4813 River Basin Dr S, Jacksonville FL 32207"; 2.) We will have "records" array which containes a series of records, each record consists of a ticket# a technician id# and a street address: $records = array( array("DV1012","30453423","9890 Hutchinson Park Dr Jacksonville, FL 32225"), array("DB3434","30404041","821 Orange Ave Crescent City, FL 32112"), array("DB3434","30605060","1972 Wells Road, Orange Park FL 32073"), array("DB4578","30605060","2 Independent Drive, Jacksonville FL 32202"), array("DB7841","30605060","5000 Norwood Avenue, Jacksonville FL 32208"), array("DB3235","30605060","9501 Arlington Expressway, Jacksonville FL 32225"), array("DB7894","30605060","Massey Avenue, Jacksonville, FL 32227"), array("DB2020","30121212","11200 Central Pkwy Jacksonville, FL 32224") ); 3.) We are going to prepare the records array for submission to Google's Distance Matrix API by URL encoding each array value into a single variable and then submit it: foreach ($records as $key => $value) {$from = $from.urlencode($value[2])."|";} $to = urlencode($to); $data = file_get_contents("//maps.googleapis.com/maps/api/distancematrix/json?origins=$from&destinations=$to&language=en-EN&units=imperial&mode=driving&sensor=false"); $res=json_decode($data) or die("Error: Cannot read object"); You may look at the ACTUAL live Google response from this here: http://tiny.cc/i6eerx (We have applied <pre> and var_dump($res) to the output) We are looking to get the following information back: The distance and travel time between the "New Service" address ($to) and each of the address' in the $records array ($from), now once that information is returned from Google (JSON response) we need to parse the response and narrow it down to 4 or less (Based on the 4 lowest drive times) to form a new array which ends like this: $results = array( array("DV1012","30453423","2.3 Miles","8 mins"), array("DB3434","30404041","2.8 Miles","9 mins"), array("DB3434","30605060","4.6 Miles","13.8 mins"), array("DB4578","30605060","5.7 Miles","15.2 min") ); OUR PROBLEM: Everything up until the the Google API response is fine, but iterating over the multidimensional arrays within multidimensional arrays of the JSON response is just not coming together in my head (or 2 dozen code attempts). I am able to ECHO an individual value like ( echo $res->rows[0]->elements[0]->distance->text; ) but this has no value for the end result i need to get to. My last thoughts and efforts was that that I was going to have to embed foreach statements within foreach statements to drill down through the various arrays but that hasn't worked very well and it seems like it shouldn't be how it has to be done. I would appreciate any help in showing me how the iteration code should be written and any explanation about the code so i can wrap my head around it.
  2. Hello I am having an issue with encoding an array to JSON, my array seems to be formed correctly but when I try and echo the json_encode version I get "null". I echo the JSON error code and it is "0" indicating no issue.. I have read that non UTF-8 characters can be an issue, but this is simple data, no strange characters... but I added the utf8_encode anyway.... Here is my code: $dataArray = array( 'title' => 'Test Item', 'icon_url' => 'http://url/api/testimage.jpg', 'item_id' => '12345', 'expiration' => 600 ); utf8_encode($dataArray); $responsArray = array( 'success' => '1', 'data' => $dataArray ); utf8_encode($responsArray); header('Content-type: application/json'); echo print_r($responsArray); echo json_encode ($responseArray); echo json_last_error(); Any thoughts would be appreciated
  3. Can anyone help by shedding some light with a little problem I encounter using JSON endpoint requests. I'm not very good with PHP. When the endpoint is called and finds no data, I want to replace it with a local image source. In this case, I am calling brewery->logo_url. Most entries have endpoints, but some don't. When an image link is found at the endpoint, it throws off my layout. You can see the ones that look off. They align to the left. I want to replace with a logo default image each time this happens, with hopes to set the layout adjust back to normal. Here's my working document http://graintoglass.com/fb/tap-menu-test.php and here's the JSON. http://mcallen.taphunter.com/widgets/locationWidget?location=Grain-To-Glass&format=jsonv2short Code Effort <?php $url = 'http://mcallen.taphunter.com/widgets/locationWidget?location=Grain-To-Glass&format=jsonv2short&servingtype=bottlecan'; $curl_session = curl_init($url); curl_setopt($curl_session, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl_session, CURLOPT_CONNECTTIMEOUT, 4); curl_setopt($curl_session, CURLOPT_TIMEOUT, 10); $data = curl_exec($curl_session); curl_close($curl_session); $beer_list = json_decode($data); echo '<p class="last-updated">Last Updated: ' . date("m/d/Y") . '</p>'; echo '<h1 class="page-title">Bottle List</h1>'; echo '<p class="page-intro">Not only do we serve a hefty list of brews on tap, we also offer an exclusive list of beers in bottle. Our bottle list is constantly changing so the occasional return visits to browse this list is the best way to stay up to date. Take a look!</p>'; foreach ($beer_list as $beer) { echo '<article class="beer-entry"> <div class="beer-image"><img src="'.$beer->brewery->logo_url.'" /></div> <div class="beer-info"> <p class="brewery-name">'.$beer->brewery->name.' — '.$beer->brewery->origin.'</p> <h2 class="beer-name">'.$beer->beer->name.'</h2> <p class="beer-style">Beer Style: '.$beer->beer->style.'</p> <p class="beer-description">'.$beer->descriptions->short_description.'</p> <p class="beer-abv">ABV: '.$beer->beer->abv.' / IBU: '.$beer->beer->ibu.'</p> <p class="beer-ibu"></p> </div> <div class="clearfix"></div> </article> '; } echo '<p class="page-bottom">If you would like to see more of our food and beer options, <a href="https://www.graintoglass.com" target="_blank">visit our website</a>.</p>'; ?>
  4. I was pointed in this direction by a friend so firstly, hello I'm having some teething problems (basically can't get my head around it) and wondered if anyone would be able to have a look at a script for me (beer money may be provided) I'm currently using a php script which grabs information from a API with curl (JSON format). I'm limited to a number of requests an hour so my plan was to read the file, insert the data into a mysql table so that I could re-read over and over again with no limitations. Then use a script to run every few hours to grab the data. The script I created works however it's a bit buggy with regards to what it does if information is already in the table. If there isn't a previous entry then it inserts everything fine. The JSON data is a multi depth array, and deals with images as well as data so for me, it's rather complex. What I want the script to do is this. Each item is a property (letting agent website) Check to see if the property exists in the database and the JSON. If there is no record in the database, then insert in. If there is a record in the database, update that record. If there is a property in the database which isn't in the JSON file, then delete it from the database. This is basically the same plan for each sub array (pictures, floorplans, etc) however the images are copied from the url given (hosted on amazon) to my own host in order to speed up loading times, etc. i've added a copy of the code but obviously its going to be stupidly hard to understand. Is there any way this could be split into different functions to try and sort it out? haha <?php $ch = curl_init(); /* Section 1 */ curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_URL, 'URL'); //prepare the field values being posted to the service $data = array("appkey" => "KEY","account" => "ACCOUNT" ); curl_setopt($ch, CURLOPT_POSTFIELDS, $data); //make the request $result = curl_exec($ch); $properties = json_decode($result, true); $properties = $properties['properties']; //pr($parsed_json); foreach($properties as $key => $value) { /* Set the vars */ $microTime = microtime(); $time = time(); $cat_id = $value['category_id']; $price = $value['price']; if ($value['category_id'] == "1") { $price_after = $value['qualifier_name']; } else { $price_after = $value['freq_name']; } $full_address = $value['full_address']; $address_1 = $value['address_1']; $address_2 = $value['address_2']; $address_3 = $value['address_3']; $address_4 = $value['address_4']; $address_5 = $value['address_5']; $bedrooms = $value['bedrooms']; $bathrooms = $value['bathrooms']; $summary = $value['summary']; $description = $value['description']; $type_name = $value['type_name']; $status = $value['status']; $feature_1 = $value['feature_1']; $feature_2 = $value['feature_2']; $feature_3 = $value['feature_3']; $feature_4 = $value['feature_4']; $lat = $value['lat']; $long = $value['lng']; /* Delete the properties from the database which can't be found in the file */ $searchProp = "SELECT property_id FROM props WHERE property_address_full = '$full_address' AND property_catid = '$cat_id'"; if ($result = mysqli_query ($linkq, $searchProp)) { if (!$whereStatement) { $whereStatement = "WHERE property_id != $row[property_id]"; } else { $whereStatement .= " OR property_id != $row[property_id]"; } // Set the whereStatement for deleting properties with no ID $deleteProp = "DELETE FROM props $whereStatement"; if ($result = mysqli_query ($linkq, $deleteProp)) { $totalPropsDeleted++; echo "Properties deleted $deleteProp"; $deleteimg = "DELETE FROM props_images $whereStatement"; if ($result = mysqli_query ($linkq, $deleteimg)) { echo ("Images Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deleteepc = "DELETE FROM props_epcs $whereStatement"; if ($result = mysqli_query ($linkq, $deleteepc)) { echo ("EPCs Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deletepdf = "DELETE FROM props_pdf $whereStatement"; if ($result = mysqli_query ($linkq, $deletepdf)) { echo ("PDFs Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } $deletefloorplan = "DELETE FROM props_floorplans $whereStatement"; if ($result = mysqli_query ($linkq, $deletefloorplan)) { echo ("Floorplans Deleted Successfully<br />\n"); } else { echo ("Error Deleting"); } } else { echo "Nothing to delete"; } } echo "<br />"; /* Check to see if the property exists currently */ $existCheck = "SELECT * FROM props WHERE property_address_full LIKE '%$full_address%' AND property_catid = '$cat_id'"; if ($result = mysqli_query ($linkq, $existCheck)) { $row_cnt = mysqli_num_rows($result); if ($row_cnt) { while ($row = $result->fetch_array(MYSQLI_ASSOC)) { echo "Property Exists - $full_address"; if (($row[property_price] != $price) || ($row[property_summary] != $summary) || ($row[property_description] != $description)) { $dateUpdated = "property_updated = $microTime,"; } else { $dateUpdated = "property_updated = property_updated,"; } /* Property exists so update the property info */ $updateProp = "UPDATE props SET property_advertised = property_advertised, $dateUpdated property_catid = '$cat_id', property_price = '$price', property_price_after = '$price_after', property_address_full = '$full_address', property_address_1 = '$address_1', property_address_2 = '$address_2', property_address_3 = '$address_3', property_address_4 = '$address_4', property_address_5 = '$address_5', property_bedrooms = '$bedrooms', property_bathrooms = '$bathrooms', property_summary = '$summary', property_description = '$description', property_type = '$type_name', property_status = '$status', property_feature_1 = '$feature_1', property_feature_2 = '$feature_2', property_feature_3 = '$feature_3', property_feature_4 = '$feature_4', property_lat = '$lat', property_long = '$long' WHERE property_id = '$row[property_id]'"; if (mysqli_query ($linkq, $updateProp)) { $totalPropsUpdated++; echo (" & Updated"); } else { echo (" & Error Updating"); } echo ("<br />\n"); /* Delete all the photos for this property as it doesn't matter if they are added again */ $deletePhotos = mysqli_query ($linkq, "DELETE FROM props_images WHERE property_id = $row[property_id] OR property_id = ''"); printf("Images Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current images and add back to the database and asign the property id */ $primaryimg = 0; $totalimg = count($value['images']); for ($x = 0; $x < $totalimg; $x++) { $imagename = $value['images'][$x]; if (!$primaryimg) { $image_main = "1"; } else { $image_main = "0"; } $insertphoto = "INSERT into props_images VALUES ('', '$row[property_id]', '$imagename', '$image_main', '')"; if (mysqli_query ($linkq, $insertphoto)) { echo ("- Inserted ($row[property_id]) ($imagename) ($image_main)\n"); if (!file_exists('images/props/'. $imagename .'.jpg')) { /* Try and copy the image from the url */ $file = 'https://utili-media.s3-external-3.amazonaws.com/stevemorris/images/' . $imagename . '_1024x1024.jpg'; $newfile = 'images/props/' . $imagename . '.jpg'; if (!copy($file, $newfile)) { echo "- Failed to Copy\n"; } else { echo "- Image Copied"; /* Resize the image and create a thumb nail */ $image = new SimpleImage(); $image->load('images/props/' . $imagename . '.jpg'); $image->resizeToWidth(240); $image->save('images/props/thumb/' . $imagename . '.jpg'); } } else { echo ("- Nothing to upload, image exists"); } echo "<br />\n"; } else { echo ("- Image Insert Error\n"); } $primaryimg++; } /* close the image loop */ /* Delete all the epcs for this property as it doesn't matter if they are added again */ $deleteEpcs = mysqli_query ($linkq, "DELETE FROM props_epcs WHERE property_id = $row[property_id]"); printf("EPCs Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current EPCs and insert into the database */ $totalepc = count($value['epcs']); for ($y = 0; $y < $totalepc; $y++) { $epcname = $value['epcs'][$y]; $insertepc = "INSERT into props_epcs VALUES ('', '$new_property_id', '$epcname')"; if (mysqli_query ($linkq, $insertepc)) { echo ("- Inserted EPC ($new_property_id) ($epcname)<br />\n"); } else { echo ("- EPC Insert Error\n"); } } /* close the epc loop */ /* Delete all the pdfs for this property as it doesn't matter if they are added again */ $deletePdfs = mysqli_query ($linkq, "DELETE FROM props_pdf WHERE property_id = $row[property_id]"); printf("PDFs Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current PDFs and insert into the database */ $totalpdf = count($value['pdfs']); for ($v = 0; $v < $totalpdf; $v++) { $pdfname = $value['epcs'][$v]; $insertpdf = "INSERT into props_pdf VALUES ('', '$new_property_id', '$pdfname')"; if (mysqli_query ($linkq, $insertpdf)) { echo ("- Inserted PDF ($new_property_id) ($pdfname)<br />\n"); } else { echo ("- PDF Insert Error\n"); } } /* close the PDF loop */ /* Delete all the pdfs for this property as it doesn't matter if they are added again */ $deleteFloorplan = mysqli_query ($linkq, "DELETE FROM props_floorplans WHERE property_id = $row[property_id]"); printf("Floorplans Deleted: %d\n", mysqli_affected_rows($linkq)); printf("<br />\n"); /* Loop the current Floorplans and insert into the database */ $totalfloorplan = count($value['floorplans']); for ($v = 0; $v < $totalfloorplan; $v++) { $floorplanname = $value['floorplans'][$v]; $insertfloorplan = "INSERT into props_floorplans VALUES ('', '$new_property_id', '$floorplanname')"; if (mysqli_query ($linkq, $insertfloorplan)) { echo ("- Inserted Floorplan ($new_property_id) ($floorplanname)<br />\n"); } else { echo ("- Floorplan Insert Error\n"); } } /* close the Floorplan loop */ } /* close the property while loop */ } else { /* close the if row exists loop */ /* Insert the property as it doesn't exist in the database */ $insert = "INSERT INTO props VALUES ('', '$time', '', '$cat_id', '$price', '$price_after', '$full_address', '$address_1', '$address_2', '$address_3', '$address_4', '$address_5', '$bedrooms', '$bathrooms', '$summary', '$description', '$type_name', '$status', '$feature_1', '$feature_2', '$feature_3', '$feature_4', '$lat', '$long', '', '')"; if (mysqli_query ($linkq, $insert)) { $totalPropsAdded++; echo ("Property Inserted - $value[full_address]<br />"); /* get the property ID from the newly added property */ $getPropID = mysqli_query ($linkq, "SELECT property_id FROM props ORDER BY property_id DESC LIMIT 1"); while ($rowNew = $getPropID->fetch_array(MYSQLI_ASSOC)) { $new_property_id = $rowNew[property_id]; } /* Loop the current images and add to the database and asign the property id */ $primaryimg = 0; $totalimg = count($value['images']); for ($x = 0; $x < $totalimg; $x++) { $imagename = $value['images'][$x]; if (!$primaryimg) { $image_main = "1"; } else { $image_main = "0"; } $insertphoto = "INSERT into props_images VALUES ('', '$new_property_id', '$imagename', '$image_main', '')"; if (mysqli_query ($linkq, $insertphoto)) { echo ("- Inserted Image ($new_property_id) ($imagename) ($image_main)<br />\n"); } else { echo ("- Image Insert Error\n"); } $primaryimg++; } /* close the images loop */ /* Loop the current epcsand add to the database and asign the property id */ $totalepc = count($value['epcs']); for ($y = 0; $y < $totalepc; $y++) { $epcname = $value['epcs'][$y]; $insertepc = "INSERT into props_epcs VALUES ('', '$new_property_id', '$epcname')"; if (mysqli_query ($linkq, $insertepc)) { echo ("- Inserted EPC ($new_property_id) ($epcname)<br />\n"); } else { echo ("- EPC Insert Error\n"); } } /* close the epcs loop */ /* Loop the current pdfs and add to the database and asign the property id */ $totalpdf = count($value['pdfs']); for ($v = 0; $v < $totalpdf; $v++) { $pdfname = $value['epcs'][$v]; $insertpdf = "INSERT into props_pdf VALUES ('', '$new_property_id', '$pdfname')"; if (mysqli_query ($linkq, $insertpdf)) { echo ("- Inserted PDF ($new_property_id) ($pdfname)<br />\n"); } else { echo ("- PDF Insert Error\n"); } } /* close the pdfs loop */ /* Loop the current floorplans and add to the database and asign the property id */ $totalfloorplan = count($value['floorplans']); for ($v = 0; $v < $totalfloorplan; $v++) { $floorplanname = $value['floorplans'][$v]; $insertfloorplan = "INSERT into props_floorplans VALUES ('', '$new_property_id', '$floorplanname')"; if (mysqli_query ($linkq, $insertfloorplan)) { echo ("- Inserted Floorplan ($new_property_id) ($floorplanname)<br />\n"); } else { echo ("- Floorplan Insert Error\n"); } } /* close the floorplans loop */ } else { echo ("Insert Error"); } /* close the insert property */ } /* close the row count loop */ } /* close the property exists loop */ } /* close everything */ curl_close($ch); mysqli_close ($linkq); ?>
  5. Good afternoon, I am working on a project that gives the user a data table and a google chart (using the api) based on what the user selects for a <select> <option>. Index.PHP code: <form> <select name="users" onchange="showUser(this.value);drawChart();"> <option value=""> Select a Metal: </option> <?php //connection details $query = "SELECT TOP(31) tblMetalPrice.MetalSourceID, tblMetalSource.MetalSourceName from tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID=tblMetalSource.MetalSourceID ORDER BY tblMetalPrice.DateCreated DESC "; $result = sqlsrv_query( $conn, $query); while( $row = sqlsrv_fetch_object ($result)) { echo "<option value='".$row->MetalSourceID ."'>". $row->MetalSourceName ."</option>"; } sqlsrv_close( $conn); ?> </select> </form> <div id="chart_div"></div> <div id="txtHint"><b>Past metal information will be generated below.</b></div> this works fine and generates the list in the select option dropdown Script to get table contents: <script> function showUser(str) { if (str=="") { document.getElementById("txtHint").innerHTML=""; return; } if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else { // code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.onreadystatechange=function() { if (xmlhttp.readyState==4 && xmlhttp.status==200) { document.getElementById("txtHint").innerHTML=xmlhttp.responseText; } } xmlhttp.open("GET","scripts/gettabledata001.php?q="+str,true); xmlhttp.send(); } </script> this also works fine and generates the table contents based on 'q' value from the select dropdown. Google API script: <script type="text/javascript"> // Load the Visualization API and the piechart,table package. google.load('visualization', '1', {'packages':['corechart']}); google.setOnLoadCallback(drawChart()); function drawChart() { var jsonData = $.ajax({ url: "scripts/getgraphdata.php", dataType:"json", data: "q="+num, async: false }).responseText; // Instantiate and draw our pie chart, passing in some options. var chart = new google.visualization.LineChart(document.getElementById('chart_div')); chart.draw(data, {width: 400, height: 240}); } </script> getgraphdata.php script: $q = intval($_GET['q']); ini_set('display_errors',1); ini_set('display_startup_errors',1); error_reporting(-1); $query ="SELECT TOP(30) tblMetalPrice.MetalSourceID, tblMetalPrice.DateCreated, tblMetalPrice.UnitPrice, tblMetalPrice.HighUnitPrice, tblMetalSource.MetalSourceName FROM tblMetalPrice INNER JOIN tblMetalSource ON tblMetalPrice.MetalSourceID = tblMetalSource.MetalSourceID WHERE tblMetalPrice.MetalSourceID = '".$q."' ORDER BY tblMetalPrice.DateCreated DESC"; $result = sqlsrv_query($conn, $query); echo "{ \"cols\": [ {\"id\":\"\",\"label\":\"Date\",\"pattern\":\"\",\"type\":\"string\"}, {\"id\":\"\",\"label\":\"Unit Price\",\"pattern\":\"\",\"type\":\"number\"} ], \"rows\": [ "; $total_rows = sqlsrv_num_rows($result); $row_num = 0; while($row = sqlsrv_fetch_object($result)){ $row_num++; if ($row_num == $total_rows){ echo "{\"c\":[{\"v\":\"" . $row->DateCreated->format('d-m-Y') ."\",\"f\":null},{\"v\":" . $row->UnitPrice . ",\"f\":null}]}"; } else { echo "{\"c\":[{\"v\":\"" . $row->DateCreated->format('d-m-Y') ."\",\"f\":null},{\"v\":" . $row->UnitPrice . ",\"f\":null}]}, "; } } echo " ] }"; sqlsrv_close( $conn); When ever i try these they don't work the getgraphdata.php scripts runs fine the issue I believe but may be totally wrong may be done to the google api script that should generate the chart but doesn't. Can anyone help here I've been trying to sort this for a few days now and losing confidence in myself rapidly. Thanks Kris
  6. Good morning, I am trying to convert a mssql query into json format so that I can then later pass this through google's visualisation api. The query and encoding seems to be working but the encode returns NULL. I have checked the normal gotcha's of making sure its utf8 encoded and that I have used a version of PHP that has the encode (using php 5.3.19). Can any one help me with getting the encode to work. PHP CODE: <?php //connection and database details (known to be working) if( $conn ) { echo "Connection established.<br><br>"; }else{ echo "Connection could not be established.<br />"; die( print_r( sqlsrv_errors(), true)); } $query = "SELECT * FROM tblProducts"; $result = sqlsrv_query( $conn, $query); while( $row = sqlsrv_fetch_array( $result, SQLSRV_FETCH_NUMERIC) ); $arr = array($result); $encodedarray = array_map(utf8_encode, $arr); echo json_encode($encodedarray); sqlsrv_close( $conn); ?> When I run this code on the server it comes back with: Connection established. [null] Has anyone got any ideas of getting this to work? Thanks Kris
  7. I am using multiple levels of JSON data coming into php from a C# application, as in: return new RootObject() { ID_Project = 4, Name_Project = "Test", Receiver_ID = 4, Receiver_Name = "ABCDE", UserID = 20, UserRole = new User_Role() { ID_User = 20, Role_User = "level 3", User_Role_Description = "U", UserGroup = new List<user_group>() { new User_Group() { ID_UserGroup = 30, Name_UserGroup = "usergroup8", UserID = 20 }, new User_Group() { ID_UserGroup = 31, Name_UserGroup = "usergroup9", UserID = 21 }, new User_Group() { ID_UserGroup = 32, Name_UserGroup = "usergroup10", UserID = 22 } } } }; i am having troubles accessing the second level: UserRole and 3rd level: User_Group in my php script. im currently trying like this: foreach ($phpArray as $key => $value) { echo "<h2>$key</h2>"; foreach ($value as $k => $v) { echo "$k | $v "; foreach ($v as $key1) { echo "$key1 "; } } } does anyone have an idea? :confused: Thanks, Revathy
  8. I'm using the following function/php code to create some JSON for some NVD3 charts I am using. The problem I have is that for each KEY, the $i variable will count even and odd numbers. Here is the data below as you can see in the first line, every x:counts as 0, 2, 4 , 6. and for KEY:IDNB it counts 1,3,5,7. I need them all to count equally so that they are against the same line on my graph. How can I make them count 1,2,3,4 for both "keys" [{"key":"IDNA","values":[{"x":0,"y":387.73},{"x":2,"y":388.57},{"x":4,"y":388.04},{"x":6,"y":387.94},{"x":8,"y":388.24},{"x":10,"y":388.44},{"x":12,"y":387.99},{"x":14,"y":388.53},{"x":16,"y":388.79},{"x":18,"y":388.6},{"x":20,"y":388.55},{"x":22,"y":388.48},{"x":24,"y":388.72},{"x":26,"y":389.02},{"x":28,"y":388.59},{"x":30,"y":388.07},{"x":32,"y":388.14},{"x":34,"y":388.58},{"x":36,"y":388.12},{"x":38,"y":388.76},{"x":40,"y":388.15},{"x":42,"y":388.26},{"x":44,"y":388.09},{"x":46,"y":388.58},{"x":48,"y":386.85},{"x":50,"y":388.23},{"x":52,"y":388.16},{"x":54,"y":388.83},{"x":56,"y":388.79},{"x":58,"y":388.74},{"x":60,"y":388.78},{"x":62,"y":388.54},{"x":64,"y":388.36},{"x":66,"y":388.7},{"x":68,"y":388.54},{"x":70,"y":388.02},{"x":72,"y":388.05},{"x":74,"y":388.31},{"x":76,"y":388.65},{"x":78,"y":388.98},{"x":80,"y":387.78},{"x":82,"y":389.42},{"x":84,"y":388.86},{"x":86,"y":388.66},{"x":88,"y":388.51},{"x":90,"y":388.27},{"x":92,"y":389},{"x":94,"y":387.8},{"x":96,"y":388.18},{"x":98,"y":388.66}]},{"key":"IDNB","values":[{"x":1,"y":387.33},{"x":3,"y":388.5},{"x":5,"y":387.75},{"x":7,"y":387.98},{"x":9,"y":388.57},{"x":11,"y":388.23},{"x":13,"y":387.83},{"x":15,"y":388.31},{"x":17,"y":388.99},{"x":19,"y":388.7},{"x":21,"y":388.49},{"x":23,"y":388.21},{"x":25,"y":388.4},{"x":27,"y":389.05},{"x":29,"y":388.26},{"x":31,"y":387.88},{"x":33,"y":388.2},{"x":35,"y":388.3},{"x":37,"y":388.08},{"x":39,"y":388.29},{"x":41,"y":388.04},{"x":43,"y":387.91},{"x":45,"y":388.23},{"x":47,"y":388.47},{"x":49,"y":386.83},{"x":51,"y":387.55},{"x":53,"y":388.03},{"x":55,"y":388.98},{"x":57,"y":388.7},{"x":59,"y":388.94},{"x":61,"y":388.47},{"x":63,"y":388.5},{"x":65,"y":387.66},{"x":67,"y":388.17},{"x":69,"y":388.29},{"x":71,"y":387.73},{"x":73,"y":388},{"x":75,"y":388.36},{"x":77,"y":388.35},{"x":79,"y":388.75},{"x":81,"y":387.36},{"x":83,"y":389.32},{"x":85,"y":388.74},{"x":87,"y":388.86},{"x":89,"y":388.57},{"x":91,"y":388.21},{"x":93,"y":388.74},{"x":95,"y":387.84},{"x":97,"y":388.18},{"x":99,"y":388.7}]}] Here is the PHP im using to make the data from a query $lrs = CDB::ExecuteQuery($sql); if($lrs) { $jsonData = convert($lrs); } function convert($lrs) { $i = 0; $intermediate = array(); while ($vals = CDB::GetAssoc($lrs)) { $key = $vals['VARIABLE']; $x = $i; $y = $vals['VAR_MEASURE_1']; $intermediate[$key][] = array('x' => $x, 'y' => $y); $i++; } $output = array(); foreach($intermediate as $key => $values) { $output[] = array( "key" => $key, 'values' => $values ); } return json_encode($output, JSON_NUMERIC_CHECK); } can anyone point me in the right direction?
  9. Hi, I'm absolutely stuck with this piece of code, I've searched and searched to get it working and have failed miserably. It also doesn't help that I'm brand new to php My Json output currently looks like this [ { "key": "OWM1", "values": [ [ "x : EW", "y :4" ], [ "x : RSE", "y :3" ], [ "x : SWE", "y :2" ], [ "x : WTE", "y :1" ], [ "x : WWE", "y :1" ] ] }, { "key": "OWM2", "values": [ [ "x : EW", "y :4" ], [ "x : RSE", "y :2" ], [ "x : SWE", "y :1" ], [ "x : WTE", "y :3" ], [ "x : WWE", "y :2" ] ] } ] But I need it to look like this for the sake of NVD3 chart to be able to process it correctly. [ { "key": "OWM1", "values": [ { x : "EW", y : 4 }, { x : "RSE", y : 3 }, { x : "SWE", y : 2 } { x : "WTE", y : 1 } { x : "WWE", y : 21 } ] }, { key: "OWM2", values: [ { x : "EW", y : 4 }, { x : "RSE", y : 2 }, { x : "SWE", y : 1 } { x : "WTE", y : 3 } { x : "WWE", y : 2 } ] }] Here is my PHP code that I am producing the first output of json with. $result = mysqli_query($con,"SELECT CODE, _POS, COUNT(CODE) AS COUNT from defects WHERE FPOS IN ('OWM1','OWM2') GROUP BY POS, CODE"); if($result) { $jsonData = convert($result); } function convert($result) { $intermediate = array(); while($rows = mysqli_fetch_assoc($result)) { $key = $rows['POS']; $x = $rows['CODE']; $y = $rows['']; $intermediate[$key][] = array('x : ' .$x,'y :' . $y); } $output = array(); foreach($intermediate as $key => $values) { $output[] = array( "key" => $key, 'values' => $values ); } echo json_encode($output); } mysqli_close($con); Is there any way anyone could help me manipulate the code I have to look exactly like the second set of JSON code that is compatible with NVD3 charts? Thanks alot.
  10. This is more of a database architect question. I am building a CMS for website development. I am ready to use it for the first time on one of my clients. Now, my issue is is how to set up some or one of my table(s) for some areas that my client wants to be able to change in the admin section. In their website on the front page, I put together this nice block slider. Its 6 blocks with text, a background image and nice effects. At first it was always going to be static, which was no issue at all, but later they came to me and asked if they could be able to change words in the boxes themselves in the admin section.. Of course this can be easily done by creating a table that is associated with this home page block thing and each row in the table will correspond to one of the blocks on the home page. But I believe there might be an easier way to store this type of data without having to create another table for every feature the client wants to edit, for example they also want to be able to edit a slider on another page. The WordPress database then came into my mind and how they store most of their data as JSON. So I was then thinking of creating a table named 'modules' for examples with three columns (id, title, data). Then inside the data column store the editable fields as a JSON string object. For example a row could like like : 1, "Front Page Box Slider", {"slider-home" : [ {"data" : "value", "img_1", "value1"}, {"data" : "value", "img_2", "value2"} ]} I've been doing a bit of research on this and people have just been saying, never do this if you do want your data to be searched through, which I don't. Can anyone tell me why or why not I should do this, or maybe a better solution to my problem? Thank you
  11. I am a noob in api so please bear with me. I tried google searching for 1 hour but I can't understand anything from the results. Currently, I have an API in kimono with the given example data : { "name": "Summoners-Details", "count": 31, "frequency": "On demand", "version": 7, "newdata": false, "lastrunstatus": "success", "thisversionrun": "Tue Sep 02 2014 02:34:07 GMT+0000 (UTC)", "lastsuccess": "Tue Sep 02 2014 02:34:07 GMT+0000 (UTC)", "stats": { "retriedUrls": [], "failedUrls": [], "successful": 1, "rows": 31, "retried": 0, "failed": 0, "duration": 1894 }, "results": { "rank": [ { "division": "Wukong's Lancers Silver-tier II" } ] } } Here is the php code I am trying to use to get the division data, but I am getting nothing! : <?php $request = "https://www.kimonolabs.com/api/c6qj1oc?apikey=xxxxxxxxxxxxxxxxxx"; $response = file_get_contents($request); $results = json_decode($response, TRUE); $division = $results->{'results'}->{'rank'}->{'division'}; echo $division; ?> What am I doing wrong here??
  12. I want to print data from response json? I was debug with firebug and show this : {"umumu":"","levelu":1,"nameu":""} How to echo data array just levelu. But i don't know how to make it? thanks
  13. We are not getting the error message, that should match with the error_code We sending the code and the object contains the error/success message to show!!! This seems to almost works. It is part of Jquery Validations, once the field or submit button is clicked. It looks for error on field. then Enter the Ajax Funciton which is to parse the error code and the out put the error message which is coming from json object. The code is not returning the error message, on line (alert(data)) Produces [object,object] not actual data string. The error message does not return. Please help, is there something work with our ajax request //*new style for error Messages*/ //var jsonErrors = frontEndErrorCodes; //JC wrote. //MG added. To retrieve Front-end error codes as well as //Backend Error Codes function _getErrorMessage(errorCode, message){ var errorData = JSON.stringify({error_code: errorCode, message: message}); var dataString = $.parseJSON(errorData); $.ajax({ url: './retrieveErrorMessage.json', type: 'POST', data: dataString, dataType: "json", contentType: 'application/json', mimeType: 'application/json', success: function(data) { //data = $.parseJSON(data); alert(data); $('.error.message').contents().find('h4').text(data.message); // if(!vanillaeGift.notify.called) { // $('.error.message').contents().find('h4').text(error.text()); // vanillaeGift.notify.showNotification(".error"); // } //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice ==true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(data.message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }, error: function(data) { //data = $.parseJSON(data); alert(data); $('.error.message').contents().find('h4').text(data.message); // if(!vanillaeGift.notify.called) { // $('.error.message').contents().find('h4').text(error.text()); // vanillaeGift.notify.showNotification(".error"); // } //Bolt Notification Called and Enabled here if(BoltNotify == true){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error"); }else if(BoltNotify == true && multipleNotice == true ){ var spanerrorgen = $('.error.message').contents().find('h4').html(data.message); VanillaReload.notify.showNotification(".error").append(spanerrorgen); }else{ var spanerrorgen = $("<span/>").css("color","#D00").hide().addClass("error").html(data.message); $fieldref.parent().append(spanerrorgen) spanerrorgen.show("fast"); } }, fail: function(jqXHR, textStatus) { alert(data); if(textStatus == "parsererror"){ return "We're Sorry a system error occured"; } } }); }
  14. Hi Guys and Girls, I'm having a bit of a hard time getting some pagination working. I have a script using CURL getting JSON results via a HTTP API. This is also used in a Wordpress Installation. The API call has a maximum of 50 records returned but allows pagination. What I can't seem to get right is actually getting this to work. Below is the code that I'm using: <?php //functions relating to wordpress go here: //---------------------------------------- $bg_colors = array('green', 'orange', 'blue', 'yellow', 'red', 'black'); //---------------------------------------- //End functions relating to wordpress // Start PetRescue PHP/API Code //---------------------------------------- // Open CuRL/JSON Stuff $ch = curl_init(); $category=$_GET['category']; $url="http://www.xxx.com.au/api/listings?token=xxxtokenxxx&group_id=xxx&species=".$category; curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Accept: application/json', 'X-some-API-Key: xxxtokenxxx', )); $json = json_decode(curl_exec($ch), true); //Pagination stuffs if($_GET['page']) { $page=substr($_GET['page'],1); echo 'page'.$page; } // Functions relating to the Echo Code foreach($json['listings'] as $listing) { $short_personality=substr($listing['personality'],0,500); $peturl="http://xxx.org.au/pet-info/?petid=".$listing['id']; $medium_photo=$listing['photos'][0]['large_340']; $gallery_first=$listing['photos'][0]['xlarge_900']; $gender_class=strtolower($listing['gender']); $breed_class=strtolower($listing['species']); $name=($listing['name']); $unique_gallery_name="lightbox['.$inc.']"; $inc++; foreach($listing['photos'] as $photosthumb) { $photo_thumb_large=$photosthumb["xlarge_900"]; $photo_thumb_hidden=$photosthumb["xlarge_340"]; } $rand_background = $bg_colors[array_rand($bg_colors)]; // General IF/AND/ELSE Statements to refine the Echo Output if($listing['photos'] == null) { $medium_photo="http://xxx.org.au/wp-content/themes/xxx/images/photo_coming_soon.png"; } if($listing['desexed'] == "Yes") { $desexed="yes"; } else { $desexed="no"; } if($listing['vaccinated'] == "Yes") { $vaccinated="yes"; } else { $vaccinated="no"; } if($listing['wormed'] == "Yes") { $wormed="yes"; } elseif($listing['wormed'] == "No") { $wormed="no"; } else { $wormed="no"; } if($listing['heart_worm_treated'] == "Yes") { $heart_worm_tested="yes"; } elseif($listing['heart_worm_treated'] == "No") { $heart_worm_tested="no"; } else { $heart_worm_tested="no"; } if($listing['species'] == "Dog") { $adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-dogs/?dog_name=$name"; $hwt="list-$heart_worm_tested"; } elseif($listing['species'] == "Cat") { $adoption_enquiry_link="http://xxx.org.au/pre-adoption-form-cats/?cat_name=$name"; $hwt="list-hwt-hidden"; } // Echo the output echo'<div class="animal"> <div class="animal-image"> <a class="size-thumbnail thickbox" rel="'.$unique_gallery_name.'" href="'.$gallery_first.'"> <img src="'.$medium_photo.'" class="image-with-border" alt=""> <div class="border" style="width: 340px; height: 340px;"> <div class="open"></div> </div> </a> <div class="item-title-bg '.$rand_background.'"> <h2 class="entry-title"> '.$listing['name'].'</h2> <div class="animal-adopt-button"> <a href="'.$adoption_enquiry_link.'" style="background-color: #575757; border-color: #494949; background-position:5px 0;" class="button medium"> Enquire about '.$name.'</a> </div> </div> </div> <div class="animal-thumbnail hidden"> <a class="lightbox" rel="'.$unique_gallery_name.'" href="'.$photo_thumb_large.'"> <img class="animal-thumbnail" src="'.$photo_thumb_hidden.'" > </a> </div> <div class="animal-content"> <div class="animal-left"> <ul class="animal-list"> <li class="list-sex-'.$gender_class.'">'.$listing['gender'].'</li> <li class="list-breed-'.$breed_class.'">'.$listing['breeds_display'].'</li> <li class="list-age">'.$listing['age'].'</li> <li class="list-fee">'.$listing['adoption_fee'].'</li> </ul> </div> <div class="animal-right"> <ul class="animal-list"> <li class="list-'.$desexed.'">Desexed?</li> <li class="list-'.$vaccinated.'">Vaccinated?</li> <li class="list-'.$wormed.'">Wormed?</li> <li class="'.$hwt.'">Heart Worm Tested?</li> </ul> </div> <div class="animal-full"> <ul class="animal-list"> <li class="list-description">'.$listing['personality'].'</li> </ul> </div></div> <div class="clearer"></div> </div> <div class="delimiter"></div>'; // Close the CURL } echo' <div class="pagination footer-pagination"> <nav class="pagination"> <div class="pages">'; for($i=1;$i<=$json['total_pages'];$i++) { $this_page=substr($_GET['page'],1); $active=""; if($i==$this_page) { $active="active"; } echo ' <span class="page'. $active.'"> <span class="number"> <a rel="prev" href="http://xxx.org.au/pet/?category=dog&page='.$i.'"> '.$i.'</a> </span> </span> </div> </nav> </div>'; curl_close($ch); } ?> This is a sample of the JSON results: {"listings":[{"adoption_fee":"$200 ","adoption_process":"For cats, please fill out our <a href=\"http://xxx.org.au/pre-adoption-form-cats/\">Pre-Adoption Questionnaire - Cats</a>.\r\n\r\nFor dogs, please fill out our <a href=\"http://xxx.org.au/pre-adoption-form-dogs/\">Pre-Adoption Questionnaire - Dogs</a>.\r\n\r\nFor more information on our Adoption Process, please visit this <a href=\"http://xxx.au/our-adoption-process/\">link</a>.\r\n\r\nPlease make sure that you are familiar with our <a href=\"http://xxx.org.au/adoption-agreement/\">Adoption Agreement</a> as it has recently changed.\r\n\r\nFor more information on any of our animals, please <a href=\"http://xxx.org.au/contact-us/\">Contact Us</a>.","age":"2 years 5 months","breeds":["Domestic Long Hair"],"breeds_display":"Domestic Long Hair","coat":"Long","contact_name":null,"contact_number":null,"contact_preferred_method":"Email","created_at":"30/1/2014 21:36","date_of_birth":"20/2/2012","desexed":true,"foster_needed":false,"gender":"Female","group":"xxx","heart_worm_treated":null,"id":273191,"interstate":false,"last_updated":"5/8/2014 12:20","medical_notes":"","microchip_number":"","mix":false,"multiple_animals":false,"name":"Helena HC13-394","personality":"Stunning Helena!\r\n\r\nThis beautiful girl is looking for a home that is fairly relaxed. She is not happy about sharing her current foster home with some bossy cats, she likes to be the princess of her realm.\r\n\r\nShe is very affectionate, and when it is quiet she will come and have a big smooch around our legs, and purr her pretty little purr. \r\n\r\nShe is somewhat timid to start with, but enjoys the company of people and once she trusts, she's a very special companion.\r\n\r\n","photos":[{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_cb61a_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_7a7a7_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_70x70.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_130x130.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_340x340.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/1/30/273191_8b90b_900x900.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_70x70_96020.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_130x130_96020.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_340x340_96020.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_691df_900x900_96020.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_70x70_d2d41.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_130x130_d2d41.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_340x340_d2d41.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/4/26/273191_6d9da_900x900_d2d41.jpg"},{"small_80":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_70x70_982c6.jpg","medium_130":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_130x130_982c6.jpg","large_340":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_340x340_982c6.jpg","xlarge_900":"http://xxx.com.au/uploads/pet_photos/2014/7/12/273191_f209f_900x900_982c6.jpg"}],"senior":false,"size":null,"species":"Cat","state":"WA","vaccinated":"Yes","wormed":"Yes"}, And the pagination details are at the bottom of the JSON response: "page":"1","per_page":"50","total_pages":"6" The issue I get with all of this, is when calling the PHP file again, it's just returning the first page of results and not the second page. Any help would stop me from eating my own eyeballs, as I've been staring at this for hours! Cheers, Dave
  15. Hi ! I am having a heck of a time sending data back in responseText. First of all, I am not actually sure how my data is being sent back into responseText - it is the result of me using a jquery plugin called iframetransport which seeks to transport file inputs across an iframe for ajax like form submission. Anyway, I am echoing back data from PHP like so echo json_encode(array("rowData"=> '<div class = "row" data-id = "'.$row['id'].'" > <div class = "row"><img src="data:image/jpeg;base64,'.base64_encode( $row['blob'] ).'"/></div> <div class = "container"> <div class = "name"><p>'.$row['name'] .'</p></div> </div> </div>')); I know that this data is valid in normal ajax $.posts because I also have form submission without the iframetransport, and it returns the exact same data with no issue. However, when the above data makes its way into responseText it looks like this on the client side: "{"rowData":"\n\t\t\t\t\t<\/div>\n\t\t\t\t\t\t\n\t\t\t\t\t\t\tasdasd<\/p><\/div>\n\t\t\t\t\t\t\t<\/p><\/div>\n\t\t\t\t\t\t\t<\/p><\/div>\n\t\t\t\t\t\t\t1<\/p><\/div>\n\t\t\t\t\t\t\t<\/p><\/div>\n\t\t\t\t\t\t<\/div>\n\t\t\t\t\t<\/div>"}" All my divs and elements are replaced with \t or they are not making it into the response. Also when I return blobs like this (this is even worse) I get a 414 (Request-URI Too Large) Any help is appreciated. This is the plugin http://cmlenz.github.io/jquery-iframe-transport/ if interested.
  16. Hi, I am having troubles trying to add View/Edit/Del options to my web system modules. I am not the creator of the web system so it's complicated for me, also, I am a newbie on this. I want to be able to view/edit/del from admin panel every product or client stored in my db. Here's the Clients module code: client.html <div ng-include="'views/menu.html'"> </div> <button type="button" class="btn btn-primary" ng-model = 'newProduct' ng-click = 'newProductButton()'>{{buttonName}}</button> <hr> <div class="table-responsive" ng-show ='!newProduct'> <table class="table table-striped table-hover"> <tr> <td>Nº</td> <td>Cédula</td> <td>Nombre</td> <td>Apellido</td> <td>Dirección</td> <td>Email</td> <td>Télefono</td> </tr> <tr ng-repeat= 'client in clients track by $index'> <td>{{$index + 1}}</td> <td>{{client.codigo}}</td> <td>{{client.nombre}}</td> <td>{{client.apellido}}</td> <td>{{client.direccion}}</td> <td>{{client.email}}</td> <td>{{client.telefono}}</td> </tr> </table> </div> <div ng-show = 'newProduct'> <form role="form" ng-submit ="updateClient (id,name,lastName,address,phoneNumber,email)"> <label>Cédula</label> <div class="form-group"> <input class="form-control" placeholder="Cédula" ng-model='id' id="id"> </div> <label>Nombre</label> <div class="form-group"> <input class="form-control" placeholder="Nombre" ng-model='name' id="sname"> </div> <label>Apellido</label> <div class="form-group"> <input class="form-control" placeholder="Apellido" ng-model='lastName' id="lastName"> </div> <label>Dirección</label> <div class="form-group"> <input class="form-control" placeholder="Dirección" ng-model='address' id="address"> </div> <label>Teléfono</label> <div class="form-group"> <input type='tel' class="form-control" placeholder="Teléfono" ng-model='phoneNumber' id="phoneNumber"> </div> <label>Email</label> <div class="form-group"> <input type='email'class="form-control" placeholder="Email" ng-model='email' id="email"> </div> <div class="alert alert-success" id='alertSuccess' style="display:none">Ingresado Satisfactoriamente...</div> <div class="alert alert-danger" id='alertDanger' style="display:none">Ese cliente ya fue agregado</div> <button type="submit" class="btn btn-primary">Agregar Cliente</button> </form> </div> client.js 'use strict'; /** * @ngdoc function * @name belkitaerpApp.controller:ClientCtrl * @description * # ClientCtrl * Controller of the belkitaerpApp */ angular.module('belkitaerpApp') .controller('ClientCtrl', function ($scope,$http) { $scope.newProduct = false; if($scope.newProduct){ $scope.buttonName = 'Ver Tabla'; } else{ $scope.buttonName = 'Ingresar Cliente'; } $http.get('../serverSide/clients.php').success(function(clients){ console.log(clients); $scope.clients = clients.Clients; }) $scope.newProductButton = function(){ $scope.newProduct = !$scope.newProduct; if($scope.newProduct){ $scope.buttonName = 'Ver Tabla'; } else{ $scope.buttonName = 'Ingresar Cliente'; } } $scope.updateClient = function(id,name,lastName,address,phoneNumber,email){ $http.post('../serverSide/updateClient.php',{id:id,name:name,lastName:lastName,address:address,phoneNumber:phoneNumber,email:email}).success(function(data){ console.log(data); $('#alertSuccess').show("slow"); setTimeout(function() { $('#alertSuccess').hide('slow'); }, 3000); }).error(function(data){ console.log(data); $('<div id="alertDanger"></div>').show("slow"); setTimeout(function() { $('<div id="alertDanger"></div>').hide('slow'); }, 3000); }) } }); client.php <?php require_once 'database.php'; $db = new Database(); $clients = $db->queryAll('SELECT clie_id as id,clie_cod as codigo, clie_ape as apellido, clie_nom as nombre, clie_dir as direccion, clie_ema as email, clie_tel as telefono FROM cliente','Clients'); echo json_encode($clients); ?> I have found a php code on the web and I was wondering if it was possible to merge it with my existing one. I tested the code with my db and it's working but I do not know how to merge it with my existing code. Here's the code: <?php if (isset($_POST['submit'])) { include 'db.php'; $clie_cod=$_POST['clie_cod'] ; $clie_ape= $_POST['clie_ape'] ; $clie_nom=$_POST['clie_nom'] ; $clie_dir=$_POST['clie_dir'] ; mysql_query("INSERT INTO `cliente`(Código,Apellido,Nombre,Dirección) VALUES ('$clie_cod','$clie_ape','$clie_nom','$clie_dir')"); } ?> </form> <table border="1"> <?php include("db.php"); $result=mysql_query("SELECT * FROM cliente"); while($test = mysql_fetch_array($result)) { $id = $test['clie_id']; echo "<tr align='center'>"; echo"<td><font color='black'>" .$test['clie_id']."</font></td>"; echo"<td><font color='black'>" .$test['clie_cod']."</font></td>"; echo"<td><font color='black'>". $test['clie_ape']. "</font></td>"; echo"<td><font color='black'>". $test['clie_nom']. "</font></td>"; echo"<td><font color='black'>". $test['clie_dir']. "</font></td>"; echo"<td> <a href ='view.php?clie_id=$id'>Edit</a>"; echo"<td> <a href ='del.php?clie_id=$id'><center>Delete</center></a>"; echo "</tr>"; } mysql_close($conn); ?> </table> </body> </html> Any help would be highly appreciated. Thank you very much.
  17. Hello guys, first post here. I have a web system which contains a login form programmed in 3 different languages HTML, PHP and JS. The problem is that it's not working, you can access without entering any data, you just press enter and it will work, I don't know why it is not validating any credentials. I was thinking about some query problems but I don't know. I am a newbie on this. I have read a lot but haven't found an answer. A friend helped me build the system but left that uncompleted and he's nowhere to be found. I was wondering if you could help me out with this. <form role="form" ng-submit="login(user,password)"> <div class="form-group"> <input type="user" class="form-control" ng-model='user' placeholder="Usuario"> </div> <div class="form-group"> <input type="password" class="form-control" ng-model='password' placeholder="Contraseña"> </div> <div class="alert alert-warning" id='alert' style="display:none">Revise la informacion...</div> <div class="alert alert-danger" style="display:none" id='alertErr'>Error Usuario o Contraseña Erronea intentelo de nuevo</div> <button type="submit" class="btn btn-primary">Ingresar</button> </form> <?php require_once 'database.php'; $db = new Database(); $body = json_decode(file_get_contents('php://input')); $user =$db->query("SELECT * FROM usuario WHERE usua_login = '".$body->user."' AND usua_pass = '".$body->password."'"); if($user == false){ http_response_code(404); } else{ http_response_code(200); echo json_encode($user); } ?> 'use strict'; /** * @ngdoc function * @name belkitaerpApp.controller:MainCtrl * @description * # MainCtrl * Controller of the belkitaerpApp */ angular.module('belkitaerpApp') .controller('MainCtrl', function ($scope,$http,$location) { $scope.login = function(user,password){ console.log('Login...'); if(user =='' || password ==''){ $('#alert').show("slow"); setTimeout(function() { $('#alert').hide('slow'); }, 3000); } else{ $http.post('../serverSide/login.php',{user:user,password:password}).success(function(data){ console.log('OK!'); $location.path('/products'); }).error(function(data){ $('#alertErr').show("slow"); setTimeout(function() { $('#alertErr').hide('slow'); }, 3000); }); } } });
  18. Hi everyone. I am looking at creating my application's back end with PHP, which returns all data with Jason or simplexml. I have tried Slim once, but think there should be something easier to use. Can anyone give me suggestions on what I can use which is easy to catch on, and maybe an example? Appreciate it. Kind regards
  19. I really don't understand the point of an API. I am totally lost on this one. I have never in my life used JSON and barely touched Javascript so I'm already quite behind the curve but this was my understanding of the "purpose" of an API; You have some data in a database that others might find useful so you write a script that allows people to go in and pull data from it. So why aren't these APIs just built using PHP? If I have a database table of first names, last names and email-addresses, and for some reason I want other people on the internet to be able to get at that, then why don't I just write a one-page script that list them all out? Then all the user has to do is "include" it in their code, right? That's probably really over-simplistic, and I am surely missing the point. There must be a point, but I cannot find a single source anywhere with an actual decent explanation of this. What am I missing? You never know, perhaps you're all about to tell me that most APIs are built using PHP and what I've described is pretty much it. But everything I research leads to a dead end because they all refer to one another; Example 1 - "Oh JSON is freaking awesome. I use it because it's awesome. It's awesome for work working with APIs". Example 2 - "Oh, APIs, yeah, you totally have to have APIs. All you have to do is use JSON. It's awesome". Not direct quotes, but close enough! Seriously, help me out. I have a lot of public data on my server and I am positive that someone can make good use of it. But how?
  20. I have created a flashcard program to teach Japanese vocabulary. I want to add sound files from native speakers so I have created a page with a recorder that 1. displays a word (on load) 2. allows the native speaker to record the word (on press of a button) 3. uploads the recording to the server (on press of another button) I wrote the word display as a separate php script so that I could use Ajax to just change the word being recorded, so that I would not need to reload the entire page every time the speaker switched to a new word. The js that gets the word to be recorded is: function ajaxRequest(){ //declare the variable at the top, even though it will be null at first var req = null; //modern browsers req = new XMLHttpRequest(); //setup the readystatechange listener req.onreadystatechange = function(){ //right now we only care about a successful and complete response if (req.readyState === 4 && req.status === 200){ //inject the returned HTML into the DOM document.getElementById('cardData').innerHTML = req.responseText; }; }; //open the XMLHttpRequest connection req.open("GET","nextcard.php",true); //send the XMLHttpRequest request (nothing has actually been sent until this very line) req.send(); }; The section that uploads the file is: $('#send').click(function(){ $.jRecorder.sendData(); } and it gets the filename from another script: $.jRecorder( { host : 'http://localhost:10088/NewFolder/japanese/jrecorder/acceptfile.php?filename=hello.wav' The problem that I have is that when I get each word I want to change the name of the file being uploaded. It all works and if I reloaded the page each time I could do this: $.jRecorder( { host : 'http://localhost:10088/NewFolder/japanese/jrecorder/acceptfile.php?filename=<?php echo $word.'_'.$reader_id;?>.wav' but I want to stay on the Ajax path. So, I think that I need to convert the newcard program to return json with something like: $response=array(filename=>$word.$reader_id, card_data=>$card_stuff); echo json_encode($response); but once I get the json back I don't see how I get the filename into the script that sets the upload url and make that script re-execute. Is there a reasonable way to do that?
  21. http://paste.ee/p/OhiWv The above is a link to a readable version of my code. The XMLHTTPREQUEST worked, and the array was pulled down. Was able to print out the undecoded/unparsed array. However, immediately afterwards, all code stops working. <script> var xhr; if (window.XMLHttpRequest) { // Mozilla, Safari, ... xhr = new XMLHttpRequest(); } else if (window.ActiveXObject) { // IE 8 and older xhr = new ActiveXObject("Microsoft.XMLHTTP"); } xhr.open("POST", "PHPLibrary/selectMemberResults.php", true); xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded"); xhr.send(); xhr.onreadystatechange = display_data; var $phparray function display_data() { if (xhr.readyState == 4) { if (xhr.status == 200) { //alert(xhr.responseText); $phparray = xhr.responseText; document.getElementById("suggestion").innerHTML = $phparray; // // //......................................................? // The above line of code is the last thing to print or // to do anything that returns to the browser.... //.......................................................? // All lines below do nothing............................? // } else { //alert('There was a problem with the request.'); } } } document.write("Length of phparray Array :" + $phparray.length + "<"); var output = JSON.parse($phparray, function (key,val) { if ( typeof val === 'string' ) { // regular expression to remove extra white space if ( val.indexOf('\n') !== -1 ) { var re = /\s\s+/g; return val.replace(re, ' '); } else { return val; } } return val; } ); document.write("Length of Array :" + $output.length + "<"); for (var i=0; i < $output.length; i++) { document.getElementById("suggestion").innerHTML = $output[i].MEMBER_NAME; } </script>
  22. Hey Guys & Girls, Okay, so here's my little issue. I'm running a WordPress site with a custom PHP script using JSON/CURL/API pulling info from an API. All is good in the world in this respect. However, the API listings that are returned are only returned in a 50 item block. The API doesn't allow for more than 50 items per call. So, what I'm looking for is a way to paginate my results so that if there are more than 50 items in the API call, it will allow the user to click to page 2, 3, 4 etc. Here's my code: <?php //functions relating to wordpress go here: //---------------------------------------- $bg_colors = array('green', 'orange', 'blue', 'yellow', 'red', 'black'); //---------------------------------------- //End functions relating to wordpress // Start PetRescue PHP/API Code //---------------------------------------- // Open CuRL/JSON Stuff $ch = curl_init(); $category=$_GET['category']; $url="http://www.myapilink.com.au/api/listings?token=f716909f5d644fe3702be5c7895aa34e&group_id=10046&species=".$category; curl_setopt($ch, CURLOPT_URL,$url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_HTTPHEADER, array( 'Accept: application/json', 'X-some-API-Key: f716909f5d644fe3702be5c7895aa34e', )); $json = json_decode(curl_exec($ch), true); // Functions relating to the Echo Code foreach($json['listings'] as $listing) { $short_personality=substr($listing['personality'],0,500); $peturl="http://mysiteurl.com.au/beta/pet-info/?petid=".$listing['id']; $medium_photo=$listing['photos'][0]['large_340']; $gallery_listing=$listing['photos'][5]['large_900']; $gender_class=strtolower($listing['gender']); $breed_class=strtolower($listing['species']); $name=($listing['name']); $unique_gallery_name="lightbox['.$inc.']"; $inc++; foreach($listing["photos"] as $photosthumb) { $photo_thumb_large=$photosthumb["large_340"]; $photo_thumb_hidden=$photosthumb["small_80"]; } $rand_background = $bg_colors[array_rand($bg_colors)]; // General IF/AND/ELSE Statements to refine the Echo Output if($listing['photos'] == null) { $medium_photo="http://mysiteurl.com.au/beta/wp-content/themes/Archive/images/photo_coming_soon.png"; } if($listing['desexed'] == "Yes") { $desexed="yes"; } else { $desexed="no"; } if($listing['vaccinated'] == "Yes") { $vaccinated="yes"; } else { $vaccinated="no"; } if($listing['wormed'] == "Yes") { $wormed="yes"; } elseif($listing['wormed'] == "No") { $wormed="no"; } else { $wormed="no"; } if($listing['heart_worm_treated'] == "Yes") { $heart_worm_tested="yes"; } elseif($listing['heart_worm_treated'] == "No") { $heart_worm_tested="no"; } else { $heart_worm_tested="no"; } if($listing['species'] == "Dog") { $adoption_enquiry_link="http://mysiteurl.com.au/beta/pre-adoption-form-dogs/?dog_name=$name"; $hwt="list-$heart_worm_tested"; } elseif($listing['species'] == "Cat") { $adoption_enquiry_link="http://mysiteurl.com.au/beta/pre-adoption-form-cats/?cat_name=$name"; $hwt="list-hwt-hidden"; } // Echo the output echo'<div class="animal"> <div class="animal-image"> <a class="size-thumbnail thickbox" rel="'.$unique_gallery_name.'" href="'.$medium_photo.'"> <img src="'.$medium_photo.'" class="image-with-border" alt=""> <div class="border" style="width: 340px; height: 340px;"> <div class="open"></div> </div> </a> <div class="item-title-bg '.$rand_background.'"> <h2 class="entry-title">'.$listing['name'].'</h2> <div class="animal-adopt-button"> <a href="'.$adoption_enquiry_link.'" style="background-color: #575757; border-color: #494949; background-position:5px 0;" class="button medium">Enquire about '.$name.'</a> </div> </div> </div> <div class="animal-thumbnail hidden"> <a class="lightbox" rel="'.$unique_gallery_name.'" href="'.$photo_thumb_large.'"> <img class="animal-thumbnail" src="'.$photo_thumb_hidden.'" > </a> </div> <div class="animal-content"> <div class="animal-left"> <ul class="animal-list"> <li class="list-sex-'.$gender_class.'">'.$listing['gender'].'</li> <li class="list-breed-'.$breed_class.'">'.$listing['breeds_display'].'</li> <li class="list-age">'.$listing['age'].'</li> <li class="list-fee">'.$listing['adoption_fee'].'</li> </ul> </div> <div class="animal-right"> <ul class="animal-list"> <li class="list-'.$desexed.'">Desexed?</li> <li class="list-'.$vaccinated.'">Vaccinated?</li> <li class="list-'.$wormed.'">Wormed?</li> <li class="'.$hwt.'">Heart Worm Tested?</li> </ul> </div> <div class="animal-full"> <ul class="animal-list"> <li class="list-description">'.$listing['personality'].'</li> </ul> </div></div> <div class="clearer"></div> </div> <div class="delimiter"></div>'; // Close the CURL } curl_close($ch); ?> Attached is some dummy data that represents the JSON data returned from the API. As you can see in the file, the last line is where the paging details comes in. Any help you guys could give would be appreciated. Cheers, Dave listings.txt
  23. Hello guys I Have to try to build an array that has a tree structure(4 levels), but I have gotten an error when I tried to put the 2 level ... commands out of sync; you can't run this command now. I attached a file with the code, what's wrong? Regards. code.txt
  24. Hi guys, I am trying to build a simple web app that takes data from database, converts it into jason and inserts the data into a veriable that should act as a playlist. I want to make the veriable called "songs" to be equals the result and insert it into ytplayer_playlist. Any guides will be very helpfull! var songs; function addsongs(event) { $.ajax({ url: 'post.php', success: function (response) { var url="http://localhost/xampp/websites/youtubeAPI/post.php"; $.getJSON(url,function(data){ $.each(data.members, function(i,song){ result = (song.SongUrl); console.log(result); }); }); } }); } ytplayer_playlist.push('tGvHNNOLnCk');
  25. Hi everyone, let me first preface this by saying that I know very little about php and json. What I know is that I need a webpage that can provide specific weather data for a group of coxswains using their cellphones while out on patrol. Don't worry that you might be talking down to me, because I promise that you won't be when it comes to my codeing skills. That said, I created an API key for weather underground. This provides me with a json file like this: { "response": { "version":"0.1", "termsofService":"http://www.wunderground.com/weather/api/d/terms.html", "features": { "conditions": 1 , "tide": 1 } } , "current_observation": { "image": { "url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png", "title":"Weather Underground", "link":"http://www.wunderground.com" }, "display_location": { "full":"Marcus Hook, PA", "city":"Marcus Hook", "state":"PA", "state_name":"Pennsylvania", "country":"US", "country_iso3166":"US", "zip":"19060", "magic":"3", "wmo":"99999", "latitude":"39.83526230", "longitude":"-75.44973755", "elevation":"28.00000000" }, "observation_location": { "full":"Radnor Green, Claymont, Delaware", "city":"Radnor Green, Claymont", "state":"Delaware", "country":"US", "country_iso3166":"US", "latitude":"39.806858", "longitude":"-75.468452", "elevation":"129 ft" }, "estimated": { }, "station_id":"KDECLAYM2", "observation_time":"Last Updated on January 17, 1:48 PM EST", "observation_time_rfc822":"Fri, 17 Jan 2014 13:48:43 -0500", "observation_epoch":"1389984523", "local_time_rfc822":"Fri, 17 Jan 2014 13:48:43 -0500", "local_epoch":"1389984523", "local_tz_short":"EST", "local_tz_long":"America/New_York", "local_tz_offset":"-0500", "weather":"Scattered Clouds", "temperature_string":"41.7 F (5.4 C)", "temp_f":41.7, "temp_c":5.4, "relative_humidity":"67%", "wind_string":"From the South at 2.0 MPH Gusting to 4.0 MPH", "wind_dir":"South", "wind_degrees":186, "wind_mph":2.0, "wind_gust_mph":"4.0", "wind_kph":3.2, "wind_gust_kph":"6.4", "pressure_mb":"1014", "pressure_in":"29.94", "pressure_trend":"-", "dewpoint_string":"32 F (-0 C)", "dewpoint_f":32, "dewpoint_c":-0, "heat_index_string":"NA", "heat_index_f":"NA", "heat_index_c":"NA", "windchill_string":"42 F (5 C)", "windchill_f":"42", "windchill_c":"5", "feelslike_string":"42 F (5 C)", "feelslike_f":"42", "feelslike_c":"5", "visibility_mi":"10.0", "visibility_km":"16.1", "solarradiation":"--", "UV":"2","precip_1hr_string":"0.00 in ( 0 mm)", "precip_1hr_in":"0.00", "precip_1hr_metric":" 0", "precip_today_string":"0.00 in (0 mm)", "precip_today_in":"0.00", "precip_today_metric":"0", "icon":"partlycloudy", "icon_url":"http://icons-ak.wxug.com/i/c/k/partlycloudy.gif", "forecast_url":"http://www.wunderground.com/US/PA/Marcus_Hook.html", "history_url":"http://www.wunderground.com/weatherstation/WXDailyHistory.asp?ID=KDECLAYM2", "ob_url":"http://www.wunderground.com/cgi-bin/findweather/getForecast?query=39.806858,-75.468452" } , "tide": { "tideInfo": [ { "tideSite":"Marcus Hook, Pennsylvania (sub)", "lat":"39.8117", "lon":"-75.4117", "units":"feet", "type":"tide", "tzname":"America/New_York" } ], "tideSummary": [ { "date": { "pretty": "5:03 PM EST on January 17, 2014", "year": "2014", "mon": "01", "mday": "17", "hour": "17", "min": "03", "tzname": "America/New_York", "epoch":"1389996218" }, "utcdate": { "pretty": "10:03 PM GMT on January 17, 2014", "year": "2014", "mon": "01", "mday": "17", "hour": "22", "min": "03", "tzname": "UTC", "epoch":"1389996218" }, "data": { "height":"", "type":"Sunset" } }, { "date": { "pretty": "6:48 PM EST on January 17, 2014", "year": "2014", "mon": "01", "mday": "17", "hour": "18", "min": "48", "tzname": "America/New_York", "epoch":"1390002484" }, "utcdate": { "pretty": "11:48 PM GMT on January 17, 2014", "year": "2014", "mon": "01", "mday": "17", "hour": "23", "min": "48", "tzname": "UTC", "epoch":"1390002484" }, "data": { "height":"", "type":"Moonrise" } }, { "date": { "pretty": "8:09 PM EST on January 17, 2014", "year": "2014", "mon": "01", "mday": "17", "hour": "20", "min": "09", "tzname": "America/New_York", "epoch":"1390007349" }, "utcdate": { "pretty": "1:09 AM GMT on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "01", "min": "09", "tzname": "UTC", "epoch":"1390007349" }, "data": { "height":"-0.39 ft", "type":"Low Tide" } }, { "date": { "pretty": "1:23 AM EST on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "01", "min": "23", "tzname": "America/New_York", "epoch":"1390026202" }, "utcdate": { "pretty": "6:23 AM GMT on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "06", "min": "23", "tzname": "UTC", "epoch":"1390026202" }, "data": { "height":"4.78 ft", "type":"High Tide" } }, { "date": { "pretty": "7:19 AM EST on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "07", "min": "19", "tzname": "America/New_York", "epoch":"1390047590" }, "utcdate": { "pretty": "12:19 PM GMT on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "12", "min": "19", "tzname": "UTC", "epoch":"1390047590" }, "data": { "height":"", "type":"Sunrise" } }, { "date": { "pretty": "8:12 AM EST on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "08", "min": "12", "tzname": "America/New_York", "epoch":"1390050752" }, "utcdate": { "pretty": "1:12 PM GMT on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "13", "min": "12", "tzname": "UTC", "epoch":"1390050752" }, "data": { "height":"-0.39 ft", "type":"Low Tide" } }, { "date": { "pretty": "8:19 AM EST on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "08", "min": "19", "tzname": "America/New_York", "epoch":"1390051164" }, "utcdate": { "pretty": "1:19 PM GMT on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "13", "min": "19", "tzname": "UTC", "epoch":"1390051164" }, "data": { "height":"", "type":"Moonset" } }, { "date": { "pretty": "1:36 PM EST on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "13", "min": "36", "tzname": "America/New_York", "epoch":"1390070194" }, "utcdate": { "pretty": "6:36 PM GMT on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "18", "min": "36", "tzname": "UTC", "epoch":"1390070194" }, "data": { "height":"5.26 ft", "type":"High Tide" } }, { "date": { "pretty": "5:04 PM EST on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "17", "min": "04", "tzname": "America/New_York", "epoch":"1390082683" }, "utcdate": { "pretty": "10:04 PM GMT on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "22", "min": "04", "tzname": "UTC", "epoch":"1390082683" }, "data": { "height":"", "type":"Sunset" } }, { "date": { "pretty": "7:44 PM EST on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "19", "min": "44", "tzname": "America/New_York", "epoch":"1390092273" }, "utcdate": { "pretty": "12:44 AM GMT on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "00", "min": "44", "tzname": "UTC", "epoch":"1390092273" }, "data": { "height":"", "type":"Moonrise" } }, { "date": { "pretty": "8:47 PM EST on January 18, 2014", "year": "2014", "mon": "01", "mday": "18", "hour": "20", "min": "47", "tzname": "America/New_York", "epoch":"1390096073" }, "utcdate": { "pretty": "1:47 AM GMT on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "01", "min": "47", "tzname": "UTC", "epoch":"1390096073" }, "data": { "height":"-0.36 ft", "type":"Low Tide" } }, { "date": { "pretty": "2:02 AM EST on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "02", "min": "02", "tzname": "America/New_York", "epoch":"1390114947" }, "utcdate": { "pretty": "7:02 AM GMT on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "07", "min": "02", "tzname": "UTC", "epoch":"1390114947" }, "data": { "height":"4.76 ft", "type":"High Tide" } }, { "date": { "pretty": "7:19 AM EST on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "07", "min": "19", "tzname": "America/New_York", "epoch":"1390133959" }, "utcdate": { "pretty": "12:19 PM GMT on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "12", "min": "19", "tzname": "UTC", "epoch":"1390133959" }, "data": { "height":"", "type":"Sunrise" } }, { "date": { "pretty": "8:49 AM EST on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "08", "min": "49", "tzname": "America/New_York", "epoch":"1390139365" }, "utcdate": { "pretty": "1:49 PM GMT on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "13", "min": "49", "tzname": "UTC", "epoch":"1390139365" }, "data": { "height":"", "type":"Moonset" } }, { "date": { "pretty": "8:53 AM EST on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "08", "min": "53", "tzname": "America/New_York", "epoch":"1390139590" }, "utcdate": { "pretty": "1:53 PM GMT on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "13", "min": "53", "tzname": "UTC", "epoch":"1390139590" }, "data": { "height":"-0.37 ft", "type":"Low Tide" } }, { "date": { "pretty": "2:14 PM EST on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "14", "min": "14", "tzname": "America/New_York", "epoch":"1390158882" }, "utcdate": { "pretty": "7:14 PM GMT on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "19", "min": "14", "tzname": "UTC", "epoch":"1390158882" }, "data": { "height":"5.18 ft", "type":"High Tide" } }, { "date": { "pretty": "5:05 PM EST on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "17", "min": "05", "tzname": "America/New_York", "epoch":"1390169151" }, "utcdate": { "pretty": "10:05 PM GMT on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "22", "min": "05", "tzname": "UTC", "epoch":"1390169151" }, "data": { "height":"", "type":"Sunset" } }, { "date": { "pretty": "8:41 PM EST on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "20", "min": "41", "tzname": "America/New_York", "epoch":"1390182096" }, "utcdate": { "pretty": "1:41 AM GMT on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "01", "min": "41", "tzname": "UTC", "epoch":"1390182096" }, "data": { "height":"", "type":"Moonrise" } }, { "date": { "pretty": "9:25 PM EST on January 19, 2014", "year": "2014", "mon": "01", "mday": "19", "hour": "21", "min": "25", "tzname": "America/New_York", "epoch":"1390184750" }, "utcdate": { "pretty": "2:25 AM GMT on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "02", "min": "25", "tzname": "UTC", "epoch":"1390184750" }, "data": { "height":"-0.37 ft", "type":"Low Tide" } }, { "date": { "pretty": "2:41 AM EST on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "02", "min": "41", "tzname": "America/New_York", "epoch":"1390203660" }, "utcdate": { "pretty": "7:41 AM GMT on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "07", "min": "41", "tzname": "UTC", "epoch":"1390203660" }, "data": { "height":"4.78 ft", "type":"High Tide" } }, { "date": { "pretty": "7:18 AM EST on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "07", "min": "18", "tzname": "America/New_York", "epoch":"1390220326" }, "utcdate": { "pretty": "12:18 PM GMT on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "12", "min": "18", "tzname": "UTC", "epoch":"1390220326" }, "data": { "height":"", "type":"Sunrise" } }, { "date": { "pretty": "9:18 AM EST on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "09", "min": "18", "tzname": "America/New_York", "epoch":"1390227517" }, "utcdate": { "pretty": "2:18 PM GMT on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "14", "min": "18", "tzname": "UTC", "epoch":"1390227517" }, "data": { "height":"", "type":"Moonset" } }, { "date": { "pretty": "9:34 AM EST on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "09", "min": "34", "tzname": "America/New_York", "epoch":"1390228453" }, "utcdate": { "pretty": "2:34 PM GMT on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "14", "min": "34", "tzname": "UTC", "epoch":"1390228453" }, "data": { "height":"-0.36 ft", "type":"Low Tide" } }, { "date": { "pretty": "2:53 PM EST on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "14", "min": "53", "tzname": "America/New_York", "epoch":"1390247607" }, "utcdate": { "pretty": "7:53 PM GMT on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "19", "min": "53", "tzname": "UTC", "epoch":"1390247607" }, "data": { "height":"5.10 ft", "type":"High Tide" } }, { "date": { "pretty": "5:07 PM EST on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "17", "min": "07", "tzname": "America/New_York", "epoch":"1390255620" }, "utcdate": { "pretty": "10:07 PM GMT on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "22", "min": "07", "tzname": "UTC", "epoch":"1390255620" }, "data": { "height":"", "type":"Sunset" } }, { "date": { "pretty": "9:39 PM EST on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "21", "min": "39", "tzname": "America/New_York", "epoch":"1390271968" }, "utcdate": { "pretty": "2:39 AM GMT on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "02", "min": "39", "tzname": "UTC", "epoch":"1390271968" }, "data": { "height":"", "type":"Moonrise" } }, { "date": { "pretty": "10:04 PM EST on January 20, 2014", "year": "2014", "mon": "01", "mday": "20", "hour": "22", "min": "04", "tzname": "America/New_York", "epoch":"1390273452" }, "utcdate": { "pretty": "3:04 AM GMT on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "03", "min": "04", "tzname": "UTC", "epoch":"1390273452" }, "data": { "height":"-0.40 ft", "type":"Low Tide" } }, { "date": { "pretty": "3:19 AM EST on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "03", "min": "19", "tzname": "America/New_York", "epoch":"1390292379" }, "utcdate": { "pretty": "8:19 AM GMT on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "08", "min": "19", "tzname": "UTC", "epoch":"1390292379" }, "data": { "height":"4.83 ft", "type":"High Tide" } }, { "date": { "pretty": "7:18 AM EST on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "07", "min": "18", "tzname": "America/New_York", "epoch":"1390306692" }, "utcdate": { "pretty": "12:18 PM GMT on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "12", "min": "18", "tzname": "UTC", "epoch":"1390306692" }, "data": { "height":"", "type":"Sunrise" } }, { "date": { "pretty": "9:47 AM EST on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "09", "min": "47", "tzname": "America/New_York", "epoch":"1390315667" }, "utcdate": { "pretty": "2:47 PM GMT on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "14", "min": "47", "tzname": "UTC", "epoch":"1390315667" }, "data": { "height":"", "type":"Moonset" } }, { "date": { "pretty": "10:18 AM EST on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "10", "min": "18", "tzname": "America/New_York", "epoch":"1390317480" }, "utcdate": { "pretty": "3:18 PM GMT on January 21, 2014", "year": "2014", "mon": "01", "mday": "21", "hour": "15", "min": "18", "tzname": "UTC", "epoch":"1390317480" }, "data": { "height":"-0.34 ft", "type":"Low Tide" } } ], "tideSummaryStats": [ { "maxheight":5.260000, "minheight":-0.400000 } ] } } I wrote a php script like this to parse the data that I need and display it: <!DOCTYPE html> <html> <body> <?php $json_string = file_get_contents("http://api.wunderground.com/api/<key removed for this post>/conditions/tide/q/PA/Marcus_hook.json"); $parsed_json = json_decode($json_string); $wlocation = $parsed_json->{'current_observation'}->{'display_location'}->{'full'}; $temp_f = $parsed_json->{'current_observation'}->{'temp_f'}; $humid = $parsed_json->{'current_observation'}->{'relative_humidity'}; $wind = $parsed_json->{'current_observation'}->{'wind_string'}; $pressure = $parsed_json->{'current_observation'}->{'pressure_mb'}; $pressuretrend = $parsed_json->{'current_observation'}->{'pressure_trend'}; $feels = $parsed_json->{'current_observation'}->{'feelslike_string'}; $wtime = $parsed_json->{'current_observation'}->{'observation_time_rfc822'}; $tlocation = $parsed_json->{'tide'}->{'tideinfo'}->{'tidesite'}; /* $temp_f = $parsed_json->{'current_observation'}->{'temp_f'}; $humid = $parsed_json->{'current_observation'}->{'relative_humidity'}; $wind = $parsed_json->{'current_observation'}->{'wind_string'}; $pressure = $parsed_json->{'current_observation'}->{'pressure_mb'}; $pressuretrend = $parsed_json->{'current_observation'}->{'pressure_trend'}; $feels = $parsed_json->{'current_observation'}->{'feelslike_string'}; $wtime = $parsed_json->{'current_observation'}->{'observation_time_rfc822'};*/ echo "Current temperature in ${wlocation} is: ${temp_f} F, but it feels like ${feels}<BR>"; echo "The current humidity is ${humid}<BR>"; echo "The winds are ${wind}<BR>"; if ($pressuretrend == "+") { echo "The current pressure is ${pressure} and rising <BR>"; } else { echo "The current pressure is ${pressure} and falling <BR>"; } echo "This weather report last updated ${wtime} <BR>"; echo "<Hr>"; echo "<BR>"; ?> </body> </html> Which prints out a nice report like this: What I can't figure out, as in completely and hopelessly lost, is how in the world to get it to make a table of the tides. The json file, for example, uses "pretty" over and over again. I need it to find EACH instance of "pretty" and add it to the tide chart, not just one. I hope I'm clear on what I'm trying to do. If not, please ask questions, just keep in mind that I'm a coding infant!
×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.