Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ajax.BeginForm(), OnSuccess - get event target

I can't get the the target of the element which fired OnSuccess() method within Ajax.BeginForm(). So here is the code snippet:

@using (Ajax.BeginForm("InsertModel", "Home", new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "doWork(this,'SomeCustomText')"
}))
{
    <div id="container">
       <--Some HTML--!>
      <input type="submit" value="OK"/>
    </div>
}

<script>
function doWork(e,customText)
{
   alert(customText);  //It shows 'SomeCustomText', so its good.

   alert(e);  //[Object] object
   alert(e.prop("tagName"));  //Object #<Object> has no method 'prop' 
   alert(e.attr("tagName"));  //Object #<Object> has no method 'attr' 
   alert(jQuery(e).html());  //undefined
   alert(jQuery(e).prop("tagName"));  //undefined
   alert(e.target);  //undefined
   alert(jQuery(e).target);  //undefined
 }
<script/>

The Question:

How to get target?! Thank you

Update 1

The jQuery version should look like this:

jQuery.ajax({
    url:"/Home/InsertModel",
    data:"some post data",
    type:"POST",
    success:function(data){ 
          doWork(this,data); // so i really do not care about data! I just need jQuery(this)
    }
  })
like image 276
Cristian E. Avatar asked Oct 30 '13 19:10

Cristian E.


1 Answers

If you want to access the form element you have many options, if you only have one form on the page you can do $("form") and jquery will give you the form element.

Another option is changing the Ajax.BeginForm constructor that takes the form id as parameter like so:

@using (Ajax.BeginForm("InsertModel", "Home",null, new AjaxOptions
{
    HttpMethod = "POST",
    OnSuccess = "doWork('SomeCustomText')"
}, new {id = "myFormId"}))
{
    <div id="container">
       <--Some HTML--!>
      <input type="submit" value="OK"/>
    </div>
}

And in javascript

<script>
function doWork(customText)
{
   alert(customText);  //It shows 'SomeCustomText', so its good.

   // find the form by id
   $("#myForm1");

   // find forms in the page
   $("form")


 }
<script/>

In plain JQuery:

$.ajax({
    url:"/Home/InsertModel",
    data:"some post data",
    type:"POST",
    success:function(data){ 
       // find the form by id
       $("#myForm1");

       // find forms in the page
       $("form")        

       ...
    }
  });
like image 199
hjgraca Avatar answered Nov 15 '22 02:11

hjgraca