-1

I want to store an object in a restful server. I tried with an html form and everything works correctly but using javascript it doesn't work.This is the code

var app2={"user_id" : seleVal, "name":nome2, "img":img2, "type":tipo2, "supplier_id": distro}

            $.ajax({
                    type: "POST",
                    url: 'http://localhost:8000/products',
                    data: app2,
                    success: alert("success"),
                    error: alert("error"),
                    }); 

the code get into success and error at the same time so I tried to catch the error making functions inside them but when I do that success and error seem to don't responde.Thank you for the help

  • 1
    With the parenthesis after each `alert`, both are being invoked immediately and their `return` values are what's being assigned to `success:` and `error:`. Related: [JavaScript event handler arguments](http://stackoverflow.com/questions/3249128/javascript-event-handler-arguments) – Jonathan Lonowski Oct 04 '15 at 19:04

3 Answers3

0

the code get into success and error at the same time

These two lines are causing that:

success: alert("success"),
error: alert("error"),

Note how you are actually calling the function alert() in each statement. Do this instead:

...
success: function() { alert("success") },
error: function() { alert("error") },
...
Daniel Conde Marin
  • 7,588
  • 4
  • 35
  • 44
  • this snip may help after you've taken Daniel's advice ..... success: function (data, text, jqXHR) { alert("success" + JSON.stringify(data) ) }), – Peter Scott Oct 04 '15 at 18:59
0

Look this:

$.ajax({
     type: "POST",
     url: 'http://localhost:8000/products',
     data: app2,
     success: function(data){
         alert("Success: " + data);
     },
     error: function(error) {
         alert("Error: " + error);
     }
});
Emir Marques
  • 2,603
  • 2
  • 16
  • 22
0

var app2={"user_id" : seleVal, "name":nome2, "img":img2, "type":tipo2, "supplier_id": distro};

$.ajax({
  type: "POST",
  url: 'http://localhost:8000/products',
  data: app2,
  success: function(){
    alert("success");
  },
  error: function(){
    alert("error");
  }
});