adminhtml – Magento admin ajax call file upload

I’m trying to make a ajax call in admin page to upload a csv file in directory then to make a stock update function.

In my PHTML:

<form method="post" enctype="multipart/form-data" id="ajaxCall" >
<input name="form_key"  type="hidden" value="<?php /* @escapeNotVerified */ echo $block->getFormKey() ?>"  />
<span class="file-uploader-button action-default">Upload CSV file:</span> <input id="image_to_upload" type="file" name="file" required />
<input type="submit" id="import"/>

), function ($) {
     //your code to send ajax request here
    formdata = new FormData();      
    $("#image_to_upload").on("change", function() {
        var file = this.files(0);
        if (formdata) {
            formdata.append("image", file);
                url: "admin/grid/index/index",
                type: "POST",
                data: {dat:formdata,form_key: window.FORM_KEY},

                error:function (request, status, error) {


When I click trigger this function I get below error.

jquery.js:10079 Uncaught TypeError: Illegal invocation

I have this script in the phtml which belongs to the same controller where I post using ajax because I have to show product update progress in the same page. In that controller I will get data like below if ajax works fine. Please note this is the previous working code in my phtml. I want to edit this code for controller standards.

    $objectManager = MagentoFrameworkAppObjectManager::getInstance ();
    $fileSystem = $objectManager->create('MagentoFrameworkFilesystem');
    $mediaPath = $fileSystem->getDirectoryRead(MagentoFrameworkAppFilesystemDirectoryList::MEDIA)->getAbsolutePath();
    $stockRegistry = $objectManager->create('MagentoCatalogInventoryApiStockRegistryInterface');
    $product = $objectManager->get('MagentoCatalogModelProduct');
    if (!file_exists($mediaPath.'csv')) {
        mkdir($mediaPath.'csv', 0777, true);
    $file_type = $_FILES('file')('type'); //returns the mimetype
    $allowed = array('text/csv');
    if(!in_array($file_type, $allowed)) {?>
    <h1 class="error">Only CSV files allowed</h1>
        <td>Wrong format</td>
        <td>Wrong format</td>
        <td>Wrong format</td>
    $displayFlag = 1;
    $csv =  $_FILES('file');    
    $targetdir = $mediaPath;   
    $temp = explode(".", $image_name);
    $newfilename = round(microtime(true)) . '.' . end($temp);
        $csvFile = file($imagepath);
        $data = ();
        foreach ($csvFile as $line) {
            $data() = str_getcsv($line, ",", '"');
        var_dump( count($data));
        $keys = ();
        $result = ();
        foreach($data as $key => $value){
            if($key == 0){
                $keys = $value;
        foreach($data as $key => $value){
            if($key !== 0){
                $result() = array_combine($keys, $value);
        foreach($result as $key => $value){
            if($product->getIdBySku($value('sku'))) {
                $stockItem = $stockRegistry->getStockItemBySku($value('sku'));
                $sku = $value('sku');            
                if($stockRegistry->updateStockItemBySku($sku, $stockItem)){                
                        <td><?php echo $value('sku') ?></td>
                        <td><?php echo $value('qty') ?></td>
                        <td><?php echo $value('sku') ?></td>
                        <td><?php echo $value('qty') ?></td>
            }else{ ?>
                        <td><?php echo $value('sku') ?></td>
                        <td><?php echo $value('qty') ?></td>
                        <td>Sku Not found</td>

c# – consultar una list usando Ajax

estoy tratando de cargar una modal con unos datos especificos de un usuario seleccionado de una tabla.

Tengo una tabla donde se muestra una lista de usuarios, al darle a un boton me debe cargar una modal con la lista de propiedades las cuales posee ese usuario.

El id del usuario llega al controlador y hago la consulta de los datos que quiero, en el controlador puse un punto de quiebre y puedo ver la lista de propiedades del usurio, el problema es que me da error en la function jquery al querer recibir esos datos.

Asi lo tengo en el controlador:

    public ActionResult listaComunidades()
            long userId = (long)Session("idTitular"); //Aqui esta almacenado el Id del usuario ya captado por el conrolador
            List<Titulo> titulosList = new List<Titulo>();
            List<community> listComunities = new List<community>();
            titulosList = ep.GetTitulosByTitular(userId);
            listComunities = ep.GetCommunityListByTitular(titulosList);
            return Json(new { result = listComunities });
        catch (Exception ex)
            return Json(new
                data = "error",
                exception = ex.HResult

Y este es mi codigo en jquery

function onCommunitiesList() { 
        var url = "@Url.Action("listaComunidades", "titulares", new { area = "webmaster" })";
        var errUrl = "@Url.Action("listado", "titulares", new { area = "webmaster", Error = "No se pudo procesar la solicitud."})";
    url: url,
    cache: false,
    type: 'POST',        
    success: function (result) {     // aqui no recibo nada o no se como puedo hacer que llegue la lista desde el controlador
                if (data != null) {
                    //listCommun = data;
                    //var t = $('.tablaComunidadesSe').DataTable();
                    //for (var i = 0; i < data.length; i++) {
                    //    t.row.add((
                    //        data(i).Id,
                    //        data(i).first_name,
                    //    )).draw(false);
                } else {
                    window.location = errUrl;
    processData: false,
            contentType: false

ajax – How do I mitigate replay attacks when talking about actions that shouldn’t happen twice?

A nonce is supposed to first help me against CSRF and help against replay attacks is just a bonus if I “personalize” the nonce to something like pay-user-{id}, but here’s the problem – if my link looked like /wordpress/admin_ajax.php?action=pay-user&id=20&security=ej3548 I have 2 cases to take care of:

  1. I created a nonce without the specific user ID, pay-user – if an attacker obtains the nonce, he can make me click that link and pay any user.
  2. I created a nonce with the specific user ID, pay-user-{id} – if an attacker obtains the nonce, he can only make me replay that request, since the nonce was made to verify that specific (to {id}) action.

But that’s still an issue in a lot of cases, paying someone is a prime example. I can’t be made to pay someone else, but if I make that request 10 times, I’ll pay that specific person 10 times.

Is there no specific “per request” hashing?

What to do?

javascript – Ajax parallel requests and callback()

I wrote this function to retrieve json data simultaneously and callback when the last request finishes.
Is this approach correct?

var mydata = {}

function getData(callback) {

    var requests = 3 // # of ajax request. When 0, callback()

    $.getJSON("/data1", function(data) {
        mydata.d1 = data || ()
        if (--requests === 0 ) callback()
    $.getJSON("/data2", function(data) {
        mydata.d2 = data || ()
        if (--requests === 0 ) callback()
    $.getJSON("/data3", function(data) {
        mydata.d3 = data || ()
        if (--requests === 0 ) callback()

php – Problema enviando datos desde un formulario cargado con ajax

estoy programando una pagina web para abm de una base de datos y tengo problemas para la parte de modificar. Lo que hice fue cargar una tabla usando ajax. Dentro de la tabla cargo cada fila de datos como formularios independientes, el id del formulario es una combinacion entre el id de la empresa y el id del contacto a modificar desde la base de datos.
Sin embargo al darle actualizar carga la pagina de modificacion pero no recibe los datos enviados por el formulario. Dejo los codigos que uso:
Codigo en javascript para enviar el formulario

function actualizar(idempresa, idcontacto){  
            var sidempresa = idempresa.toString();
            var sidcontacto = idcontacto.toString();
            var idform = "empresa"+sidempresa+"contacto"+sidcontacto;

Formulario HTML:

<form method="POST" action="actualizar.php" id="---">
<input type="hidden" name="empresaId" value="---">
<input type="hidden" name="contactoId" value="---">
<input type="text" name="nombreEmpresa" id="nombreEmpresa" class="form-control" value="Nombre empresa"></td>
<input type="text" name="nombreContacto" id="nombreContacto" class="form-control" value="nombre-contacto"></td>
<input type="text" name="mail" id="mail" class="form-control" value="mail-de-contacto"></td>
<input type="text" name="telefono" id="telefono" class="form-control" value="telefono-de-contacto">
<input type="submit" class="btn btn-outline-light" name="actualizar" value="actualizar" onclick="actualizar(idempresa,idcontacto)">

Utilice la herramienta de inspeccion de google para ver los datos enviados hacia la pagina de actualizacion y no envia ningun dato. tambien utilice un Alert para comprobar que la funcion recibe bien los parametros y los recibe sin problemas.

Why WordPress plugin url ajax doesn’t work?

I need to send information to the plugin folder via ajax. WordPress has a function for the link “plugin_dir_url (__ FILE__)” which works properly but if I put it in ajax it doesn’t work.

Function: plugin_dir_url (__ FILE__) = http: // localhost / aa / wp-content / plugins / pluginfolder /

This works normally:

var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

        };"GET", "http://localhost/aa/wp-content/plugins/pluginfolder/wp-getinfo.php?"&SENDINFO=sendinfo, true);

This does not work (php inside url):

var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

        };"GET", ""+<?php echo plugin_dir_url(__FILE__) .?>+" wp-save.php?"&SENDINFO=sendinfo, true);

This does not work (php url as variable):

var urlwp = <?php echo plugin_dir_url(__FILE__) . 'wp-getinfo.php?' ?>;

var xmlhttp = new XMLHttpRequest();
        xmlhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

        };"GET", ""+urlwp+"&SENDINFO=sendinfo, true);

What is the correct way to call a PHP Function with multiple parameters from the AJAX Handler?

Q: What is the correct way to call a PHP Function with multiple parameters from the AJAX Handler?

Q: Am I calling the php function correctly?

Page Element
The user clicks a button.

The click should connect to an external server using the following params:

  1. User Name 2. IP Address 3. Port 4. Public Key 5. Service

Send an vote string (from host A) to an external Gaming server (host B).
I do not need to update any wordpress content.

WordPress Version: 5.4.1
I put my custom php code into “/wp-contents/plugins/my-plugin/votifier.php”

I made sure the custom plugin is activated.

I have WordPress in Debug mode. i.e. Debug mode is true.

The Button

<div id="frm_field_61_container">
<button type="button">Try it</button>

WordPress JQuery with AJAX

jQuery(document).ready( function($) {


         type : "post",

         dataType : "json",

         url : myAjax.ajaxurl,

         data : {    action: "my_vote_count"
                    ,username: $('input(name="item_meta(59)")').val()
                    ,key: $.trim($("#field_yjr62").val())
                    ,ip: $('input(name="item_meta(40)")').val()
                    ,port: $('input(name="item_meta(42)")').val()
                    ,service: "Votifier"

        success:    function(data,status,xhr){
                    alert("Data: " + data);
                    alert("Status: " + status);
                    alert("xhr: " + xhr);

My Custom PHP Script


function mainVotifier($username, $public_key, $server_ip, $port, $service_name) {

define( 'VOTE_FORMAT', 'VOTEn%sn%sn%sn%dn' );
define( 'PUBLIC_KEY_FORMAT', '-----BEGIN PUBLIC KEY-----n%sn-----END PUBLIC KEY-----' );

$key    = wordwrap($public_key, 65, "n", true);
$key    = sprintf(PUBLIC_KEY_FORMAT, $key);

  if (php_sapi_name() !== 'cli') {
            //Detect proxy and use correct IP.
            $address = isset($_SERVER('HTTP_X_FORWARDED_FOR')) ? $_SERVER('HTTP_X_FORWARDED_FOR') : $_SERVER('REMOTE_ADDR');
        } else {
            //Script is run via CLI, use server name.
            $address = $_SERVER('SERVER_NAME');

    $data = sprintf(VOTE_FORMAT, $service_name, $username, $address, time());
    openssl_public_encrypt($data, $crypted, $key);
    $socket = @fsockopen($server_ip, $port);

    if ($socket) {
        if (fwrite($socket, $crypted)) {
            return true;



/* ===== WP_ENQUEUE SCRIPTS ==== */

/* ===== JQuery Ajax Script to call votifier.php ==== */
add_action( 'wp_enqueue_scripts', 'my_script_enqueuer' );
function my_script_enqueuer() {

   wp_enqueue_script( 'my_voter_script',  plugins_url('sendvote.js', __FILE__), array( 'jquery'),   '1.0', true);

   wp_localize_script( 'my_voter_script', 'myAjax', array( 'ajaxurl' => admin_url( 'admin-ajax.php' )));


/* ===== My AJAX Handler ==== */

/* add_action( 'wp_ajax_nopriv_my_vote_count', 'my_ajax_handler' ); */ 
add_action( 'wp_ajax_my_vote_count', 'my_ajax_handler');
function my_ajax_handler() {

/*  check_ajax_referer('votifier_response_key'); */

    $username       = $_POST("username");
    $public_key     = $_POST('key');
    $server_ip      = $_POST("ip");
    $port           = $_POST("port");   
    $service_name   = $_POST("service");

   echo "mainVotifier("" . $username . "", "" . $public_key . "", "" . $server_ip . "", "" . $port . "", "" . $service_name . "");";

    wp_die(); // All ajax handlers die when finished


Console Results

The console results are good, but the other server is not responding.
I tested the PHP code locally from my personal computer and Server B is responding.

Request URL:
Request Method:POST
Remote Address:
Status Code:

filters – post value to function with Ajax and jQuery

This is how you would create a custom smart tag in wp forms:

function ea_custom_smart_tags( $content, $tag ) {
    if( 'my_smart_tag' == $tag ) {
        $value = 'Testing 1 2 3';
        $content = str_replace( '{' . $tag . '}', $value, $content );
    return $content;
add_filter( 'wpforms_smart_tag_process', 'ea_custom_smart_tags', 10, 2 );

I want to post a value via ajax instead of hard coding it.

My jQuery/ajax:

    type: 'POST',
    url: 'http://localhost:8888/mywebsite/wp-admin/admin-ajax.php',
    data: {
        action: 'my_action',
        theTotal: newTotal
}).success(function (result) {

My functions.php:

function my_action_callback($content, $tag){

if ( 'total' === $tag ) {

 $total = $_POST('theTotal');

 $content = str_replace( '{total}', $total, $content );


return $content;
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_filter( 'wpforms_smart_tag_process', 'my_action_callback', 10, 2 );

This is however giving me an error:

Uncaught ArgumentCountError: Too few arguments to function
my_action_callback(), 1 passed in and exactly 2 expected

Magento2: How to add qty increment/decrement in with ajax product update in order review page?

I want to add increment/decrement option in order review summary section.
According to increment/decrement option product should be update same time.
I have checked files and path is web/template/summary/item/details.html
It is using knockout js for displaying quantity only.
How can do that. Anyone have an idea for that please?