Save Data Through Ajax In Prestashop

In this tutorial I will show you how easy is to save data through ajax in Prestashop. I will assume you already have the form which needs to be saved using ajax. For this example I will create a very simple form with an input because backend code is the part which interests you. So in the following you can see my basic form:

<form id="save_post_name" action="url to controller">
<input type="text" name="post_name" placeholder="Post name">
<button type="submit" name="save_post_name">Save Data</button>
</form>

As you can see is a simple form the only thing where you should pay attention is at the button element because I added a name parameter to it, which will called in the backend to know what form was submitted. Don't forhet to replace the action parameter with the url to your controller.

The javascript part should look like the following:

jQuery('#save_post_name button').on('click', function(e){
    e.preventDefault();
    var link = jQuery('#save_post_name').attr('action'),
        data = jQuery('#save_post_name').serialize();
    jQuery.ajax({
        type:"POST",
        url:link,
        data:data,
        success:function(result){
            console.log(result);
        },
        error:function(error){
            console.log(error);
        }
    });
});

With the above function you will be able to send data from your form to the controller. With all these already done the next step is to get data in controller and from there we can save it in the database. There is no difference between how to save data using ajax and saving data in normal way. So, we need to create a postProcess() functon in our controller to handle the data which will come using ajax. 

Your function should look like the following:

public function postProcess(){
    if(Tools::isSubmit('save_post_name')){
       $fields = $_POST;
       echo '<pre>';var_dump($fields);die();
    }
}

In if statement we check if the attribute passed in our button element is in the $_POST fields. If it is there we know that the right form was submitted. This is the easiest way you can save data through ajax in prestashop. Let me know if you have any questions about this method and I will try to help you.

0 0 votes
Article Rating
Subscribe
Notify of
guest
1 Comment
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Oliver
Oliver
3 years ago

This saves me, thanks!

1
0
Would love your thoughts, please comment.x
()
x