简体   繁体   English

用表单替换链接以将变量传递给javascript / ajax-单个脚本

[英]Replace link with form to pass variables to javascript / ajax - single script

I'm sending a single variable to javascript/ajax via a link, but want to send via a form so I can pass user input as well. 我通过链接将单个变量发送到javascript / ajax,但希望通过表单发送,这样我也可以传递用户输入。 (It's for a plugin that interfaces with an Echonest Remix python script to create audio edits). (它是用于与Echonest Remix python脚本交互以创建音频编辑的插件)。 The short question is how can I receive this in a WP ajax javascript: 简短的问题是如何在WP ajax javascript中收到此消息:

<form id="receive_me" method="POST">
Username: <input type="text" name="user_variable">
<input type="hidden" name="generated_var" value="'.$arguments.'">
<input type="submit" value="Submit">
</form>

The JS: JS:

function glitch_player_display(generated_var) {
      jQuery.ajax({
        type: 'POST',
        url: ajaxglitch_playerajax.ajaxurl,
        data: {
          action: 'ajaxglitch_player_ajaxhandler',
          mix_name: mix_name
        },
        success: function(data, textStatus, XMLHttpRequest) {
          var showglitchplayer = '#showglitchplayer';
          jQuery(showglitchplayer).html('');
          jQuery(showglitchplayer).append(data);
        },
        error: function(MLHttpRequest, textStatus, errorThrown) {
          alert(errorThrown);
        }
      });
    }

This is the PHP current: 这是PHP当前:

function glitch_player_show_make_mix(){
    $result = "";
    $generated_var = wp_create_nonce("ajaxloadpost_nonce");
    $arguments = "'".$nonce."'";
    $link = ' <div id="make_button"><a onclick="glitch_player_display('.$arguments.');">'. "Link Title" .'</a></div>';
    $result .= '<h3>' . $link . '</h3>';
    $result .=  '<div id="showglitchplayer">';
    $result .= '</div>';
    $result .= '<div id="play_button"><a title="The Title" href="'.plugin_URL.$generated_var.'.mp3">First Mix</a></div>';
    return $result;
}


add_action( 'wp_ajax_nopriv_ajaxglitch_player_ajaxhandler', 'ajaxglitch_player_ajaxhandler' );
add_action( 'wp_ajax_ajaxglitch_player_ajaxhandler', 'ajaxglitch_player_ajaxhandler' );

function ajaxglitch_player_ajaxhandler(){
    $generated_var = isset( $_POST['generated_var'] )? $_POST['generated_var'] : false;
    error_log( "The generated_var is $generated_var" ); // write it to the error_log too.)

But I'm not sure how to receive the POST to javascript. 但是我不确定如何接收javascript的POST。 Something along these lines? 遵循这些原则?

$('#inputForm').submit(function glitch_player_display(mix_name)

I don't need a second php script do I? 我不需要第二个php脚本吗? I'll be grateful for a point further (or at all) in the right direction. 我将向正确的方向进一步(或根本)表示感谢。

Thanks and stay well. 谢谢,并保持良好。

ANSWER: Based on input below, here ONE OF THE WAYS to send the variable via form: 解答:根据以下输入,此处是通过表格发送变量的一种方式:

<form id="form_id" name="form" method="post">
Field Title: <input type="text" id="user_input" size = 2>
<input type="hidden" id="mix_name" value="'.$arguments.'">
<input id="btn-submit" type="submit" onclick="glitch_player_display()" value="Submit">
</form>

And here's the JS/jQuery 这是JS / jQuery

function glitch_player_display() {
        user_input = document.getElementById("user_input").value ? document.getElementById("user_input").value : 2;
        generated_var = document.getElementById("generated_var").value ? document.getElementById("generated_var").value : "Default_Var";
        $(document).on('submit', '#form_id', function(event){
            event.preventDefault();
        });
        jQuery.ajax({ 
            beforeSend: function() {
                alert(generated_var + " in ajax user_input: " + user_input);
            },
            type: 'POST',
            url: ajaxglitch_playerajax.ajaxurl,
            data: {
                action: 'ajaxglitch_player_ajaxhandler',
                generated_var: generated_var,
                user_input: user_input
            },
            success: function(data, textStatus, XMLHttpRequest) {play_button
                var showglitchplayer = '#showglitchplayer';
                jQuery(showglitchplayer).html('');
                jQuery(showglitchplayer).append(data);
            },
            error: function(MLHttpRequest, textStatus, errorThrown) {
                alert(errorThrown);
            }
        });
    }

Note that we are not sending the variables to the js function glitch_player_display() as we were in the first case. 请注意,我们没有像第一种情况那样将变量发送到js函数glitch_player_display() We are picking it up within the JS function via document.getElementById("user_input").value . 我们正在通过document.getElementById("user_input").value在JS函数中进行选择。 Also

beforeSend: function() {
                alert(generated_var + " in ajax user_input: " + user_input);
            },

Is just a way to test and see what the jQuery.ajax function is actually receiving. 只是测试并查看jQuery.ajax函数实际接收的一种方法。 And since we're not actually calling another script via the submit button, it is necessary to invoke 而且由于我们实际上并不是通过“提交”按钮调用另一个脚本,因此有必要调用

$(document).on('submit', '#form_id', function(event){
            event.preventDefault();
        });

So jQuery (or JS?) doesn't think it should be finding another script and generate an error, which in this case replaced user_variable with [object Object]. 因此,jQuery(或JS?)认为不应找到另一个脚本并生成错误,在这种情况下,该错误将user_variable替换为[object Object]。 The object could be viewed by using console_log() and I think it was a huge error object. 可以使用console_log()查看该对象,我认为这是一个巨大的错误对象。

Your button should call your javascript function with an onclick="" parameter and the javascript function can access the fields using documet.getElementById("fieldname").value to do what you want with it. 您的按钮应使用onclick =“”参数调用javascript函数,并且javascript函数可以使用documet.getElementById(“ fieldname”)。value访问字段以执行所需的操作。 Just give each field an ID="fieldname", replacing "fieldname" with a unique ID for each one, which you then access with document.getElementById(). 只需为每个字段指定一个ID =“ fieldname”,然后用每个字段的唯一ID替换“ fieldname”,然后使用document.getElementById()访问即可。

First to launch the ajax request you need to prevent default behavior of the form submit. 首先启动ajax请求,您需要防止表单提交的默认行为。

$('#inputForm').submit(function(e) {

     // Prevent submitting the form normal way 

     e.preventDefault();

     // Now call the function that handles the ajax request

     glitch_player_display();
})

You need to get the value from the form. 您需要从表单获取值。 You can do it either in your .submit event handler and pass the mix_name to your glitch_player_display(mix_name) function as an argument, or just call glitch_player_display() without arguments and get your value inside this function through jquery. 您可以在.submit事件处理程序中执行此操作,然后将mix_name作为参数传递给glitch_player_display(mix_name)函数,或者仅调用不带参数的glitch_player_display()并通过jquery在此函数内获取值。 Than you're making ajax request to ajaxglitch_playerajax.ajaxurl .. process it on your server-side and return response from there. 比您向ajaxglitch_playerajax.ajaxurl发出ajax请求..在服务器端处理它并从那里返回响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM