Search code examples
jqueryyii2pjaxactive-form

Yii2: Detect Pjax form submit vs manual submit


I have a view for creating an item. In the view I have an ActiveForm inside Pjax this form is an image upload input that upon change I use javascript to submit the form:

$('#itemForm').submit();

The purpose is that I want to upload the images to a temp folder and display them on the page so they can be sorted before the item is saved.

The problem I have is differentiating between the javascript submit and when the user submits the form by using the submit button.

I've tried adding a name to the submit button:

Html::submitButton('Save Item', ['class' => 'btn btn-success', 'name' => 'submitButton'])

But regardless of if I submit via javascript or via the button, $_POST contains submitButton, so I can't tell when the images are being uploaded and when the item is being saved.


Solution

  • Well if you want to detect the submit via javascript you should declare a hidden field with a default value of 0.

    Html::hiddenInput('is_js_submit',0,['id'=>'is_js_submit']);
    

    Then before you are calling the

    $('#itemForm').submit();
    

    to submit the form on image upload add the statement

    $("#is_js_submit").val(1)
    

    and now you can check for the value inside your controller/action if it is a javascript submit or normal form submit.

    Hope it helps you out.