GSCustomMenuSection

Contents for SharePoint, ReactJS, C#, ASP .Net, JavaScript, JQuery, SQL

Wednesday, March 16, 2016

Retrieve items from list using JSOM


This blog demonstrates how to connect to a list and retrieve specific items based on filter/query using JSOM.

<script>
    var ListItem;

    function getTheList(employee) {

        clientContext = new SP.ClientContext.get_current();

        //get web object from current context
        var web = clientContext.get_web();

        //Provide list name and fetch the list
        var myList = web.get_lists().getByTitle('LIST_NAME');

        //write a query to fetch records based on filter
        var query = new SP.CamlQuery();
        query.set_viewXml('<View><Query><Where><Eq><FieldRef Name="EmployeeName"/>
            <Value Type="Text">' + employee + '</Value></Eq></Where></Query></View>');      

        //fetch list items based on query formed in above statement
        ListItem = myList.getItems(query); 

        //Load the object
        clientContext.load(ListItem,'Include(EmployeeName)'); 

        //Final step to execute the query to get details for loaded objects
        clientContext.executeQueryAsync(Function.createDelegate(this, this.mySuccessFunction),
             Function.createDelegate(this, this.myFailFunction));

        return false;
    }

    //This method will be called on success of executeQueryAsync
    function mySuccessFunction(sender, args) 
    {    
        var listItemEnumerator = ListItem.getEnumerator();
        while (listItemEnumerator.moveNext())
        {
              var item = listItemEnumerator.get_current();
                  
              var employee = item.get_item('EmployeeName');
              //Your code goes here..
        }
    }

    //This method will be called on failure or on any exception thrown in executeQueryAsync
    function myFailFunction(sender, args) 
    { 
        alert(args.get_message() + "\n" + args.get_stackTrace()); 
    }

</script>

No comments :

Post a Comment