0

I'm totally new to this, so apologies if I'm not explaining this correctly.

I want to post some data in json format to a rest service. I'm trying to get this work with JQuery in a simple .cshtml (razor) page.

My json string looks like this:

{
   "ListRequest":{
      "Values":[
         {
            "Name":"SC",
            "Value":"PRO001"
         },
         {
            "Name":"PC",
            "Value":"Z0R14"
         }
      ]
}

}

I need to pass 2 values from a form into this string and then post it but I'm not sure how do I declare this in javascript and then post it to my $.post function.

My HTML looks like this:

<form action="/" id="getListForm">
    <input type="text" name="txtSC">
    <input type="text" name="txtPC">
    <input type="submit" value="Get List">
</form>

I thought I'd just declare a var:

var jsonText = '{"ListRequest":{ "Values":[' +
'{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
'{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';

Is that the correct way to handle this??

Then I've got my 'post' code to test:

var posting = $.post( url, term);

posting.done(function (data) {
    var content = $(data).find("#content");
    $("#result").empty().append(content);
});

But whenever I call this, it put these 2 values as part of a query string, instead of doing an actual post where this data is not visible in the url.

http://localhost/WebTest/WebDataService.svc/GetList?txtSC=brc001&txtPC=12345

Can someone tell me how to fix this??

Thanks.

UPDATE:

Here is the full code from my test page as it still not working for me. I just noticed that the submit event is not triggered. It seems to be putting the textbox and value automatically because they are part of the form, but my event is definitely not triggered as I've just commented all the code and put a alert('test'); and it didn't show up.

Any ideas?

Thanks.

<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>

<script type="text/javascript">

// Attach a submit handler to the form
$("#getListForm").submit(function (event) {
    event.preventDefault();

    //var jsonText = '{"ListRequest":{ "Values":[' +
    //       '{"Name":"SC", "Value":"' + $form.find("input[name='txtSC']").val() + '"},' +
    //       '{"Name":"PC","Value":"' + $form.find("input[name='txtPC']").val() + '"}]}}';


    var obj = {
        ListRequest: {
            Values: [
                 {
                     Name: "SC",
                     Value: $('input[name="txtSC"]').val()
                 },
                 {
                     Name: "PC",
                     Value: $('input[name="txtPC"]').val()
                 }
            ]
        }
    }


    var jsonObj = JSON.stringify(obj);

    var $form = $(this), term = jsonText, url = 'http://localhost/WebTest/DataService.svc';

    $.post(url + '/GetList', jsonObj,
    function (data, status) {
    alert("Data: " + data + "\nStatus: " + status);
    });

    // Send the data using post
    //var posting = $.post( url, term);
    //posting.done(function (data) {
    //    var content = $(data).find("#content");
    //    $("#result").empty().append(content);
    //});

});
</script>

@{
    ViewBag.Title = "Json Test";
}

<hgroup class="title">
    <h1>@ViewBag.Title.</h1>
    <h2>@ViewBag.Message</h2>
</hgroup>


<form id="getListForm">
    <input type="text" name="txtSC">
    <input type="text" name="txtPC">
    <input type="submit" value="Get List">
</form>

<div id="result"></div>

Thanks.

UPDATE:

Latest code where I've updated the term to use the jsonObj and I've put my code in the $(document).ready block as suggested:

<script src="http://ajax.microsoft.com/ajax/jQuery/jquery-1.5.js" type="text/javascript"></script>
<script type="text/javascript">

$(document).ready(function () {
    // Attach a submit handler to the form
    $("#getDocumentListForm").submit(function (event) {

        event.preventDefault();
        alert('test1');

        var obj = {
            ListRequest: {
                Values: [
                     {
                         Name: "SC",
                         Value: $('input[name="txtSC"]').val()
                     },
                     {
                         Name: "PO",
                         Value: $('input[name="txtPC"]').val()
                     }
                ]
            }
        }


            var jsonObj = JSON.stringify(obj);

            var $form = $(this), term = jsonObj, url = 'http://localhost/WebTest/DataService.svc';

            alert(term);
            alert(url);

            $.post(url + 'GetList', jsonObj,
            function (data, status) {
                alert("Data: " + data + "\nStatus: " + status);
            });

            //Tried posting using term but no luck. Same problem.
            //$.post(url + 'GetList',
            //function (data, status) {
            //    alert("Data: " + data + "\nStatus: " + status);
            //});

            // Send the data using post
            //var posting = $.post(url, term);
            //posting.done(function (data) {
            //    //var content = $(data).find("#content");
            //    //$("#result").empty().append(content);
            //    alert(data)
            //});

            alert('test2');
        });
    });

</script>

@{
    ViewBag.Title = "Test";
}

<hgroup class="title">
    <h1>@ViewBag.Title.</h1>
    <h2>@ViewBag.Message</h2>
</hgroup>


<form id="getDocumentListForm">
    <input type="text" name="txtSC">
    <input type="text" name="txtPC">
    <input type="submit" value="Get Document List">
</form>

<div id="result"></div>

Finale Update on this question

MAKE SURE:

  1. NOT TO USE IE11 WITH JQUERY, WELL AT LEAST JQUERY 2.1.1! DON'T KNOW HOW WELL IT WORKS WITH OTHER VERSIONS OF IE.

  2. ALWAYS TEST WITH OTHER BROWSERS

  3. MAKE SURE TO SET YOUR JQUERY SRC TO THE CORRECT HTTP OR HTTPS DEPENDING ON WHAT YOU USE.

That's it.

Thierry
  • 6,142
  • 13
  • 66
  • 117
  • 1
    Why are you posting `term` (whatever it is) and not `jsonText`? Also, it would be easier, prettier and less error-prone to build a JavaScript object, then use `JSON.stringify` on it. – Amadan May 13 '14 at 02:18
  • Do take a look at [this answer](http://stackoverflow.com/questions/6255344/how-can-i-use-jquery-to-post-json-data). Looks like a possible duplicate – AVK May 13 '14 at 02:18
  • change your submission to GET not POST.. http://api.jquery.com/jquery.get/ – Olrac May 13 '14 at 02:19
  • 1
    Have a look here http://stackoverflow.com/a/1407139/870118 – Md Nazmoon Noor May 13 '14 at 02:31
  • Term was being set to jsonText. As for the building the JS object, it makes total sense now! Sorry as I said, I'm new to this :) – Thierry May 13 '14 at 09:49
  • @Olrac, I'm currently testing this and while it might look like a get behaviour, I do want to post the data. – Thierry May 13 '14 at 09:50

1 Answers1

0

I suppose what's going on there is that you are trying to pass an undefined variable named term instead of jsonText, so the javascript code is throwing an uncaught exception and gets ignored, and you get a normal action from your form element.

You should pass the correct data. And also, knowing about JSON.stringify can probably save you a lot of time and headaches ;). You could build your object like so:

var obj = {
    ListRequest: {
        Values: [
             { 
                 Name:  "SC",
                 Value: $('input[name="txtSC"]').val()
             },
             {
                 Name:  "PC",
                 Value: $('input[name="txtPC"]').val()
             }
        ]
    }
};

var jsonObj = JSON.stringify(obj);

Another pitfall I can think of in your code, is that you have bound your AJAX to a click event on your submit button, or to an onsubmit event, and you are not preventDefault()ing.

Edit

Given the code you posted, you have a couple of mistakes:

  1. Did you wrap your code into a jQuery(document).ready() block?
  2. You commented out jsonText but still assign it to the variable term, causing an uncaught exception.

Fix these two things and your POST request will be done correctly.

On the other hand, why on Earth are you using jQuery version 1.5?

Community
  • 1
  • 1
Sunyatasattva
  • 5,619
  • 3
  • 27
  • 37
  • I never thought that I could define an object in JSON format directly in javascript... Dooh (JavaScript notation....) This makes sense!! I thought I had to define it as a string! As for the preventDefault(), I do use it, but didn't include it here. My bad! I'm going to update my post and post the entire page as it still not working. Must be missing something. – Thierry May 13 '14 at 09:38
  • I edited my answer to solve your problem. I tested on my local machine and the POST request gets sent correctly if you fix those two things. – Sunyatasattva May 13 '14 at 16:02
  • I've changed the 2 things you've suggested but still no luck. Any ideas? I'll update my code above so you can clearly see what I've done – Thierry May 16 '14 at 00:40
  • I've managed to get the "done" event to get triggered but when I display the data returned, it displays my .cshtml page rather than the json data. Any ideas? – Thierry May 16 '14 at 01:03
  • I am not sure I understand what the problem is. Your `done` callback gets executed? And right now you are only `alert`ing the data. Is there a problem with that? Also, I ask again, why using jQuery version 1.5? – Sunyatasattva May 16 '14 at 16:25
  • What version of jquery should I use?? I just installed it via NuGet in my asp.net project. While I get the callback, it the callback error that gets triggered and it doesn't even display – Thierry May 17 '14 at 13:35
  • jQuery version 1.5 is more than 3 years old. Either use 1.11.1, or 2.1.1 depending on your browser support requirements. I don't really understand what doesn't work: are you sure your backend code works properly? Your js looks fine to me. Try to test your backend response using something like [Postman](https://chrome.google.com/webstore/detail/postman-rest-client/fdmmgilgnpjigdojojpjoooidkmcomcm/) and let me know how it goes. – Sunyatasattva May 18 '14 at 00:13
  • thanks for taking the time to try to help me out btw. Appreciated. I'm not sure where to go from here. I might just get a crash course on JQuery and learn more about it as I'm obviously missing something. My (WCF) rest web service is 100% correct and is working as expected. Fully tested via Fiddler and via a console app. I just wanted to build a test in JQuery so I could include samples in our documentation on how to do it, but I guess I may have to postpone this for a while until I learn more. Thanks again! – Thierry May 19 '14 at 22:24
  • You're welcome, sorry if I wasn't able to help you further. If you had a public URL of your REST web service I could test your code and try to understand the problem. Good luck! – Sunyatasattva May 20 '14 at 03:03
  • would you believe that this worked all along!! I opened another similar problem when I noticed that IE11 (desktop and modern ui) are the problem! It works just fine in Chrome and firefox! Thank again! – Thierry May 21 '14 at 23:32
  • I don't understand why this wouldn't work on IE11, though, as jQuery should be compatible. Also, in your update you mention not to use jQuery 2.1.1, weren't you using version 1.5? Finally, you can use the global `location.protocol` to get your HTTP vs HTTPs right. You might want to accept this answer (or add another answer and accept it) to close the question. – Sunyatasattva May 22 '14 at 05:48