0

I have already read this and this to get some help but there is something wrong in my code. Well I want to insert a form to database via Ajax and this is what i did:

The Ajax function :

<script type="text/javascript">
        function doAjaxPost() {

        var form = $('#ajf');
        frm.submit(function () {
        $.ajax({
        type: "POST",
        url: "${pageContext.request.contextPath}/ajouter_user",
        data:  form.serialize(),
        success: function(response){
        // we have the response
        $('#info').html(response);

        },
        error: function(e){
        alert('Error: ' + e);
        }
        });
        });
        }
        </script>

'#info' is the ID of the DIV where i want to show the success message returned by the controller.

this is my controller :

@RequestMapping(value="/ajouter_user",method=RequestMethod.POST)
    public @ResponseBody String addUser(@ModelAttribute User us,BindingResult result,ModelMap model){
        String returnText;
        if(!result.hasErrors()){
            model.addAttribute("us", new User());
            userservice.AddUser(us);

            model.addAttribute("usersystem", userservice.getAllUsers());
           return returnText = "User has been added to the list." ;
        }else{
           return returnText = "Sorry, an error has occur. User has not been added to list.";
        }

    } 

HTML :

<form:form id="ajf" method="POST" commandName="user">
         Here are my fields ...
        <input  type="submit" value="Créer" onclick="doAjaxPost()"/>

</form:form>

What is wrong is : I don't get the String that the controller return , I get an alert error (object [] object ), the data is inserted to database and the page reload after submitting without giving any error

Can someone give me a toturial how to use Ajax with spring (inserting to database ) please help me

Community
  • 1
  • 1
Souad
  • 3,981
  • 10
  • 58
  • 118
  • Can you check from the controller end if you properly get the requesting ModelAttribute ? – MCF Jun 04 '13 at 18:10
  • The problem is not in the modelAttribute because it works before integrating ajax. – Souad Jun 04 '13 at 18:12
  • So the Ajax works (that is, you are inserting, the controller is working) but the Ajax returns an error? – acdcjunior Jun 05 '13 at 01:52

1 Answers1

0

If you are using jQuery (it looks like you are), then you need to include the event in the function and do an event.preventDefault() to prevent the form from submitting. Otherwise the event will propagate up and the form will submit, and you will get the ajax post and the form post.

CodeChimp
  • 7,511
  • 3
  • 35
  • 76
  • Is it doing the double-submit thing still? – CodeChimp Jun 04 '13 at 19:19
  • sorry i edite my question. the values are inserted to database but i always have the alert error and i don't receive the message returned by the controller @CodeChimp – Souad Jun 04 '13 at 19:24
  • From your problem description, it sounded like you were getting two posts before: "the page reload after submitting without giving any error". Can you confirm if that has gone away? If you use Chrome or Firefox with Firebug, and view what is being sent, do you see one or two posts? Can you put a break point in your code, run it, and see which path it takes? Maybe you are getting an exception? – CodeChimp Jun 04 '13 at 19:30
  • I didn't change anything since my last comment and data are not inserted now to database !! I lose my mind really, I see just one post and i have in the console of firebug this error : **uncaught exception: [Exception... "prompt aborted by user" nsresult: "0x80040111 (NS_ERROR_NOT_AVAILABLE)" location: "JS frame :: resource:///components/nsPrompter.js :: openTabPrompt :: line 457" data: no]** – Souad Jun 04 '13 at 19:38
  • i can't fixe the problem so i don't really know how can i get an answer :/ – Souad Jun 04 '13 at 19:44
  • 1
    Well, it looks like you have a couple things happening. First, you are getting a JavaScript error it appears. Also, you are seeing some possible issues with Hibernate. I would concentrate your efforts on fixing one or the other first to rule out anything you can. Also, I would suggest putting a breakpoint or a printout in your Controller and service classes right before you do the insert to try and ensure your are a) only getting the call once, and b) retrieving the correct data. – CodeChimp Jun 05 '13 at 13:48
  • 1
    I would also put a try/catch around your entire Controller method with a generic printout of the exception stack try try and rule out that something happened on the backend that is somehow being muffled/suppressed from logging. – CodeChimp Jun 05 '13 at 13:49