javascript – Pegar as informações de um body via Multpart-Form e enviar para o controlador via Ajax . C# MVC

Olá, gente primeiramente eu dei uma enxugada no COD para não ficar gigante, e tentei colocar todas as partes importantes. Ele está todo estruturado corretamente, funcionando sem erros.
Eu preciso pegar todas as informações que o usuário digita e enviar para meu controlador via o meu model.
- O serialize esta capturando todos os dados menos da foto e do vídeo.
- Não sei como fazer a ponte entre essa função serialize e o MVC
Segue o cod com melhores detalhes:

  ```\CSHTML 
    <div id=formulário >
        <form id=dados  Mmultisteps-form>
            <div pag1>
                <input  id="SelectNome" name="IdNome">
                              //primeira página que recebe um nome completo.
                </input>
            </div pag1>
        
            <div pag>
                <input  id="SelectFoto" name="IdFoto">
                              //segunda página que recebe uma foto.
                </input>
            </div pag2>
    
            <div pag3>
                <input  id="SelectVideo" name="IdVideo">
                              // terceira página que recebe um video.
                </input>
            </div pag3>
    
            <div pag4>
                <input  id="SelectCPF" name="IdCPF">
                              // quarta página que recebe dados do tipo CPF.
                  // possui umbotão de submit para o formulário 
                    <button  id="btnSubmitForm"  </button>
                </input>
            </div pag4>
    
        </form>
    </div>
    ```
    //JavaScript está todo estruturado para pegar as informações do usúario e fazer as validações necessarias;
    //Função de exemplo:
       ```         $("#SelectVideo").change(function () {
                    readVideoURL(this);
                    var vid = document.getElementById('uploadVideo');
    
                    if (vid.duration < 20 || vid.duration > 60) {
                        $('#uploadVideo').attr('src', '#');
                        alert("O vídeo deve ter no mínimo 20 e no máximo 60 segundos.")
                    }
                });
    //Essa função faz o sirialize do form, porem não consigo enviar os dados para o controlador e também a Foto/Video.
                function showValues() {
                    var dataForm= $("#dados").serialize();
                    $.ajax({
                url: '@Url.Action("RegistroCliente", "ClientePerfilController")',
                type: 'POST',
                            data: dataForm,
                            datatype: "json",
                            success: function (dataForm) {
                        },
                error: function(){
                console.log("erro na tentativa de emissão!");}
    
                    });
                }
    ```
    //O model está configurado seguinte:
    
    ```
    namespace TH.FrontEnd.Web.Models
    {
        public class ClienteCadVM
        {
        public String TxtName { get; set; }
            public String TxtCPF { get; set; }
            public HttpPostedFileBase ImageFile { get; set; }
            public HttpPostedFileBase VideoFile { get; set; }
        }
    }
    ```
    //O controller está funcionando assim:
                (Route("**/Home/CadastroCliente/ClientePerfilController/RegistroCliente"))
                public async Task<ActionResult> RegistroCliente(TH.FrontEnd.Web.Models.ClienteCadVM profileVM)
                {
                //eu não sei como receber o Model
                    return View();
                }```
    
                                               

magento2 – How to add multiple products to cart using ajax in magento 2

I want to add more products to cart using ajax in magento 2 but it doesn’t work. please help me to solve this problem here’s my code

file ajax.phtml

<script>
require(('jquery'), function($){

    $(document).on("click",".tool-buttton-buy", function() {
        var addCartUrl = "<?php echo $block->getAjaxUrl().'ajaxcart/index/allcart' ?>";
        
        var searchIDs = $("input(name='product')").map(function(){return $(this).val();}).get();

        var jsonString = JSON.stringify(searchIDs);
        $.ajax({
            url: addCartUrl,
            type: 'POST',
            showLoader: true,
            cache: false,
            dataType: 'json',
            data: {productId : jsonString},
            success: function (data) {
                console.log(data);
            }
        });
    })
})

file Controller Ajax

         $productAllId = json_decode($this->getRequest()->getParam('productId'));
    


foreach ($productAllId as $productId) {
   
    $params = array(
                'form_key' => $this->formKey->getFormKey(),
                'product' => $productId, 
                'qty'   =>1
            );              
    $product = $this->product->load($productId);       
    $this->cart->addProduct($product, $params);
    $this->cart->save();

}

javascript – $.ajax(…) is not a function

I have the problem even if I use the regular version of jquery

<script src="https://code.jquery.com/jquery-3.5.1.min.js" integrity="sha256-9/aliU8dGd2tb6OSsuzixeV4y/faTqgFtohetphbbj0=" crossorigin="anonymous"></script>

<script>window.jQuery || document.write('<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>')</script>

ajax function :

    $.ajax() ({
        type: 'POST',
        url: 'file.php',
        data: { name : name, content : content},
        dataType: 'json'
    });

Uncaught TypeError: $.ajax(…) is not a function

How to prevent multiple post with same meta value being created simultaneously in WordPress (with ajax)

I’m trying to make my own appointment system for WordPress. For this, I created a post type called “appointments”. When users select a service from the service list, the available dates and times are listed. When the available date and time are selected and the appointment is created, a meta key named “appointment_datetime” is added for this appointment. Here is where the problem started.

Two different users should not be able to make an appointment for the same service at the same time. Therefore, when a user tries to create an appointment, the following method is used to check whether the date and time he chose are available.

$already_reserved = new WP_Query(array(
    'post_type' => 'appointments',
    'fields' => 'ids',
    'meta_query' => array(
        'relation' => 'AND',
        array(
            'key' => 'datetime',
            'value' => $date_time, // timestamps
            'type' => 'numeric',
            'compare' => '='
        )
    ),
    'tax_query' => array(
        array(
            'taxonomy' => 'services',
            'field' => 'id',
            'terms' => $service_id,
        )
    )
));
if ( !empty($already_reserved->posts) ) {
    $response = 'Sorry, this date is full.';
} else {
    // create new appointment post
    // ...
}

And here is the ajax code I used:

var $response = jQuery('#response');
$('#createnew').click(function () {
    var service = document.getElementById('service').value;
    var datetime = document.getElementById('datetime').value;
    $response.html("<div class='loading'>Waiting...</div>");

    $.ajax({
        type: 'POST',
        url: myajax.ajaxurl,
        data: {
            action: 'new_appoitment',
            service: service,
            datetime: datetime,
            // ... another customer details
        },
        success: function(data, textStatus, XMLHttpRequest) {
            $response.html('');
            $response.append(data);
        }
    });
});

After all; When two different users click the button at the same time, they can create an appointment for the same date and time. Is there any way I can prevent this?

Select2 throws an error on ajax call

What I am doing is:

jQuery(function () {

    jQuery("#make").select2({
        allowClear : true,
        placeholder : "Make",
        ajax: {
            url: my_ajax_object.ajax_url,
            data : {
                action: "get_data"
            },
            success: function (res) {
                alert(res)
            }
        }
    })

})

Select 2 is rendered good, but when I open it it throws an error in the console: Uncaught TypeError: data.call is not a function

In functions.php I have the get_data function like this:

function my_enqueue() {
    wp_enqueue_script( 'ajax-script', get_template_directory_uri() . '-child/js/select2.js', array('jquery') );
    wp_localize_script( 'ajax-script', 'my_ajax_object', array( 'ajax_url' => admin_url( 'admin-ajax.php' ) ) );
}
add_action( 'wp_enqueue_scripts', 'my_enqueue' );

function get_data() {
    echo 1;
    wp_die();
}
add_action( 'wp_ajax_nopriv_get_data', 'get_data' );
add_action( 'wp_ajax_get_data', 'get_data' );

I think the things are pretty straight forward but if you want me to provide some more info, please let me know. Thank you!

webforms – How to redirect in WebformHandler after submitting Ajax form

I’m trying to redirect to a results page after a form that uses Ajax is submitted. The form is a semi long multi step form, so Ajax is enabled for the user experience.

I have created a new WebformHandler and I’m using the confirmForm() method, but I’m having difficulties to make the redirect work. The ‘Confirmation’ setting in my Webform is set to ‘None’. I also don’t see errors in the logs.

namespace Drupalburnout_modulePluginWebformHandler;

use DrupalCoreFormFormStateInterface;
use DrupalwebformPluginWebformHandlerBase;
use DrupalwebformWebformSubmissionInterface;

/**
 * Send values to the matching API and get results back, redirects to results page
 *
 * @WebformHandler(
 *   id = "matching_api_handler",
 *   label = @Translation("Matching API"),
 *   category = @Translation("Webform Handler"),
 *   description = @Translation("Send values to the matching API and get results back, redirects to results page."),
 *   cardinality = DrupalwebformPluginWebformHandlerInterface::CARDINALITY_UNLIMITED,
 *   results = DrupalwebformPluginWebformHandlerInterface::RESULTS_PROCESSED,
 *   submission = DrupalwebformPluginWebformHandlerInterface::SUBMISSION_REQUIRED,
 * )
 */

class MatchingApiWebformHandler extends WebformHandlerBase {

  /**
   * {@inheritdoc}
   */


  public function confirmForm(array &$form, FormStateInterface $form_state, WebformSubmissionInterface $webform_submission) {

    // Get an array of the values from the submission.
    $values = $webform_submission->getData();

    // $result = ... code for calculating results with form values


    $url = DrupalCoreUrl::fromRoute('burnout.match')->setRouteParameters(array('result' => json_encode($result)));
    $form_state->setRedirectUrl($url);

  }

}

I have also tried other possibilities:

  • Using a RedirectResponse which gave me a ‘Headers already sent’ error
  • AjaxResponse with a RedirectCommand, nothing happens, no errors

Hopefully someone can point me in the right direction.

Kind regards

Webform alter with ajax submit callback – field values are empty in callback

At this point I’m doubting if I’m doing it the right way, but I’m struggling with an issue:

I’m adding an Ajax callback to the form alter of a specific form:

function mymodulename_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'webform_submission_matching_node_218_add_form') {
    $form('actions')('submit')('#ajax') = array(
        'callback' => 'matching_api_call',
        //'event' => 'click',
        'effect' => 'fade',
        'speed' => 500,
        'wrapper' => 'block-matchingblock',
        'progress' => (
            'type' => 'throbber',
            'message' => t('Matching...'),
        ));
    }
}

The callback works fine but when I call $form_state->getValues(), I get an array with all my fields but they are simply empty or 0.

My callback function:

function matching_api_call(&$form, DrupalCoreFormFormStateInterface $form_state) {
    // ajax debug
    $response = new AjaxResponse();
    $selector = '#block-matchingblock';
    $content = print_r($form_state->getValues(), true);
    $settings = ();
    
    $response->addCommand(new HtmlCommand($selector, $content, $settings));
    return $response;
}

My output:

Array(
    (field1) =>
    (field2) =>
    (field3) => 0
    (field4) => 0
    (submit) => Match
    (form_build_id) => {formbuildid}
    (form_token) => {formtoken}
    (form_id) => {form_id}
    (op) => Match
)

The entry is added in the backend so it does get submitted. Should I do something else because I’m using Ajax here?

Thanks in advance.

Is it possible to call a custom ajax event after removing a file from a managed_file field?

I have a custom form with a managed_file field element. I’d like to call an ajax event after removing a file (clicking the REMOVE button).

Is there a way to expand the existing ajax callback for the remove button?

ajax – OpenModalDialogCommand without site configuration permission

I have a custom module in Drupal 8.9.9 to open a form in a modal dialog with OpenModalDialogCommand.

The custom_modal.routing.yml file has:

custom_modal.open_modal_form:
  path: '/modal_form/{title}/{vocabulary}'
  defaults:
    _title: 'Modal Form'
    _controller: 'Drupalcustom_modalControllerCustomModalController::openModalForm'
  requirements:
    _access: 'TRUE'
  options:
    parameters:
      title:
        type: String
      vocabulary:
        type: String

And the CustomModalController.php:

  public function openModalForm($title, $vocabulary) {
    $response = new AjaxResponse();

    $values = array('vid' => $vocabulary);

    $term = Drupal::entityTypeManager()
      ->getStorage('taxonomy_term')
      ->create($values);

    $form = Drupal::entityTypeManager()
      ->getFormObject('taxonomy_term', 'default')
      ->setEntity($term);

    $term_form =  Drupal::formBuilder()->getForm($form);

    $response->addCommand(new OpenModalDialogCommand($title, $term_form, ('width' => '800')));

    return $response;
  }

My theme has the following dependencies:

global-scripts:
  dependencies:
    - core/jquery
    - core/drupal.ajax
    - core/drupal
    - core/drupalSettings
    - core/jquery.once
    - core/drupal.dialog.ajax

And I have even added the following to my custom_modal.module:

function custom_modal_form_alter(&$form, &$form_state, $form_id, $no_js_use = FALSE) {
  $form('#attached')('library')() = 'core/drupal.dialog.ajax';
  $form('#attached')('library')() = 'core/drupal.ajax';
}

Nevertheless, whereas everything works fine when I use the site administrator, when using a simple authenticated user the modal dialog does not open and I get the following error:

There was an HTTP AJAX error.
HTTP Result Code: 403
Below is the information on debugging.
Path: /modal_form/Create/style
StatusText: Forbidden
ResponseText: {"message": "The administer site configuration permission is required."}"

Any ideas? Thanks in advance

javascript – Sending referrer URL via WordPress AJAX in vanilla JS

Let’s say you have a form. On submit, you coded the page to submit the form data to a given data base, by holding the data in a json object, like so:

myData = {first_value: value1, second_value: value2}

.. and so on, and converting it to a JSON string before then sending it to the server via AJAX. Now, all of this works perfectly, until the moment where I added the code that the
script shall add the page’s referrer link (obtianed with document.referrer) into the object, if it’s not empty, and also send that additional info to the server in that case.

Problem is that, from what I found, WordPress seems to escape JSON strings using wp_slash() before sending them to the server, resulting in for example, sticking to the example above:

myData = "{"first_value": "value1", "second_value": "value2"}"

The problem with this is that, as soon as the a referrer is added into the myData object, the escape slashing of WordPress does not work properly, and the JSON string’s structure breaks (making that for example keys of myData become actual parameter names). When then using json_decode() on the server – side, I get an empty array when I var_dump(). Happens with pretty much any referrer link, and only since I try to do that.

I tried to use stripslashes() on the server – side, but I get the same empty array when I var_dump(). So I guess using wp_unslash() would yield the same, as the error actually occurs on the client-side already. What I mean by that is, in the data sent in the request Header of the XHR, instead of:

myData : "{"first_value": "value1", "ref":"myUrl", "second_value": "value2" }"

I get something that doesn’t even seem to be a valid JSON string to me anymore:

myData : "{"first_value": "value1", "ref":"myUrl
second_value: "value2" }"

so you can see it kind of breaks the JSON structure at the value of the referrer link. How can I avoid this and safely send referrer links in addition to other data in the same JSON? Is there really no way, and I have to separately serialize the referrer string as a separate request parameter?