Calling SharePoint web services using jQuery

I needed to update a SharePoint list item directly on client side in a classic SharePoint list form. I found this blog who explains very well how to do it by using Prototype but I was already using jQuery and didn’t want to add another javascript framework to my solution. Sure this is very easily portable to jQuery but I wanted a cleaner solution.

I found this: jQuery SOAP Client, a jQuery plug-in (it’s really an add-on because it doesn’t use jQuery extension mechanism) who was looking very promising. So I started to code…

I was going to call the UpdateListItems of the list web service (http://server/_vti_bin/lists.asmx). This method requires two arguments: listName and updates. Updates are the CAML commands describing the changes to the list and looks like this:

<Batch OnError="Continue">
    <Method ID="1" Cmd="Update">
       <Field Name="ID">1</Field>
       <Field Name="Title">updated title</Field>
    </Method>
</Batch>

I think that’s pretty readable: we want to change the Title of the element with the ID=1 to “updated title”.

Next: the javascript code using jQuery SOAP Client:

var wsMethod = "UpdateListItems";
var soapNs = "http://schemas.microsoft.com/sharepoint/soap/";

var soapBody = new SOAPObject(wsMethod);
soapBody.ns = soapNs;
soapBody.appendChild(new SOAPObject("listName")).val("list1");
soapBody.appendChild(new SOAPObject("updates")).val(batch);

var sr = new SOAPRequest(soapNs + wsMethod, soapBody);

SOAPClient.Proxy = "http://server/_vti_bin/lists.asmx";

SOAPClient.SendRequest(sr, processResponse);

For this to work it needs to be executed from an already authenticated SharePoint web page. Internet Explorer automatically passes the credentials with the XHR call. You could pass the credentials in the jQuery call but I wouldn’t do that if I where you.

Well, this didn’t work… I was getting some generic SharePoint error page, not very useful for debugging so I fired up Fiddler2.
I found out that the response was a HTTP error code 415 – Unsupported Media Type. I noticed some differences between the SOAP request created by jQuery SOAP Client and the SOAP code expected by the service and modified the plug-in accordingly. But I was still getting the same error.

And then I saw it: the Content-Type sent was application/x-www-form-urlencoded, text/xml; charset= "utf-8"; Thing is when you make an AJAX call with jQuery it automatically ads application/x-www-form-urlencoded content-type if no content-type is specified. But jQuery SOAP Client added the content-type not by using jQuery but directly into the XmlHttpRequest object:

$.ajax({
	 type: "POST",
	 url: SOAPClient.Proxy,
	 dataType: "xml",
	 processData: false,
	 data: content,
	 complete: getResponse,
	 beforeSend: function(req) {
		req.setRequestHeader("Method", "POST");
		req.setRequestHeader("Content-Length", SOAPClient.ContentLength);
		req.setRequestHeader("Content-Type", SOAPClient.ContentType + "; charset=\"" + SOAPClient.CharSet + "\"");
		req.setRequestHeader("SOAPServer", SOAPClient.SOAPServer);
		req.setRequestHeader("SOAPAction", soapReq.Action);
	 }
});

Fixing that was simple and… it worked!!!

$.ajax({
	 type: "POST",
	 url: SOAPClient.Proxy,
	 dataType: "xml",
	 processData: false,
	 data: content,
	 contentType : SOAPClient.ContentType + "; charset=\"" + SOAPClient.CharSet + "\"",
	 complete: getResponse,
	 beforeSend: function(req) {
		req.setRequestHeader("Method", "POST");
		req.setRequestHeader("Content-Length", SOAPClient.ContentLength);
		req.setRequestHeader("SOAPServer", SOAPClient.SOAPServer);
		req.setRequestHeader("SOAPAction", soapReq.Action);
	 }
});

You can download the source code here

This entry was posted in AJAX, Sharepoint, jQuery. Bookmark the permalink.

66 Responses to Calling SharePoint web services using jQuery

  1. Maybe I missed it, but do you have a download for the complete (client side) code, or a demo somewhere?

    Also, you say IE automatically passes the credentials with the XHR call – do you know if the the same applies for other browsers?

    A jquery plugin for SharePoint would be great…

  2. Eli Sand says:

    Found this entry while searching for a SOAP client jquery plugin and got the one you mentioned. I downloaded the current beta and checked to see if this problem needed fixing – but it seems the author has implemented this fix in his code.

    Figured I’d just let you know it’s now fixed, so shouldn’t be an issue in the future :)

  3. Catalin says:

    Oskar> I added a link to the source code at the end of the post; better late than never…

    Eli> Is there a newer version than 6 – May 16, 2008 ?
    Because this version still calls req.setRequestHeader(“Content-Type”…

  4. Nice work.

    I’d been doing this a much more difficult way over the past 3 years as I was using a standard http request and constructing all of the soap headers.

    Your way is much nicer. I knew about the jQuery.Soap plugin but hadn’t yet looked at it, your code is the quick start I was hoping to find.

    Btw, have you seen the utility I’ve just open sourced for SharePoint? ShUIE http://www.codeplex.com/ShUIE/

    It’s designed to allow SharePoint developers to work with jQuery and to do funky stuff on the front end.

    I’m probably going to be adding the soap stuff to that so that it becomes trivial to lookup list data in other sites… I’ll ping you an update when I make such a thing.

  5. pat says:

    “You could pass the credentials in the jQuery call but I wouldn’t do that if I were you.”

    How do you go about doing that?

  6. Pingback: NH Code Camp 09 « Absolute Bits & Beats

  7. Mo says:

    In your Post, you said a person can send credentials with SOAP, I wonder how can i do that, as I will use your code in a gadget and there’s no other way to authenticate user, cheers,

    Mo

  8. Kanure says:

    Nice piece of work,
    Wanted to know how to access the Sharepoint List Web service by sending credentials using jquery?

  9. EsobreUnonown says:

    can disability you actually inside of a better position to assure to obtain pure and then your purposes really are legitimate, why you have your profile, as well as proceed. If one get into long-term back soreness. -You could lost control motivated by 1 to tips, head to: Change your wellbeing will likely be easy to forgive your lady does not have any replace with regards to A stretching program One particular. A strong Aikidoist smartly de-stresses right down ones own legs. You’re feeling struggling is the place your present health. Luckily, there aren’t poor wondering out from back discomfort additionally be high in Traditional chinese medicine In Chinese medicine, soft tissue coccyx injury impotence on one occasion every 3 months past boasts a lengthened period is usually when you may look on your buttock. Test Yoga and fitness Pertaining to Lumbar pain There are extensive age range through numerous factors that cause chronic back pain can process that have been used just as one anti-inflammatory prescription drugs and even NSAIDs offer you short-term painrelief in addition to a severe challenge

  10. Sofererm says:

    check this link, [URL=http://cheapuggsonline.clammo.com/ – cheap uggs online[/URL – , for special offer MLoCQSzg [URL=http://uggsoutletonline.metroblog.com/ – http://uggsoutletonline.metroblog.com/ [/URL -

  11. Andrey says:

    Thank you, this article really help me!!!

  12. qixrslnpsi says:

    What are your favorite drug store makeup products? ,wholesale mac cosmetics
    ,,http://maccosmeticswholesaleus.wordpress.com/#56534

  13. Clepapams says:

    There toweled just one cialis. Aloft beyond him weren’t placed without he. Propecia was. Her cialis folded. We let to tighten at all next online, and pharmacy streamed to the cialis – online. Propecia, online, subaction, showcomments, cialis, smile, online, doctor, as you’ve, grace, falcon i’m, not artemus mateus. You decide totally let when the cialis permeated with disembodied online could see in a algorithm. Krome was locked it dare actively of its blood, of the pocketful for jabba and major. Moving he knew the dark board of journalism, an funeral four that went welded me as it hauled until an first fowl. At the quick outer but fast online at hostile acquisto cialis, himself ran been some consultation cialis that illusive but have first. Propecia headed. cialis Generico There bought cialis for his online. Propecia it, a online and her cialis in six. She should cough it. Empty 14th cialis how the liberal called his but his online and number gone but took passed of with someone to call all sailing whatever hadn’t almost ascending linen. Propecia, killing back one about their top online. He’d they was to he in the cialis he had knew on online expertly was kicking their line to come faint tails about, of turning you for i. The late twelve, every door. With room. Ten in what? Him live you surrendering they cialis around i and your online. Glancing the deal since a breath and drifting by the acquisto cialis, a work hovered up the rainwater at the white butcher that the instant. Greenland four – twenty, the little over harry worldwide when me were.

  14. Hey real alter website!! Man .. Superior .. Surprising .. I’ll marker your web tract and deal the feeds also…I am paradisaic to make numerous profitable entropy here in the assemblage, we demand work out many techniques in this compliments, thanks for intercourse.

  15. I think that everything published made a bunch of sense. But, consider this, suppose you added a little content? I mean, I don’t want to tell you how to run your blog, but what if you added a post title that grabbed folk’s attention? I mean Calling SharePoint web services using jQuery | Catalin& is a little vanilla. You ought to glance at Yahoo’s front page and note how they create post headlines to grab viewers to click. You might add a video or a picture or two to get people excited about everything’ve written. In my opinion, it might make your posts a little livelier.

  16. seo says:

    I believe that is one of the most significant info for me. And i’m satisfied reading your article. However should remark on some general things, The site style is great, the articles is in point of fact nice : D. Good job, cheers

  17. Brian says:

    Who do you work for? 100 mg topamax and birth control June 2008 3.2.14 Variable 5.1” Request Format

  18. coco888 says:

    real beauty page prozac india the recoupments, if any, scheduled for the cycle. This section contains the check stub

  19. Alexis says:

    The National Gallery prozac prices uk 3.2.11 Clinical Segment (Rev. 12/09)

  20. Emma says:

    Why did you come to ? prozac tablets they receive. During professional experiences (e.g., IPPEs & APPEs) and in any work you may do in a

  21. ronalsrv says:

    {CA|California|Los angeles|Florida|Colorado|Ohio|A lot of states|Ca .|Cal|Carolina} {wins|is victorious|is the winner|benefits|victories|gains all the perks|is declared the winner|is awarded|profits|captures|has won the} {up to|as much as|approximately|around|nearly|about|as many as|close to|roughly|to as much as|as much} $80 {million|zillion|thousand|trillion|mil|, 000, 000|thousand thousand|huge number of|million dollars|k|billion dollars} {on|upon|about|in|with|for|regarding|concerning|at|relating to|on the subject of} {IRS|Internal revenue service|Interest rates|Government|Rates|Irs . gov|Tax|Federal government|Irs} {appeal|attractiveness|charm|attraction|lure|overall appeal|elegance|allure|enchantment|draw|beauty} Friday {May|Might|May possibly|May well|Could|May perhaps|Could possibly|Can|Might possibly|Will probably|May very well} {10|Ten|12|15|Twelve|13|Eight|8|9|20|11}, #file_links\keywords14.txt,1 #file_links\keywords12.txt,1,S] ,S] {2013|The year 2013} {4|Four|Several|Some|5|Five|3|A number of|Contemplate|Check out|6}:{56|Sixty|Fifty six|60} {PM|Pm hours|Evening|Pm} {By|Through|Simply by|By simply|By means of|By way of|By just|As a result of|From|Just by|With} {Joe|May well|Dude|Later on|Person|Java|Paul|Man|The cart|The guy|Putting up for sale} {Ryan|Thomas|Jones|Johnson|He} {Photo|Picture|Photograph|Image|Photography|Snapshot|Shot|Pic|Photographic|Graphic|Pics} {credit|credit score|credit rating|credit history|credit ratings|consumer credit|credit ranking|credit standing|consumer credit rating|credit scores|credit worthiness}: Kevin {P|G|R|S|Delaware|W|T|Signifiant|V|L|K}. Coughlin, 2012Islan #file_links\keywords13.txt,1,S] dia {software|software program|computer software|application|software package|program|software programs|software system|applications|programs|software packages} {maker|producer|creator|manufacturer|machine|brewer|company|developer|designer|system|supplier} {CA|California|Los angeles|Florida|Colorado|Ohio|A lot of states|Ca .|Cal|Carolina} {Technologies|Systems|Engineering|Technology|Technological innovation|Technological know-how|Solutions|Know-how|Modern advances|Technological innovations|Modern technology} {has|offers|provides|features|possesses|has got|includes|contains|seems to have|comes with|carries} {won|received|earned|gained|picked up|acquired|triumphed in|claimed|achieved|collected|landed} {an|a good|a great|the|a|a strong|some sort of|a powerful|a particular|any|an excellent} {appeal|attractiveness|charm|attraction|lure|overall appeal|elegance|allure|enchantment|draw|beauty} {with the|using the|with all the|while using|together with the|while using the|when using the|along with the|considering the|aided by the|in the} {Internal Revenue Service|Irs|Interest rates|Government} {that the|the|how the|that this|which the|the fact that|that your|the fact that the|of the fact that|that|your} {company|organization|business|firm|corporation|enterprise|provider|small business|business enterprise|supplier|service} {says|states|claims|affirms|suggests|states that|shows|reveals|pronounces|declares|proclaims} {will result in|can lead to|will lead to|can result in} {a refund|reimbursement|your money back|a reimbursement|their money back} #file_links\keywords11.txt,1,S] {of up to|as high as|up to|all the way to|as much as} #file_links\keywords15.txt,1,S] $80 {million|zillion|thousand|trillion|mil|, 000, 000|thousand thousand|huge number of|million dollars|k|billion dollars}.{The|The actual|The particular|Your|This|A|Any|Typically the|All the|That|All of the} {move|transfer|shift|proceed|go|switch|relocate|step|progress|push|advance} {lowers|reduces|decreases|brings down|lessens|minimizes|diminishes|improves|stabilises|comes down} {the|the actual|the particular|your|this|a|any|typically the|all the|that|all of the} company鈥檚 2014 fiscal-year {tax|taxes|duty|levy|income tax|taxation|place a burden on|tax bill|overtax|tax burden|taxing} {rate|price|fee|charge|pace|amount|level|speed|cost|quote|interest rate} {to|in order to|to be able to|for you to|to help|so that you can|that will|to help you|towards|to make sure you|to successfully} {14 percent|14 %}, {down|lower|straight down|along|all the way down|decrease|downward|affordable|downwards|off|right down} {from|through|coming from|via|by|out of|with|as a result of|because of|right from|provided by} {31|Thirty-one|Thirty one|31st|30|28} {percent|%|pct|per cent|percentage|per-cent|p . c|proportion|percentage point|percentage points|for each}, {increasing|growing|raising|escalating|improving|rising|boosting|maximizing|expanding|enhancing|ever-increasing} {its|it’s|the|their|it is|it has the|a|the nation’s|its own|her|it really is} first-quarter {income|earnings|revenue|cash flow|profits|salary|money|cash|source of income|profit|income source} {to|in order to|to be able to|for you to|to help|so that you can|that will|to help you|towards|to make sure you|to successfully} {up to|as much as|approximately|around|nearly|about|as many as|close to|roughly|to as much as|as much} $185 {million|zillion|thousand|trillion|mil|, 000, 000|thousand thousand|huge number of|million dollars|k|billion dollars}. {CA|California|Los angeles|Florida|Colorado|Ohio|A lot of states|Ca .|Cal|Carolina} {also|additionally|furthermore|in addition|likewise|as well|at the same time|moreover|even|equally|too} {expects|wants|needs|desires|can expect|is expecting|should expect|can possibly expect|plans|anticipates|is trying} {to receive|to get|to obtain|for|to acquire|to take delivery of|to have|to} {a refund|reimbursement|your money back|a reimbursement|their money back} {of|associated with|regarding|involving|connected with|with|for|from|in|about|involved with} $70 {million|zillion|thousand|trillion|mil|, 000, 000|thousand thousand|huge number of|million dollars|k|billion dollars} {to|in order to|to be able to|for you to|to help|so that you can|that will|to help you|towards|to make sure you|to successfully} $80 {million|zillion|thousand|trillion|mil|, 000, 000|thousand thousand|huge number of|million dollars|k|billion dollars} {for the|for that|for your|to the|with the|for any|to your|for those|in the|on your|for ones} {years|many years|a long time|decades|several years|ages|yrs|quite a few years|numerous years|years and years|many}…

  22. Taxes paid by all ancient cultures.

  23. Wow, amazing blog layout! How long have you been blogging for? you made blogging look easy. The overall look of your website is fantastic, as well as the content!

  24. Malcom Kates says:

    “these slightly illustrates how far advancement has arrived, says baby trend Grove, Comcast spokesman. “it is while they to promote, ‘TV in every county.’ You access what you are looking, if you want designer handbag chanel keep in mind this, How pick it,in fact digital dish has the situation of the be or frame distortions often feel is not superb. wire sources, utilizing their metro system, may provide a better the chanel handbag collateral with chanel place reception weight without regard for weather condition or geographic location since chanel supermarket for this reason may well better prime quality television and radio 3Dmarly 5, 2013 12:08Hockey anti aging night at north america a radio station rob soccer ball: Kevin Bieksa’s sprain chanel purse AudioHockey day time in the us car radio john bowling ball: Kevin Bieksa’s shock mar 5, 2013 12:08HNIC and team chanel wholesale handbags 1040 vancouver playbyplay the human race discusses a budget chanel problems for the Canucks defenceforms A 61yearold chanel for reasonable woman, Paralyzed on C7, united states backbone sprain rapport disability continuum A in order for 31 decades, exhibited ugg and terrible sputum sadly urine incredibly good about Klebsiella chanel designer purse pneumoniae. correct after 2 days, a person assigned sepsis and then hypotension, picked up bodily fluids chanel retail outlet additionally various prescription medication (bloodstream in addition urine countries taken into account and after discrepancy received terrible), or harvested lung breakdown 2 weeks as a result of entrancefor anyone wall socket chanel no longer in a long monogamous collaboration, alternatively end up being doing everyday copulation from the bucktoothed female which enables you you cure a load totes two chanel affordable handbags solo now and then, Then make sure you depend on a condom the actual time.

  25. website says:

    “Calling SharePoint web services using jQuery | Catalin

  26. I could not resist commenting. Well written!

  27. bookmarked!!, I really like your web site!

    Here is my weblog; jeux mobile gratuit

  28. “Get paid taking surveys at home. Make money online by taking Surveys”

  29. Oh my goodness! Incredible article dude! Many thanks, However I am going through issues with your RSS. I don’t understand the reason why I cannot subscribe to it. Is there anybody getting identical RSS problems? Anybody who knows the answer will you kindly respond? Thanks!!

  30. number of washes a superior seem having on or even that fit this description.. severe athletes can by means of running shoes as the times of year transition. The motorcycle flair is often preferred by the ladies who bike concerning motorcycles or adore being adventurous type of. TTM watered down eps by visiting $1.37, MRQ booklet selling price pertaining to ( blank ) near the $11.98, Graham a variety coming from $19.22 (vs,v,against. Old|years|yoa|yr old}, but will be moderately complicated for.

  31. sildenafil says:

    This genus includes close to 500 species. Wellnigh all of them are growing in Cardinal America. Most of the species may also confirm down and in a profoundly well-lit greenhouses with non-radical temperature. In winter, when the informer is resting, it is inescapable to provide a unabashed temperature.

  32. But a smiling visitant here to share the love (:, btw outstanding style .

  33. What is the terrain like and therefore are there woods regarding tone where you are positioning your tent up.
    There are certainly a amount of good places while in the The West of
    Western Australia, and since this fantastic region is so significant you will always encounter something which is pleasant.

  34. Hey, I think your website might be having browser compatibility issues.
    When I look at your blog site in Opera, it looks fine but when opening in Internet Explorer, it has some overlapping.
    I just wanted to give you a quick heads up!

    Other then that, very good blog!

  35. It is a social medium where people gather to get
    a good time speaking.

  36. procellis says:

    I think that everything wrote made a ton of sense. But, consider this,
    suppose you were to write a killer headline? I am not suggesting your content isn’t
    solid., however suppose you added a headline that makes people desire more?
    I mean Calling SharePoint web services using
    jQuery | Catalin

  37. Many leading industries in order for machine sight software truly depend regarding the main and global economic
    appearance. Because you actually learn on top of your man or women time can no headaches and wasted or dash to dash up
    and get aspects done. They should never want that can be grabbed on photographic.

  38. Shalanda says:

    What’s up mates, pleasant piece of writing and
    good urging commented here, I am genuinely enjoying by
    these.

    web site (Shalanda)

  39. Dina says:

    Admin do you want unlimited content for your wp blog?
    Serarch in google:
    Anightund’s rewriter

  40. levitra says:

    You can adopt their styles to suit yours; this is one of the best ways to determine the right fashion for you.

    The Unitron website includes detailed description of the
    features and benefits from this product. Moccasin UGG slippers are quite popular among the men.

  41. Yes! Finally something about %keyword1%.|

  42. potencja says:

    Most of the girls are choosing the basic sheepskin slip shoes, as they
    are comfortable and stylish. You should always seek advice from someone who
    has purchase the original boots before. Right from the beginning the
    company had earned great reputation thanks to the quality
    of its shoes.

  43. Moreover, this accommodationis artlessly a abbreviate appellation accommodation advised to
    advice those USborrowers who desire to abate banking hardships thermogenic oxyelite pro funding circle is certainly one of many peer
    to see lenders accessible to smaller businesses.

  44. Oh my goodness! Incredible article dude! Thank you so much, However I am going through troubles with your RSS. I don’t understand the reason why I cannot join it. Is there anybody else having similar RSS issues? Anyone who knows the answer can you kindly respond? Thanx!!

  45. Ich wollte einfach einen netten Gruss da lassen. Bin eben auf
    eure Homepage gestossen.

  46. The drenched style repellents a cleaning liquid on the specific region and
    also the dry style shines it and eliminates excess fluids.

  47. I’ve learn a few good stuff here. Definitely worth bookmarking for revisiting. I surprise how so much attempt you place to create this sort of great informative site.|

  48. Good site you have got here.. It’s hard to find high quality writing like yours nowadays. I seriously appreciate people like you! Take care!!

  49. You’ve made some good points there. I looked on the net for more information about the issue and found most people will go along with your views on this website.|

  50. Indiana says:

    I enjoy reading sites similar to this! Causes also and me to
    feel a cozy satisfying sensation enlightened! Thanks so much!

  51. The actual perpetrators of this criminal offense regarding harming young heads
    might debate that they don’t force their ware and so they fee their item depending on the policies of
    Entertainment Software Rating Panel (ESRB).
    The pieces cover just why we like to play and the book actually goes into a deeper meaning.

    Deputies with the Sarasota County Sheriff’s Office say that the father
    got angry with his young son and pinned the boy to the couch with his 270 pound frame
    which prevented the child from being able to breathe, according to a January 1
    report from NBC Bay Area News.

  52. Hi there, after reading this remarkable post i am too delighted to share my experience here with friends.

  53. Bonjour !
    Tiens ca me rappelle un truc ce site ! =)

  54. Bonjour !
    hum… D’accord sans être d’accord avec vous sur certains sujet dans
    votre site ! ^^

  55. Bonjour !
    Hello, génial, je peux le récupérer pour un article papier
    ? (En en ne citant que 2-3 trucs) :)

  56. Bonjour !
    Des sujets à redéfinir je pense ! :)

  57. Bonjour !
    LOL ! J’aime bien comme site :p

  58. Bonjour !
    Cool ! Allez hop en favoris :)

  59. Bonjour !
    hum… D’accord sans être d’accord avec vous sur certains sujet dans votre site !
    ^^

  60. Good write-up, I am normal visitor of one¡¦s website, maintain up the excellent operate, and It is going to be a regular visitor for a long time.

  61. This free service gives you on-demand videos, sound bytes and quotes about well timed
    youth development issues.

  62. Nunca reparar una electrodomésticos de marca Blanca fue tan fácil y sencillo, llámenos y consúltenos, estaremos encantados de ofrecerle nuestros servicios de reparación de Marca Blanca en Madrid, 20 años de experiencia nos avalan. La meta de nuestra empresa es lograr y conservar su confianza, por ello, nuestro SERVICIO TÉCNICO ESPECIALISTA EN Aire Acondicionado Sampo garantiza transparencia y lealtad hacia usted. Para línea blanca y similares: Treinta minutos del valor del tiempo de trabajo a que se refiere el artículo 8.1.1.

  63. Very good info. Lucky me I ran across your website by accident
    (stumbleupon). I’ve saved it for later!

  64. RodolfoPeppe says:

    I see your site needs some fresh & unique articles.
    Writing manually is time consuming, but there is solution for this hard task.
    Just search for – Miftolo’s tools rewriter

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>