Search code examples
wordpressphonegapwordpress-rest-api

I need to receive fetch post from my wordpress to phonegap using wordpress rest api & json


please i need help concerning phonegap and wordpress rest api.. I am a bit new to phonegap. i want to be able to receive my latest posts using GET etc and likely post from my mobile and also possibly perform other CRUD operation. thanks


Solution

  • I got it done already thanks much. I am posting my code here to help some out there and these community:

    // Device Event Listener

    document.addEventListener("deviceready", onDeviceReady, false);
    var portfolioPostsContainer = document.getElementById("portfolio-posts-container");
    var portfolioPostsContainer2 = document.getElementById("portfolio-posts-container2");
    
    
    function onDeviceReady(){
    
     var ourRequest = new XMLHttpRequest();
     ourRequest.open('GET', 'http://mydomain/wp-json/wp/v2/posts?_embed');
     ourRequest.onload = function() {
      if (ourRequest.status >= 200 && ourRequest.status < 400) {
        var data = JSON.parse(ourRequest.responseText);
        createHTML(data);
        console.log(data);
    
      // portfolioPostsBtn.remove();
    } else {
      console.log("We connected to the server, but it returned an error.");
    }
    };
    
    ourRequest.onerror = function() {
      console.log("Connection error");
    };
    
    ourRequest.send();
    
    }
    
    
    function createHTML(postsData) {
     var ourHTMLString = '';
     var postid ='';
    
    
    for (i = 0; i < postsData.length; i++) {
    
     var posturl = postsData[i].link;
     ourHTMLString +='<tr>';
    
     ourHTMLString += '<td>' + '<a href="loadpost.html?id='+postsData[i].id+'" + rel="external" + " style="text-decoration:none ">'  + postsData[i].title.rendered + postsData[i].id+'</a>'+'</td>';
     ourHTMLString += '<td>' + '<a href="loadpost.html?id='+postsData[i].id+'"><img width="100%" src ="' + postsData[i]._embedded['wp:featuredmedia']['0'].source_url + '"  />' + '</a>'+'</td>';
     ourHTMLString += '<td>' + postsData[i].excerpt.rendered + '</td>';
     ourHTMLString+= '</tr>';
    } 
    portfolioPostsContainer.innerHTML = ourHTMLString;
    }