I've been trying to convert this code to jQuery from Javascript but to no avail. This code is for adding a new item to a list which I took from the msdn website. It works in javascript but I need it to run every time the page is loaded. I tried to google for why it wasn't working with javascript and found this. The guy who asked the question said it worked well with jQuery. So, I've been trying to convert this. All help is appreciated! Thanks!!
Note: As I'm working for a client, I'm not allowed to use third party tools like SPServices.

Edit: Code I've done till now:

<script language="javascript" src="/SiteAssets/jquery-1.8.3.min.js" type="text/javascript">

</script><script language="javascript" type="text/javascript">

function createListItem() {

    var clientContext = new SP.ClientContext(siteUrl);
    var oList = clientContext.get_web().get_lists().getByTitle("Announcements");

    var itemCreateInfo = new SP.ListItemCreationInformation();
    this.oListItem = oList.addItem(itemCreateInfo);

    oListItem.set_item("Title", "My New Item!");
    oListItem.set_item("Body", "Hello World!");



    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));

function onQuerySucceeded() {

    alert("Item created: " + oListItem.get_id());

function onQueryFailed(sender, args) {

    alert("Request failed. " + args.get_message() + "\n" + args.get_stackTrace());
  • _spBodyOnLoadFunctionNames.push("createListItem"); use this insteed of $(document).ready(function() { createListItem(); }); – Rajesh Chowdary Dec 27 '12 at 10:40
  • Tried. It freezes up my screen after reloading. – Akhoy Dec 27 '12 at 10:45
  • are you using firefox browser if so please install firebug (addons.mozilla.org/en-US/firefox/addon/firebug) and check console tab and refresh the browser and check for error – Rajesh Chowdary Dec 27 '12 at 10:47
  • no problem press F12 key and select console tab and check for the error – Rajesh Chowdary Dec 27 '12 at 10:49
  • have you added sp.js to your page – Rajesh Chowdary Dec 27 '12 at 10:54

_spBodyOnLoadFunctionNames.push("createListItem"); use this instead of $(document).ready(function() { createListItem(); });

Hope this helps

  • Hi, I'm now getting the error: "Unable to get value of the property 'get_current': object is null or undefined" after I refresh the page. Please help. – Akhoy Dec 27 '12 at 12:07
  • send me the code how you are calling that method and all – Rajesh Chowdary Dec 27 '12 at 13:03
  • I replaced _spBodyOnLoadFunctionNames.push("createListItem"); with $(document).ready(function() { ExecuteOrDelayUntilScriptLoaded(createListItem,"SP.js");}); It seems to work properly now. Thanks. – Akhoy Dec 27 '12 at 13:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.