We launched new forums in March 2019—join us there. In a hurry for help with your website? Get Help Now!
    • 18809
    • 109 Posts
    I am building an Android app based on Ionic framework and I am using blogit Extra.
    I want to fetch blog data from tables and I saw that BlogIt Extra saving data in site_content table in database. I successfully fetched content, id, introtext etc.

    I have two questions -

    1 - Its fetching home and others pages content also. So its mixing with blog posts. I just want to fetch content from Blog page. Which is BlogIt container. I am fetching direct from table, and generating REST Api to show json data.

    2 - I am unable to fetch postthumb image tv content on each blog post json. How to fetch this ?

    Or is there any other way to easily get json data for specific container or page?

    Currently getting this. I want images and other rows too like image etc which is generated by image tv and showing on site but not in json or this table (site_content)
    [
      {
        "id": "4",
        "pagetitle": "Post 2",
        "introtext": "Demo summary of post 2 for the BlogIt extra.",
        "content": "<p>Demo content of post 2 for the BlogIt extra.</p>"
      },
      {
        "id": "3",
        "pagetitle": "Post 1",
        "introtext": "Demo summary of post 2 for the BlogIt extra.",
        "content": "<p>Demo content of post 2 for the BlogIt extra.</p>"
      },
      {
        "id": "2",
        "pagetitle": "Blog",
        "introtext": "",
        "content": "<h1>Blog overview</h1>"
      },


    I also use this https://forums.modx.com/thread/102949/rest-api-in-modx-to-build-an-android-app?page=2
    REST api but I am still unable to know how to get tv data in json and that too in right place (blogit post). [ed. note: Mayanktaker last edited this post 5 years, 9 months ago.]
      My Proudly Powerd By Modx site - http://irresistiblemt.in smiley Its simple site but its made in best CMS.
      • 18809
      • 109 Posts
      Anyone???
        My Proudly Powerd By Modx site - http://irresistiblemt.in smiley Its simple site but its made in best CMS.
        • 18809
        • 109 Posts
        Please. Anyone?
          My Proudly Powerd By Modx site - http://irresistiblemt.in smiley Its simple site but its made in best CMS.
          • 17301
          • 932 Posts
          How are you making your call to return the json?
            ■ email: [email protected] | ■ website: https://alienbuild.uk

            The greatest compliment you can give back to us, is to spend a few seconds leaving a rating at our trustpilot: https://uk.trustpilot.com/review/alienbuild.uk about the service we provided. We always drop mention of services offered by businesses we've worked with in the past to those of interest.
            • 3749
            • 24,544 Posts
            We need to see the query that gets the data before we can help you.
              Did I help you? Buy me a beer
              Get my Book: MODX:The Official Guide
              MODX info for everyone: http://bobsguides.com/modx.html
              My MODX Extras
              Bob's Guides is now hosted at A2 MODX Hosting
              • 18809
              • 109 Posts
              <?php
              
              
              
              /** CONFIG:START **/
              $config["host"] 		= "localhost" ; 		//host
              $config["user"] 		= "modx265" ; 		//Username SQL
              $config["pass"] 		= "modx265" ; 		//Password SQL
              $config["dbase"] 		= "modx265" ; 		//Database
              $config["utf8"] 		= true ; 		//turkish charset set false
              $config["timezone"] 		= "Asia/Jakarta" ; 		// check this site: http://php.net/manual/en/timezones.php
              $config["abs_url_images"] 		= "http://domain.com/apps/mymodxblog//media/image/" ; 		//Absolute Images URL
              $config["abs_url_videos"] 		= "http://domain.com/apps/mymodxblog//media/media/" ; 		//Absolute Videos URL
              $config["abs_url_audios"] 		= "http://domain.com/apps/mymodxblog//media/media/" ; 		//Absolute Audio URL
              $config["abs_url_files"] 		= "http://domain.com/apps/mymodxblog//media/file/" ; 		//Absolute Files URL
              $config["image_allowed"][] 		= array("mimetype"=>"image/jpeg","ext"=>"jpg") ; 		//whitelist image
              $config["image_allowed"][] 		= array("mimetype"=>"image/jpg","ext"=>"jpg") ; 		
              $config["image_allowed"][] 		= array("mimetype"=>"image/png","ext"=>"png") ; 		
              $config["file_allowed"][] 		= array("mimetype"=>"text/plain","ext"=>"txt") ; 		
              $config["file_allowed"][] 		= array("mimetype"=>"","ext"=>"tmp") ; 		
              /** CONFIG:END **/
              
              date_default_timezone_set($config['timezone']);
              if(isset($_SERVER["HTTP_X_AUTHORIZATION"])){
              	list($_SERVER["PHP_AUTH_USER"],$_SERVER["PHP_AUTH_PW"]) = explode(":" , base64_decode(substr($_SERVER["HTTP_X_AUTHORIZATION"],6)));
              }
              $rest_api=array("data"=>array("status"=>404,"title"=>"Not found"),"title"=>"Error","message"=>"Routes not found");
              
              /** connect to mysql **/
              $mysql = new mysqli($config["host"], $config["user"], $config["pass"], $config["dbase"]);
              if (mysqli_connect_errno()){
              	die(mysqli_connect_error());
              }
              
              
              if(!isset($_GET["json"])){
              	$_GET["json"]= "route";
              }
              if((!isset($_GET["form"])) && ($_GET["json"] == "submit")) {
              	$_GET["json"]= "route";
              }
              
              if($config["utf8"]==true){
              	$mysql->set_charset("utf8");
              }
              
              $get_dir = explode("/", $_SERVER["PHP_SELF"]);
              unset($get_dir[count($get_dir)-1]);
              $main_url = "http://" . $_SERVER["HTTP_HOST"] . implode("/",$get_dir)."/";
              
              
              switch($_GET["json"]){	
              	// TODO: -+- Listing : site_content
              	case "site_content":
              		$rest_api=array();
              		$where = $_where = null;
              		// TODO: -+----+- statement where
              		if(isset($_GET["id"])){
              			if($_GET["id"]!="-1"){
              				$_where[] = "`id` LIKE '%".$mysql->escape_string($_GET["id"])."%'";
              			}
              		}
              		if(isset($_GET["pagetitle"])){
              			if($_GET["pagetitle"]!="-1"){
              				$_where[] = "`pagetitle` LIKE '%".$mysql->escape_string($_GET["pagetitle"])."%'";
              			}
              		}
              		if(isset($_GET["blogit_post_main_image"])){
              			if($_GET["blogit_post_main_image"]!="-1"){
              				$_where[] = "`blogit_post_main_image` LIKE '%".$mysql->escape_string($_GET["blogit_post_main_image"])."%'";
              			}
              		}
              		if(isset($_GET["introtext"])){
              			if($_GET["introtext"]!="-1"){
              				$_where[] = "`introtext` LIKE '%".$mysql->escape_string($_GET["introtext"])."%'";
              			}
              		}
              		if(isset($_GET["content"])){
              			if($_GET["content"]!="-1"){
              				$_where[] = "`content` LIKE '%".$mysql->escape_string($_GET["content"])."%'";
              			}
              		}
              		if(is_array($_where)){
              			$where = " WHERE " . implode(" AND ",$_where);
              		}
              		// TODO: -+----+- orderby
              		$order_by = "`id`";
              		$sort_by = "DESC";
              		if(!isset($_GET["order"])){
              			$_GET["order"] = "`id`";
              		}
              		// TODO: -+----+- sort asc/desc
              		if(!isset($_GET["sort"])){
              			$_GET["sort"] = "desc";
              		}
              		if($_GET["sort"]=="asc"){
              			$sort_by = "ASC";
              		}else{
              			$sort_by = "DESC";
              		}
              		if($_GET["order"]=="id"){
              			$order_by = "`id`";
              		}
              		if($_GET["order"]=="pagetitle"){
              			$order_by = "`pagetitle`";
              		}
              		if($_GET["order"]=="blogit_post_main_image"){
              			$order_by = "`blogit_post_main_image`";
              		}
              		if($_GET["order"]=="introtext"){
              			$order_by = "`introtext`";
              		}
              		if($_GET["order"]=="content"){
              			$order_by = "`content`";
              		}
              		if($_GET["order"]=="random"){
              			$order_by = "RAND()";
              		}
              		$limit = 100;
              		if(isset($_GET["limit"])){
              			$limit = (int)$_GET["limit"] ;
              		}
              		// TODO: -+----+- SQL Query
              		$sql = "SELECT * FROM `modx_site_content` ".$where."ORDER BY ".$order_by." ".$sort_by." LIMIT 0, ".$limit." " ;
              		if($result = $mysql->query($sql)){
              			$z=0;
              			while ($data = $result->fetch_array()){
              				if(isset($data['id'])){$rest_api[$z]['id'] = $data['id'];}; # id
              				if(isset($data['pagetitle'])){$rest_api[$z]['pagetitle'] = $data['pagetitle'];}; # heading-1
              				
              				/** images**/
              				$abs_url_images = $config['abs_url_images'].'/';
              				$abs_url_videos = $config['abs_url_videos'].'/';
              				$abs_url_audios = $config['abs_url_audios'].'/';
              				if(!isset($data['blogit_post_main_image'])){$data['blogit_post_main_image']='undefined';}; # images
              				if((substr($data['blogit_post_main_image'], 0, 7)=='http://')||(substr($data['blogit_post_main_image'], 0, 8)=='https://')){
              					$abs_url_images = $abs_url_videos  = $abs_url_audios = '';
              				}
              				
              				if(substr($data['blogit_post_main_image'], 0, 5)=='data:'){
              					$abs_url_images = $abs_url_videos  = $abs_url_audios = '';
              				}
              				
              				if($data['blogit_post_main_image'] != ''){
              					$rest_api[$z]['blogit_post_main_image'] = $abs_url_images . $data['blogit_post_main_image']; # images
              				}else{
              					$rest_api[$z]['blogit_post_main_image'] = ''; # images
              				}
              				if(isset($data['introtext'])){$rest_api[$z]['introtext'] = $data['introtext'];}; # text
              				if(isset($data['content'])){$rest_api[$z]['content'] = $data['content'];}; # to_trusted
              				$z++;
              			}
              			$result->close();
              			if(isset($_GET["id"])){
              				if(isset($rest_api[0])){
              					$rest_api = $rest_api[0];
              				}
              			}
              		}
              
              		break;
              	// TODO: -+- route
              	case "route":		$rest_api=array();
              		$rest_api["site"]["name"] = "MyModxBlog" ;
              		$rest_api["site"]["description"] = "My Modx blog Json" ;
              		$rest_api["site"]["imabuilder"] = "rev18.07.25" ;
              
              		$rest_api["routes"][0]["namespace"] = "site_content";
              		$rest_api["routes"][0]["tb_version"] = "Upd.1807311159";
              		$rest_api["routes"][0]["methods"][] = "GET";
              		$rest_api["routes"][0]["args"]["id"] = array("required"=>"false","description"=>"Selecting `site_content` based `id`");
              		$rest_api["routes"][0]["args"]["pagetitle"] = array("required"=>"false","description"=>"Selecting `site_content` based `pagetitle`");
              		$rest_api["routes"][0]["args"]["blogit_post_main_image"] = array("required"=>"false","description"=>"Selecting `site_content` based `blogit_post_main_image`");
              		$rest_api["routes"][0]["args"]["introtext"] = array("required"=>"false","description"=>"Selecting `site_content` based `introtext`");
              		$rest_api["routes"][0]["args"]["content"] = array("required"=>"false","description"=>"Selecting `site_content` based `content`");
              		$rest_api["routes"][0]["args"]["order"] = array("required"=>"false","description"=>"order by `random`, `id`, `pagetitle`, `blogit_post_main_image`, `introtext`, `content`");
              		$rest_api["routes"][0]["args"]["sort"] = array("required"=>"false","description"=>"sort by `asc` or `desc`");
              		$rest_api["routes"][0]["args"]["limit"] = array("required"=>"false","description"=> "limit the items that appear","type"=>"number");
              		$rest_api["routes"][0]["_links"]["self"] = "http://" . $_SERVER["HTTP_HOST"] . $_SERVER["PHP_SELF"]."?json=site_content";
              		break;
              	// TODO: -+- submit
              
              	case "submit":
              		$rest_api=array();
              
              		$rest_api["methods"][0] = "POST";
              		$rest_api["methods"][1] = "GET";
              
              	break;
              
              }
              
              
              header('Access-Control-Allow-Origin: *');
              header('Access-Control-Allow-Credentials: true');
              header('Access-Control-Allow-Methods: GET,PUT,POST,DELETE,PATCH,OPTIONS');
              header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization,X-Authorization');
              if (!isset($_GET["callback"])){
              	header('Content-type: application/json');
              	if(defined("JSON_UNESCAPED_UNICODE")){
              		echo json_encode($rest_api,JSON_UNESCAPED_UNICODE);
              	}else{
              		echo json_encode($rest_api);
              	}
              
              }else{
              	if(defined("JSON_UNESCAPED_UNICODE")){
              		echo strip_tags($_GET["callback"]) ."(". json_encode($rest_api,JSON_UNESCAPED_UNICODE). ");" ;
              	}else{
              		echo strip_tags($_GET["callback"]) ."(". json_encode($rest_api) . ");" ;
              	}
              
              }


              Generated this via a rest api generator script.
              I am also using REST API of Modx as Bob sir and I discussed here
              https://forums.modx.com/thread/102949/rest-api-in-modx-to-build-an-android-app


              Both giving same results. I want to know how do I get tv data like tagger tags or post thumb images so I can use them in app to get featured image in blog list page.

              I want it like this -

              {
                  "id": "4",
                  "pagetitle": "Post 2",
                  "introtext": "Demo summary of post 2 for the BlogIt extra.",
                 "featured_media": "https://domain.com/image.jpg",
                  "tags": "sports, football",
                  "content": "<p>Demo content of post 2 for the BlogIt extra.</p>"
                },
                My Proudly Powerd By Modx site - http://irresistiblemt.in smiley Its simple site but its made in best CMS.
                • 3749
                • 24,544 Posts
                I'm assuming that code above runs on the MODX site.

                Does the API code above instantiate MODX or run inside MODX (as a snippet)? If it did, you could use xPDO to assemble the data to return, and you wouldn't have to create the DB connection (which would make things more secure). Something like this:
                $id = $_GET['id'];
                $doc = $modx->getObject('modResource', $id);
                if ($doc) {
                    $rest_api = array(
                        'id' => $id,
                        'pagetitle' => $doc->get('pagetitle'),
                        'introtext' => $doc->get('introtext'),
                        'featured_media => $doc->getTVValue('featured_media'),
                        'tags' => $doc->getTVValue('tags'),
                        'content' => $doc->get('content');
                    } 
                } else {
                    /* handle error */
                }
                


                Once that's working, you could make it more efficient by using getObjectGraph() to get the resource and its TVs in the same query.

                  Did I help you? Buy me a beer
                  Get my Book: MODX:The Official Guide
                  MODX info for everyone: http://bobsguides.com/modx.html
                  My MODX Extras
                  Bob's Guides is now hosted at A2 MODX Hosting
                  • 18809
                  • 109 Posts
                  Quote from: BobRay at Aug 03, 2018, 06:28 PM
                  I'm assuming that code above runs on the MODX site.

                  Does the API code above instantiate MODX or run inside MODX (as a snippet)?


                  no sir its generated by a different ionic app creator software and nothing to do with Modx. Its just required db user pass and table row and it generates Json with REST.

                  Can you please tell me how to use XPDO to get json data with REST API or something ?

                  I just want my data in json format. Your code, I can understand little bit but dont know how and where to use it.. I am new in this and still figuring out things by browsing forum and documents. Where and how to use your code ?
                  Please help.
                    My Proudly Powerd By Modx site - http://irresistiblemt.in smiley Its simple site but its made in best CMS.
                    • 3749
                    • 24,544 Posts
                    The code I posted will not work outside of MODX.

                    xPDO is for MODX to communicate with the MODX database, so it's not going to help you get anything from an API.

                    Almost all APIs return data in JSON to begin with. If you have one of the API's URLs, you can paste it into your browser's address window and see what it returns.

                    You can also watch the Network tab in Dev. tools (Ctrl-shift-i) in Chrome or Firefox. If you click on the line that calls the API, you can see the request and the response. The response will show you what is returned from the API.

                    Check the API's documentation. There may be a way to tell it the format you want from the returned data.

                      Did I help you? Buy me a beer
                      Get my Book: MODX:The Official Guide
                      MODX info for everyone: http://bobsguides.com/modx.html
                      My MODX Extras
                      Bob's Guides is now hosted at A2 MODX Hosting
                      • 18809
                      • 109 Posts
                      How do I work with xPDO to get json data with Modxs RESTFUL api? I worked with Modxs REST API and got same result but i dont know how to step forward amd get tv data in json.
                      We discussed this earlier here -
                      https://forums.modx.com/thread/102949/rest-api-in-modx-to-build-an-android-app?page=2
                        My Proudly Powerd By Modx site - http://irresistiblemt.in smiley Its simple site but its made in best CMS.