Solved

JQuery Ajax Function not Posting ID

Posted on 2014-01-21
35
503 Views
Last Modified: 2014-01-23
Hi again,
I am still learning  about client side scripting and making probably some foolish mistakes but I have spent the whole day yesterday trying to figure out what I'm doing wrong and got no where.
I have built a website which has a tree view in a master page and it and when you pick a leaf in the tree it gives you all the details. You can then use buttons to find out more info which call jquery Ajax functions. I wrote 2 functions for adding more details 1 opens a partial view

 function getAddDeviation() {        
            $.ajax({            
                type:"GET",
                url:"/Deviations/Create/" + TreeId,
                success: function(content) {  
                    $("#hdnfld").val(TreeId); 
                    $("#tableVW").empty();
                    $("#dinput").html(content);          
                }                              
            });             
        }

Open in new window

and the other Posts back all the details when you have filled in the partial view

 
 function postAddDeviation() {        
        $.ajax({
        type: "POST",
        url:"/Deviations/Create/" + TreeId,
        data: $("#myform").serialize(),       
        success: function (){
        getDeviations()        
        }});
        }

Open in new window

       
the Post function sends all the info except the Treeid I have watched it using firebug and all the fields are populated except P_ID (which should be the value of TreeID).
I know I'm missing something simple but just can't see it
0
Comment
Question by:Niall292
  • 19
  • 11
  • 5
35 Comments
 
LVL 82

Expert Comment

by:leakim971
ID: 39796714
$("#myform").serialize() look for HTML fields (input, textarea, select) having a "name" attribute.
0
 

Author Comment

by:Niall292
ID: 39796784
I'm not sure I follow you.
Everything is coming across except that one field (P-ID)

Do you mean do something like:
 $("myform").serialize(myInput, myTextarea, myTextbox)
0
 
LVL 82

Assisted Solution

by:leakim971
leakim971 earned 300 total points
ID: 39796798
no, I say if you want to see P-ID, the corresponding field MUTS have a name attribute (in our case must be P-ID) and of course inside the form (myform)
0
 

Author Comment

by:Niall292
ID: 39796849
Hopefully you will be able to help me here.
I have a hidden field in myform

 <%= Html.HiddenFor(model => model.P_ID, new { id = "hdnfld",  })%>

but I am having trouble getting the ID from the Masterpage to the hidden field in the Partial View

Thank you for your help
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39796859
You're not behind ID but behind NAME.
Looking for the NAME?
Do a right click on the page, choose view source to locate your hidden field, post it here if needed
0
 

Author Comment

by:Niall292
ID: 39796875
I got it going now but I have to admit it looks ugly.
I was able to get the value of the treeID into a hidden field in the Masterpage  and then made the value of the hiiden field in the partialview the value of the field in the Master page

 $("#hdnfld").val($("#mhdnfld").val()));

Like I said I know it's ugly but it works. Maybe you can think of a better way
0
 

Author Comment

by:Niall292
ID: 39796879
Sorry I didn't see your last comment will do it now
0
 

Author Comment

by:Niall292
ID: 39796897
OK, This is the hidden field

<input id=shdnfld" type="hidden" value="100195" name="P_ID">
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39796984
So it was not inside the form

<form id="myform">
<!-- other fields -->
</form>
<input id=shdnfld" type="hidden" value="100195" name="P_ID">
0
 

Author Comment

by:Niall292
ID: 39797117
I'm sending the whole thing because when I open it and go to view source, it only shows the source of the Master page

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="ctl00_Head1"><title>
	
	Index
	

</title><link href="/Content/Site.css" rel="stylesheet" type="text/css" /><link href="Scripts/Dialog/jquery.ui.dialog.css" rel="stylesheet" type="text/css" />

    <script src="../../Scripts/Dialog/jquery-1.9.1.js" type="text/javascript"></script>

    <script src="../../Scripts/Dialog/jquery-ui-1.10.3.custom.min.js" type="text/javascript"></script>

    <script src="../../Scripts/jsTree/_lib/jquery.js" type="text/javascript"></script>

    <script src="../../Scripts/jsTree/_lib/jquery.jstree.js" type="text/javascript"></script>

    <script src="../../Scripts/jsTree/_lib/jquery.cookie.js" type="text/javascript"></script>

    
    <link href="Scripts/jsTree/jstree.css" rel="stylesheet" type="text/css" />

    <script type="text/javascript">
           var uid = 100136;
           var TreeId;          
          $(function() {          
              $("#categories").jstree(
          {
              "themes": {
                  "theme": "classic",
                  "dots": true,
                  "icons": true
              },
              "json_data": {
                  "ajax": {
                      "url": "/Home/GetEmployeeInfo/"   }
              },

              "core": { "initially_open": uid },
              "ui": { "select_limit": 1 },
//              "cookies": {"auto_save":true,"save_opened":"jstree_open","save_selected":"jstree_select"  },              
              "plugins": ["themes", "json_data", "ui", "cookies", "types"]
          }).bind("select_node.jstree", function(e, data) {	 
            TreeId =   data.rslt.obj.attr("id"); 
            $("hidID").val(TreeId);                 	
            $.ajax({
                type:"GET",
                url:"/Details/GetDetail/" + TreeId,
                success: function(content) {
                    $("#content").empty();
                    $("#content").html(content);
               
                }               
            }); 
	      });
          });          
       
        function getSummary() {
            $.ajax({
                type:"GET",
                url:"/Details/GetDetail/" + TreeId,
                success: function(content) {
                    $("#content").empty();
                    $("#content").html(content);
               
                }               
            }); 
        }
        function getRemarks() {
            $.ajax({
                type:"GET",
                url:"/Remarks/Index/" + TreeId,
                success: function(content) {
                    $("#content").empty();
                    $("#content").html(content);
               
                }               
            }); 
        }
        
          function getDeviations() {
            $.ajax({
                type:"GET",
                url:"/Deviations/Index/" + TreeId,
                success: function(content) {
                    $("#content").empty();
                    $("#content").html(content);
               
                }               
            }); 
        }
        
           function getCorrective() {
            $.ajax({
                type:"GET",
                url:"/Corrective/Index/" + TreeId,
                success: function(content) {
                    $("#content").empty();
                    $("#content").html(content);
               
                }               
            }); 
        }
        
          function getTime_Adj() {
            $.ajax({
                type:"GET",
                url:"/Details/PV_TimeAdj/" + TreeId,
                success: function(content) {
                    $("#content").empty();
                    $("#content").html(content);
               
                }               
            }); 
        }
        
               function getEditSummary() {
            $.ajax({
                type:"GET",
                url:"/Details/Edit/" + TreeId,
                success: function(content) {
                    $("#content").empty();
                    $("#content").html(content)                  
               { $(this).slidedown();
                }}
                              
            }); 
            
        }
        
           function getAddRemark() {
            $.ajax({
                type:"GET",
                url:"/Remarks/Create/" + TreeId,
                success: function(content) {
                    $("#reTable").empty();                     
                    $("#rinput").html(content)                  
               
                }
                              
            }); 
            
        }
        
         function getAddDeviation() {        
            $.ajax({            
                type:"GET",
                url:"/Deviations/Create/" + TreeId,
                success: function(content) {  
                    $("#hdnfld").val(TreeId); 
                    $("#tableVW").empty();
                    $("#dinput").html(content);           
               
                }
                              
            }); 
            
        }
        
           function getEditDeviation() {
            $.ajax({
                type:"GET",
                url:"/Deviations/Edit/" + TreeId,
                success: function(content) {
                    $("#dinput").empty();
                    $("#dinput").html(content)        
                }                              
            });             
        }
        
        
        function postAddDeviation() {        
        $.ajax({
        type: "POST",
        url:"/Deviations/Create/" + TreeId,
        data: $("#myDevform").serialize(),       
        success: function (){
        getDeviations()        
        }});
        }            
             
        
          function getAddCorrective() {
            $.ajax({
                type:"GET",
                url:"/Corrective/Create/" + TreeId,
                success: function(content) {
                    $("#hdnfld").val(TreeId);
                    $("#corTable").empty();
                    $("#cinput").html(content)                  
               
                }
                              
            }); 
            
        }
        
        function postAddCorrective() {        
        $.ajax({
        type: "POST",
        url:"/Corrective/Create/" + TreeId,
        data: $("#myCorform").serialize(),       
        success: function (){
        getCorrective()        
        }});
        }
        
//     $(function() {
//                $("#datepicker").datepicker();
//            });
            
            
//            $("#btnCreateDiv").on('click',getDeviations());
            
    </script>

</head>
<body>
    <div id="header">
        <div class="title">
            CardWorks Roster</div>
        
        <div id="tabs" style="direction: ltr;">
            <ul id="menu" style="direction: ltr;">
                <li><a href="javascript:getSummary()">Summary</a></li>
                <li><a href="javascript:getRemarks()">Remarks</a></li>
                <li><a href="javascript:getDeviations()">Deviations</a></li>
                <li><a href="javascript:getCorrective()">Corrective</a></li>
                <li><a href="javascript:getTime_Adj()">TimeAdj</a></li>
                
            </ul>
            <br />
        </div>
    </div>
    <div id="categories" style="overflow: auto; height: 83vh;">
    </div>
    <input type="hidden" id="hdnfld" />
    <div id="content" style="height: 85%;">
        
        

    <h2>Index</h2>


    </div>
</body>
</html>

Open in new window

0
 

Author Comment

by:Niall292
ID: 39797216
This is copied from the ascx file

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<Mvc.Models.Dev>" %>
<% using (Html.BeginForm(new { id = "myDevform" }))
   {%>
<%= Html.ValidationSummary(true)%>
<fieldset>
    <legend>Add Deviation</legend>
    <%= Html.HiddenFor(model => model.P_ID, new { id = "shdnfld",  })%>
    <table>
        <tr>
            <td>
                <div class="editor-label">
                    <%= Html.Label("Deviation Type")%>
                </div>
                <div class="editor-field">
                    <%= Html.DropDownListFor(x => x.Type, new SelectList((IEnumerable)ViewData["DevTypes"], "Dev_Type_ID", "Dev_Name"))%>
                    <%= Html.ValidationMessageFor(model => model.Type)%>
                </div>
            </td>
            <td>
                <div class="editor-label">
                    <%= Html.Label("Date")%>
                </div>
                <div class="editor-field">
                    <%= Html.TextBoxFor(model => model.Date)%>
                    <%= Html.ValidationMessageFor(model => model.Date)%>
                </div>
            </td>
            <td>
                <div class="editor-label">
                    <%= Html.Label("Time")%>
                </div>
                <div class="editor-field">
                    <%= Html.TextBoxFor(model => model.Time, new { style = "width:30px" })%>
                    <%= Html.ValidationMessageFor(model => model.Time)%>
                </div>
            </td>
        </tr>
        <tr>
            <td colspan="3">
                <div class="editor-label">
                    <%= Html.Label("Notes")%>
                </div>
                <div class="editor-field">
                    <%= Html.TextAreaFor(model => model.Notes, new { style = "width: 500px; height: 70px;" })%>
                    <%= Html.ValidationMessageFor(model => model.Notes)%>
                </div>
            </td>
        </tr>
        <tr>
            <td>
            </td>
            <td>
            </td>
            <td>
                <p>
                    <input type="submit" onclick="javascript:postAddDev()" value="Create" />
                </p>
            </td>
        </tr>
    </table>

    <script type="text/javascript">
        $(document).ready(
        $("#shdnfld").val($("#hdnfld").val()));
        alert($("#shdnfld").val());
    </script>

</fieldset>
<% } %>
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39797321
with Firefox or Chrome, do a right click inside the form, and choose : Inspect the element
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39797378
It looks like you're creating the hidden field OK, but never populating it. In your jQuery, you have the following lines:

TreeId =   data.rslt.obj.attr("id");
$("hidID").val(TreeId);


There is no HTML element called hidID - your hidden element has an ID of 'shdnfld':

<%= Html.HiddenFor(model => model.P_ID, new { id = "shdnfld",  })%>

So your jQuery should probably read:

TreeId =   data.rslt.obj.attr("id");
$("#shdnfld").val(TreeId);
0
 

Author Comment

by:Niall292
ID: 39797519
This is from Firefox

<form method="post" action="/Deviations/Create/myDevform">

    <fieldset>
        <legend></legend>
        <input id="shdnfld" type="hidden" value="100155" name="P_ID"></input>
        <table>
            <tbody>
                <tr>
                    <td></td>
                    <td>
                        <div class="editor-label"></div>
                        <div class="editor-field">
                            <input id="Date" type="text" value="" name="Date"></input>
                        </div>
                    </td>
                    <td></td>
                </tr>
                <tr></tr>
                <tr></tr>
            </tbody>
        </table>
        <script type="text/javascript"></script>
    </fieldset>

</form>

Open in new window

0
 

Author Comment

by:Niall292
ID: 39797544
@Chris,
Thanks for that but that was something else I was trying to do earlier but then found another way to do it so the $("hidID"). field can be totally removed.

Also as I said I got it posting the data now but very ugly and when it finishes it changes to the url in the Address bar to http://localhost5050/Deviations/Create/myform and displays it as a new page instead of repopulating the partial view.
I know it is something I am doing foolishly or ignorantly (taking the true meaning of the word)
0
 
LVL 82

Accepted Solution

by:
leakim971 earned 300 total points
ID: 39797561
You form don't have the right ID here, so you've an other form somewhere else?

So replace :
$("#myform").serialize()
by :
$("form").serialize()
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39797567
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39797577
I think maybe it's time we saw your page in operation. The code you keep posting seems 'inconsistent'!

In your original post, you had these lines:

$("#hdnfld").val(TreeId)
data: $("#myform").serialize(),

But in the page you've just shown us, your form has no ID and your hidden field has an ID of shdnfld

In the setup of the Tree, you are binding a SELECT event and using this code:

TreeId =   data.rslt.obj.attr("id");
$("hidID").val(TreeId);  

But as I previously said $('hidID') is invalid - it's looking for an HTML of the hidID type - that simply doesn't exist.

Seeing your ASP code is absolute no help here - jQuery works on the rendered client-side HTML, not on the server-side code. Once you've loaded up your page in firefox, we need to see the whole generated HTML code.

A link to a test site would help us to solve this one quickly - currently we're only seeing inconsistent snippets
0
 

Author Comment

by:Niall292
ID: 39797713
I will try to explain and don't worry I know it is messy.

The $("hdnfld") is a hidden field in my Master Page.
$("shdnfld") is a hidden field in my partial view.
When I click on my treeview I couldn't get the value to go directly to partial view because it is a choice of partial views you can go to later to either Edit, Add or Delete records.

The partial view I am using is to Add a record so I put the value of the hdnfld into shldnfld (When I look at it that probably is not needed) I will look at that again.

The hidID can be totally taken out for now. I was putting a value there a lot earlier but discovered it was a lot better to use a variable (var id = Treeview).

What can I do to see it.
0
 

Author Comment

by:Niall292
ID: 39797725
@Leakim971,
Sorry I missed your comments and am looking into them now.
I think you have helped me 2 or 3 times before since I started this project.
0
 
LVL 42

Assisted Solution

by:Chris Stanyon
Chris Stanyon earned 200 total points
ID: 39797755
The concept of master views and partials view are specific to ASP - they have absolutely no bearing on the rendered page that your browser sees, and as jQuery acts only on the rendered html, it doesn't matter that the fields are part of master / partial views.

I think you're overly complicated things - if you have one field in a partial view and one field in a master view, it doesn't matter - by the time page is rendered you will have 2 fields in the HTML view and that's all that matters.

I can't stress this enough - jQuery does not work with ASP - never has and never will! It's only the rendered HTML that's important here, which is why we need to see the rendered HTML and NOT the ASP!
0
 

Author Comment

by:Niall292
ID: 39797791
This is my Master page:
and before you point it out I know it is a mess and I am learning as I build this and the hopefully get time to go and tidy it up later.
Does this help or is it exactly what I sent you earlier

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">

    <head id="ctl00_Head1"></head>
    <body>
        <div id="header"></div>
        <div id="categories" class="jstree jstree-0 jstree-focused jstree-classic" style="overflow: auto; height: 83vh;"></div>
        <input id="hdnfld" type="hidden" value="100155"></input>
        <div id="content" style="height: 85%;">
            <h2></h2>
            <div align="center" ;="">
                <div id="dinput" class="inputForm" ;="">
                    <form method="post" action="/Deviations/Create/myDevform">
                        <fieldset>
                            <legend></legend>
                            <input id="shdnfld" type="hidden" value="100155" name="Person_ID"></input>
                            <table>
                                <tbody>
                                    <tr></tr>
                                    <tr>
                                        <td colspan="3">
                                            <div class="editor-label"></div>
                                            <div class="editor-field">
                                                <textarea id="Notes" style="width: 500px; height: 70px;" rows="2" name="Notes" cols="20"></textarea>
                                            </div>
                                        </td>
                                    </tr>
                                    <tr></tr>
                                </tbody>
                            </table>
                            <script type="text/javascript"></script>
                        </fieldset>
                    </form>
                </div>
                <div id="tableVW" class="displayTable"></div>
            </div>
        </div>
        <div id="jstree-marker" style="display: none;"></div>
        <div id="jstree-marker-line" style="display: none;"></div>
        <div id="vakata-contextmenu"></div>
    </body>

</html>

Open in new window

0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39797809
Again with the master page!!! It's extremely important that you get this, otherwise you'll keep going round in circles all day..jQuery works on the ENTIRE HTML Document!! What you've posted isn't the entire HTML document.

I'm going to re-iterate what I said earlier - inconsistent!!! Now your form has no ID and your hidden field is called Person_ID.

We can't help you if you keep changing things like this.

Do you have a link to this site that we can take a look at - at least that way, we can see the full HTML and jQuery in operation.
0
 

Author Comment

by:Niall292
ID: 39797860
I opened the website at the page where I fill in the form to do the post and did a Inspect element in firebug and sent you everything it displayed.
If this is not right please let me know as it is showing my lack of knowledge (ignorance)
0
 

Author Comment

by:Niall292
ID: 39797867
Sorry, yes you are right the when I was sending the Html to you before I edited the hidden field so its name showed as P_ID but it is Person_ID. The website is an Intranet site so unfortunately I can't send you a link to it.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39797910
Using : $("form")
You don't about form name or ID, you ust serialize any form in the page, did you tried it?

data: $("form").serialize()
0
 

Author Comment

by:Niall292
ID: 39797950
@leakim971

Yes,
I did do that, and could that be why the form ID is not showing up anymore?

 function postAddDeviation() {        
        $.ajax({
        type: "POST",
        url:"/Deviations/Create/" + TreeId,
        data: $("form").serialize(),       
        success: function () {
             getDeviations ()
             }
             });
             }

Open in new window

0
 
LVL 82

Expert Comment

by:leakim971
ID: 39797981
No
0
 

Author Comment

by:Niall292
ID: 39802683
leakim971
I am getting somewhere now and it is saving all info. I put in alerts for success: and error: and on error I am getting this [object Object].
Can you help with what that means and how to fix it.

This is how the function looks now:

           function postAddDeviation() {        
        $.ajax({
        type: "POST",
        url:"/Deviations/Create/" + TreeId,
        data: $("form").serialize(),               
        success: function (result) {        
//            getDeviations ();    
                alert(result);       
             },
             error: function (c) {
             alert(c);
             }                
});
}

Open in new window

0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39802704
An object has been returned from your Deviations/Create/ script - probably a json object, so you need to access the properties of the object like so:

result.propertyName

We'd need to see exactly what's output from your script to be more specific. Instead of alert(result), add the following to your script:

console.log(result);

And then have a look at the console (Firebug if your're using Firefox, built in if you're using IE, Chrome etc.) - press F12 to see the developer tools.
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39802727
replace :
alert(result);
by :
alert( JSON.stringify(result) );
0
 

Author Comment

by:Niall292
ID: 39803333
Sorry it took so long to get back,

using alert( JSON.stringify(result) );
I got
{"readyState":0, "resonseText"."","status":0,"statusText":"error"}
0
 
LVL 82

Expert Comment

by:leakim971
ID: 39803346
so check server side process to locate the error, we're aoff topic now no?
Can you see the PID firebug now so your initial question is answered ?
0
 

Author Comment

by:Niall292
ID: 39803373
This is true, My original question is answered and thank you both.
I will look back over the answers and award points .

Thank you for your patience
0
 

Author Closing Comment

by:Niall292
ID: 39803495
I got my question answered but now I have another question or at least something to work on .

Thank you both
0

Featured Post

Maximize Your Threat Intelligence Reporting

Reporting is one of the most important and least talked about aspects of a world-class threat intelligence program. Here’s how to do it right.

Join & Write a Comment

In this article you'll learn how to use Ajax calls within your CodeIgniter application. To explain this, I'll illustrate how to implement a simple contact form to allow visitors to send you an email through your web site.
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

705 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now