Beginners to JQuery

Question!

The following is my form

        <form id="form1">
        <table>
            <tr><td >Name:</td><td class="CommentsRight"><input type="text" name="txtName" style="width:90%" /></td></tr>
            <tr><td >Email: (Optional)</td><td class="CommentsRight"><input type="text" Name="txtEmail" style="width:90%" /></td></tr>
            <tr><td >Comment: </td><td class="CommentsRight"><textarea type="text" style="width:90%" Name="txtMessage" TextMode="MultiLine" Rows="10"></textarea></td></tr>
            <tr><td ></td><td class="CommentsRight"><input type="submit" width="100" ID="cmdSubmit" onclick="javascript: SubmitComment();" />&nbsp;&nbsp;&nbsp;<input type="button" ID="cmdCancel" Text="Reset" value="Reset" onclick="document.getElementById('form1').reset();" /></td></tr>
        </table>
    </form>

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js" type="text/javascript"></script>


function SubmitComment()
{
    alert($("txtName").val());

    $.ajax({
        type: "POST",
        url: "@(Request.RawUrl)",
        data: '{txtCode: "' + $("#txtName.value") + '" }',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function () { alert('success'); } ,
        failure: function (response) {
            alert(response.d);
        }
    });
}

The alert is bringing back undefined all the time for the alert, i'm a beginner to Ajax/Jquery. I've tried #txtName, I've tried input also but it doesn't return any value I put into the txtName, what am I do wrong. I want to then extend data so i pass all the input strings into the data.

In short,

  1. How do I get the value of txtName.text
  2. How do I build up the data string so it contains separated data values

Your help most appreciated.



Answers

you have written wrong code in data parameter in ajax request. you can pass object of paramater then jQuery take care of it to convert into Raw POST data or Query string.

function SubmitComment()
{
    alert($("txtName").val());

    $.ajax({
        type: "POST",
        url: "@(Request.RawUrl)",
        data: {txtCode: $("#txtName").val()},
        dataType: "json",
        success: function (data) { alert('success'); alert(JSON.stringify(data)) } ,
        failure: function (response) {
            alert(response.d);
        }
    });


Look you can do it in many ways. According to your markup you can try to get value of txtName in following way

$("input[name=txtName]").val();

Or you can add an id with the input field in following way



$("input[name=txtName]").val() is to get the value by name. $("#id").val() is to get value by its id. $(".class").val() is to get value by class name.

By : Raghu N


This video can help you solving your question :)
By: admin