Home > jquery > Passing variable data from external jQuery file to options.php

Passing variable data from external jQuery file to options.php

October 5Hits:1
Advertisement

I'm setting up a plugin that requires passing of a variable from a stand alone jQuery file to options.php. I have (I think) set up the scripts to be used in my plugin file like so:

function ndw_js_init(){     wp_enqueue_script('jquery');     wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );     wp_enqueue_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array(), '1.0.0', true);     $scriptdata = array('admin_ajax' => admin_url( 'admin-ajax.php' ));     wp_localize_script( 'ndw_js', 'toremove', $scriptdata); } add_action('admin_init', 'ndw_js_init'); 

Where I am coming unstuck is in the jQuery file. The variable is passed onclick. So far I have this which works fine (tested using an alert()):

$('tr td .widget-remove a').click(function(){      var toremove = $(this).attr('rel');      var url = 'options.php'; // EDIT: Actualy, is this right? Or should the data be passed to the name of my plugin main page I wonder      // Out of ideas }); 

So what I need is help to use the correct AJAX syntax to pass the value of var 'toremove' to 'options.php' and then do something in 'options.php' using the value of 'toremove'.

Hope that makes sense!

EDIT No.1:

OK, so after playing with different settings provided by all of you I have a (semi) functional script:

function ndw_js_init(){     wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );     wp_enqueue_script( 'ndw_js' ); // not working without this     wp_localize_script( 'ndw_js', 'toremove', array('ajaxurl' => admin_url( 'admin-ajax.php' ))); } add_action('admin_init', 'ndw_js_init'); 

Without these settings as they are nothing works. In my external js file I now have:

$('tr td .widget-remove a').click(function(){         var toremove = $(this).attr('rel');         $.ajax({             type: 'POST',              dataType: 'json',             url: ajaxurl,              data: {                 nonce : toremove.nonce,                 toremove : toremove             },             complete: function( data ){                 alert(toremove + " ding!");             }         });     }); 

This works - but only the jQuery code. In the Admin area on my plugin settings page the alert fires on click with the correct id no and the word 'ding!'.

Back to my plugin settings page and I add this (thanks @MMK):

function ndw_ajax_function(){                 $toremove = $_POST['toremove'];     echo "To remove: " . $toremove; }  add_action('wp_ajax_my_ajax_action', 'ndw_ajax_function' ); 

This does not work, I view the generated source and the echoed line does not appear. However, I am not sure in that last add action what wp_ajax_my_ajax_action refers to.

Answers

May i suggest:

$('tr td .widget-remove a').click(function(){
    var toremove = $(this).attr('rel');
    // Out of ideas     -     you shouldn't really be for we are here!
    $.ajax({
        type: 'POST',         // use the method you want
        dataType: 'json',
        url: ajaxurl,        // this is the url to the admin ajax script
        data: {
            nonce : your_script_data_object.nonce,
            toremove: toremove
        },
        complete: function( object ){
            // do what you want here when the ajax requests completes
        }
    });
});

Now in your plugin somewhere you will have to have a function that intercepts the data that your are sending. You should just make sure you are adding your ajax intercept function to the right action hook in wordpress. Here's how you can do it.

Here is the non-oop way.

add_action('wp_ajax_my_ajax_action', 'my_ajax_function' );

And here the oop way.

add_action('wp_ajax_my_ajax_action', array( $this, 'my_ajax_function' ) );

Here is the function:

function my_ajax_function(){
    // do what you want here - the world is open to you
    $toremove = $_POST['toremove'];
    // Any other thing you want to do
    wp_send_json_success( array( 'AnyDataYouWantToSend' => $your_data ) );
}

If you encounter any error in my_ajax_function then use wp_send_json_error in place of wp_send_json_success.

I also noted one unusual thing. Why are you using wp_register_script and wp_enqueue_script on the same script. Here is something you can do. Remove the wp_register_script line and let your function look like this:

function ndw_js_init(){
    wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'ndw_js' );
    wp_localize_script( 'ndw_js', 'toremove' );
}
add_action('admin_init', 'ndw_js_init');

You don't need the $scriptdata variable you were using since as i told you the ajaxurl javascript variable already gives you access to the admin ajax url. That is only if you are in the admin. On the frontend make sure your $scriptdata var is present as the parameter for wp_localize_script

You don't need this line too:

wp_enqueue_script('jquery');

This is because you are already telling Wordpress that your script requires jquery in the dependencies array parameter array( 'jquery' ).

Hope that helps.

OK, I got this working like so:

Step One: Main Plugin File

function ndw_js_init(){
    wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
    wp_enqueue_script( 'ndw_js' );
    wp_localize_script( 'ndw_js', 'removeid', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action('admin_init', 'ndw_js_init');

Step Two: External JS File

$('tr td .widget-remove a').click(function(){
    var toremove = $(this).attr('rel');
    $.ajax({
        url: removeid.ajaxurl,
        data:{
            'action' : 'ndw_ajax_function',
            'passiton' : toremove
        },
        success: function( data ){
            $('.widget-remove').html(data);
        }
    });
});

Step Three: Back in Main Plugin File

function ndw_ajax_function(){
    $toremove = $_REQUEST['passiton'];
    echo $toremove;
    die();
}
add_action('wp_ajax_ndw_ajax_function', 'ndw_ajax_function' );
add_action( 'wp_ajax_nopriv_ndw_ajax_function', 'ndw_ajax_function' );

This works just fine. Thank you for your help, its greatly appreciated.

Related Articles

  • Passing variable data from external jQuery file to options.phpOctober 5

    I'm setting up a plugin that requires passing of a variable from a stand alone jQuery file to options.php. I have (I think) set up the scripts to be used in my plugin file like so: function ndw_js_init(){ wp_enqueue_script('jquery'); wp_register_scri

  • How to trigger a form and pass variables to $form_state with jQuery?November 11

    What is the best way to trigger a drupal form via js/jQuery? And pass new values to the form_state while doing so. My use case is the following: I have a main form, which has an element that triggers a jQuery.ui dialog with a form in it. When submitt

  • Pass variable between two different html file February 10

    This question may be common question. But this is my exact problem. I am not going to write my code, but explain the scenario. I have 2 html files to get value from user and 1 php file to process request from 2 html files through XHR. first html file

  • How to pass form data to external php scriptDecember 18

    I need to pass a value from a form to an external php script via a url, but my code isn't working. When I submit my form, I'm expecting the url to look like this: example.com/script.php?zip=12345 but what I'm getting is this: example.com/script.php?

  • TikZ external Library and pgfplots reading data from external txt file September 3

    Is it possible to use the TikZ/external library and have pgfplots recreate a figure when a data file that is plotted changes? Say I have something like the following: file.tex: \documentclass{article} \usepackage{tikz,pgfplots} \usetikzlibrary{extern

  • How do I add an associative array to a variable from an external ini file?August 11

    I'm modifying a simple script to add function and learn more about how to write bash scripts. Currently, the script creates associative arrays using a function: declare -A site theme add_site() { local shortcut=$1 site[$shortcut]=$2 theme[$shortcut]=

  • Is it possible to pass variables to WordPress externally?February 9

    I would like to know if it is possible to pass json variables from a form which is located outside WordPress? This is the situation: The user fills a form located on x server. Then his answers are sent to the WordPress site located in Y server in whi

  • Is it possible to pass a date from one Advance Custom Fields options page to another?May 14

    I have been trying for a week now to figure this out. I have a site that has numerous ACF options pages. On one options page (Trade Show Details) the start and end dates for a trade show are entered. On a second options page show attendees are entere

  • Passing variables to JS from theme folder .tpl filesFebruary 5

    I use many template files in my modules via hook theme. In order to pass variable to JS files I use the method described here: https://www.drupal.org/node/304258 in the .tpl.php files: $my_settings = array( 'basePath' => $base_path, 'animationEffect'

  • PHP Session variable in external JS file is nullFebruary 2

    I am trying to get a PHP session variable into an external JS file. In the JS file, I want to read and use the value of the session variable, but also assign a new value to the Session variable. I tried this : php file: <?php session_start();?> <

  • How to get data from external JSON with Ionic?January 27

    Currently i'm developing an app using Ionic Framework. I need to get data from external JSON file using token and parameter (1 for premium or 2 for basic) The URL display data correctly, but i don't understand how to get data from my "pageCtrl".

  • How to store backup data on External Hard Drive by testdisk?September 20

    I want to recover my lost Laptop Hard Drive data by testdisk software and want to store on my 1TB External Seagate External HDD . But while use testdisk , there is no option to store recovered data on external HDD. Only options are the Laptop folders

  • Passing variables from external bash file not behaving as expectedJanuary 26

    I have a bash script that's using rsync to backup some files from my local desktop to a remote machine on my LAN. I have the main script with some customisable variables in a separate .sh file to make for easy maintenance, deployment and git manageme

  • Reload data from external file periodically with jQueryJanuary 28

    I have a file (mycompliments.js) looking like this: var mycompliments = { interval: 2000, fadeInterval: 4000, morning: [ 'Good morning, handsome!', 'Enjoy your day!', 'How was your sleep?' ], afternoon: [ 'etc' ], evening: [ 'wopwopppwpwepwe' ] } At

  • How to pass variable from jade template file to a script file?January 2

    I'm having trouble with a variable (config) declared in a jade template file (index.jade) that isn't passed to a javascript file, which then makes my javascript crash. Here is the file (views/index.jade): h1 #{title} script(src='./socket.io/socket.io

  • control a bash script with variables from an external fileJanuary 6

    I would like to control a bash script like this: #!/bin/sh USER1=_parsefromfile_ HOST1=_parsefromfile_ PW1=_parsefromfile_ USER2=_parsefromfile_ HOST2=_parsefromfile_ PW2=_parsefromfile_ imapsync \ --buffersize 8192000 --nosyncacls --subscribe --sync

  • Cannot pass variable to js file October 22

    I cannot pass variable to js file, from my common.module $max_length = 10; //variable_get('title_max_length'); drupal_add_js(drupal_get_path('theme', 'myTHEME'). '/js/script.js'); drupal_add_js(array('common' => array('max' => $max_length)), array('

  • In jquery use php variable to execute an enqueued jquery fileAugust 2

    I am loading some jquery on a specific Wordpress admin page, the jquery loads and works fine but I need have this jquery only trigger if a php variable exists. In php I would just write a function and hook it into the admin page: I am enqueuing the j

  • pass from my php code a value to my jquery fileApril 6

    I want to pass from my php code a value to my jquery file(both in a plugin code). I managed to do it with simple variables with wp_localize_script() but I'm stack with passing class value(that should be used as a selector in the jquery). Can somone h

  • jQuery - Passing data from a jQuery function to a specific div?January 22

    I'm trying to pass data from a function to a specific div, but I can't seem to be able to get this to work. I'm making a gallery viewer and I just want to pass the counter that I use to show the pictures and the total number of files for each gallery

Copyright (C) 2017 ceus-now.com, All Rights Reserved. webmaster#ceus-now.com 14 q. 1.234 s.