Amuk Saxena
Amuk Saxena

Reputation: 1571

Cakephp :How to post data on two actions

I am trying to post data by a form.

I need to submit the form on other website and have to save the data in my database as well. I tried my best but did not find the solution for this.

Here is my form:

<form class="formaction" action="http:www.demo.com" method="post">
   <input type="text" value="1" name="quantity" class="form-style pull-left">
   <input type="hidden" name="stock" value="1100">
   <input type="submit" value="Add" style="display: block;" class="button-style">
</form>

Case I:

In this case form is submitted to www.demo.com , but it causes error at mystagingserver/addtotrolley

Ajax function:

 $('.formaction').submit(function() {
    $.ajax({
        type: 'POST',
        url: 'mystagingserver/addtotrolley',
        data: { 
               quantity: $( "input[name$='quantity']" ).val(), 
               stockcode: $( "input[name$='stockcode']" ).val()
              }
    });
}); 

Case II:

In this case Form is not submitted to www.demo.com but ajax works properly, and it saves my data to database from mystagingserver/addtotrolley

$('.formaction').submit(function() {
    $.ajax({
        type: 'POST',
        url: 'mystagingserver/addtotrolley',
        data: {
               quantity: $( "input[name$='quantity']" ).val(), 
               stockcode: $( "input[name$='stockcode']" ).val()
              }
    });
    return false;
}); 

Upvotes: 0

Views: 126

Answers (1)

roosevelt
roosevelt

Reputation: 1974

From Case I what I gathered is, when the user clicks Submit, it makes an ajax call. And immediately attempts to submit the form to www.demo.com. Meaning you are moving away from the page and probably losing the connection. What error message are you getting exactly?

The best approach would be to make an AJAX call to your staging server. If it succeeds only then proceed with the regular form submission or make another AJAX post request to the third party domain.

Something like below would be ideal:

$('.formaction').submit(function() {
    $.ajax({
        type: 'POST',
        url: 'mystagingserver/addtotrolley',
        data: {
               quantity: $( "input[name$='quantity']" ).val(), 
               stockcode: $( "input[name$='stockcode']" ).val()
              },
        success: function(resp) {
            $.ajax({
                type: 'POST',
                url: 'http:www.demo.com',
                data: {
                       quantity: $( "input[name$='quantity']" ).val(), 
                       stockcode: $( "input[name$='stockcode']" ).val()
                      },
                success: function(resp) {
                    alert("Successfully submitted to both!");
                }
            });
        }
    });
    return false;
});

Upvotes: 1

Related Questions