最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

update_post_meta using ajax

matteradmin10PV0评论

I have this code but its not working. How can i make it work thanks!

HTML:

<form id="updateAmountOffered" class="amountOffered" method="post" action="">

    <label for="amount">Amount Offered:</label>
    <div class="flex">
        <span class="currency">$</span>
        <input id="amount" class="inpAmount" type="text" maxlength="15" />
        <input type="hidden" name="action" value="updateAmountOffered" />
        <button type="submit" class="btnSubmit">
        <span>
        <span>
        <i class="fa fa-check"></i>
        </span>
        <span>Accept</span>
        </span>
      </button>
    </div>
  </form>

PHP:

function updateAmountOffered(){

$amount = $_POST["inpAmount"];
$post_id = '27030';

update_post_meta($post_id, 'amount', $amount);

die();
}
add_action('wp_ajax_updatemeta', 'updateAmountOffered');
add_action('wp_ajax_nopriv_updatemeta', 'updateAmountOffered');

JS:

<script type="text/javascript">
(function($, undefined) {

"use strict";

// When ready.
$(function() {

    var $form = $( "#updateAmountOffered" );
    var $input = $form.find( "input" );

    $input.on( "keyup", function( event ) {


        // When user select text in the document, also abort.
        var selection = window.getSelection().toString();
        if ( selection !== '' ) {
            return;
        }

        // When the arrow keys are pressed, abort.
        if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
            return;
        }


        var $this = $( this );

        // Get the value.
        var input = $this.val();

        var input = input.replace(/[\D\s\._\-]+/g, "");
                input = input ? parseInt( input, 10 ) : 0;

                $this.val( function() {
                    return ( input === 0 ) ? "" : input.toLocaleString( "en-US" );
                } );
       } );

    /**
     * ==================================
     * When Form Submitted
     * ==================================
     */
    $form.on( "submit", function( event ) {

        var $this = $( this );
        var arr = $this.serializeArray();

        for (var i = 0; i < arr.length; i++) {
                arr[i].value = arr[i].value.replace(/[($)\s\._\-]+/g, ''); // Sanitize the values.
        };

        $.ajax({
type: "POST",
url: "/wp-admin/wp-admin/admin-ajax.php",
data: updateAmountOffered,
error: function(jqXHR, textStatus, errorThrown){                                        
    console.error("The following error occured: " + textStatus, errorThrown);                                                       
},
success: function(data) {                                       
    console.log("Hooray, it worked!");                                                                  
}                              
 });

        console.log( arr );

        event.preventDefault();
    });

});
 })(jQuery);
 </script>

I have this code but its not working. How can i make it work thanks!

HTML:

<form id="updateAmountOffered" class="amountOffered" method="post" action="">

    <label for="amount">Amount Offered:</label>
    <div class="flex">
        <span class="currency">$</span>
        <input id="amount" class="inpAmount" type="text" maxlength="15" />
        <input type="hidden" name="action" value="updateAmountOffered" />
        <button type="submit" class="btnSubmit">
        <span>
        <span>
        <i class="fa fa-check"></i>
        </span>
        <span>Accept</span>
        </span>
      </button>
    </div>
  </form>

PHP:

function updateAmountOffered(){

$amount = $_POST["inpAmount"];
$post_id = '27030';

update_post_meta($post_id, 'amount', $amount);

die();
}
add_action('wp_ajax_updatemeta', 'updateAmountOffered');
add_action('wp_ajax_nopriv_updatemeta', 'updateAmountOffered');

JS:

<script type="text/javascript">
(function($, undefined) {

"use strict";

// When ready.
$(function() {

    var $form = $( "#updateAmountOffered" );
    var $input = $form.find( "input" );

    $input.on( "keyup", function( event ) {


        // When user select text in the document, also abort.
        var selection = window.getSelection().toString();
        if ( selection !== '' ) {
            return;
        }

        // When the arrow keys are pressed, abort.
        if ( $.inArray( event.keyCode, [38,40,37,39] ) !== -1 ) {
            return;
        }


        var $this = $( this );

        // Get the value.
        var input = $this.val();

        var input = input.replace(/[\D\s\._\-]+/g, "");
                input = input ? parseInt( input, 10 ) : 0;

                $this.val( function() {
                    return ( input === 0 ) ? "" : input.toLocaleString( "en-US" );
                } );
       } );

    /**
     * ==================================
     * When Form Submitted
     * ==================================
     */
    $form.on( "submit", function( event ) {

        var $this = $( this );
        var arr = $this.serializeArray();

        for (var i = 0; i < arr.length; i++) {
                arr[i].value = arr[i].value.replace(/[($)\s\._\-]+/g, ''); // Sanitize the values.
        };

        $.ajax({
type: "POST",
url: "/wp-admin/wp-admin/admin-ajax.php",
data: updateAmountOffered,
error: function(jqXHR, textStatus, errorThrown){                                        
    console.error("The following error occured: " + textStatus, errorThrown);                                                       
},
success: function(data) {                                       
    console.log("Hooray, it worked!");                                                                  
}                              
 });

        console.log( arr );

        event.preventDefault();
    });

});
 })(jQuery);
 </script>
Share Improve this question asked Oct 17, 2018 at 2:26 rjm_wdrjm_wd 111 bronze badge 3
  • This looks suspect: data: updateAmountOffered, I don't see where that gets set anywhere. – Milo Commented Oct 17, 2018 at 3:25
  • data needs to be an object that requires an action attribute with your function, that you want to call in wp-admin, so it should read: data: {action: 'updatemeta'} you could add more attributes in there, f.ex. a nonce to make a security check or some ID or whatever you like. try to google wordpress ajax and you'll find plenty of solutions that will get you started.. this manual looks good for a start.. and your url looks weird too: 2 times wp-admin inside /wp-admin/wp-admin/admin-ajax.php? – honk31 Commented Oct 17, 2018 at 14:41
  • @honk31Thank you so much! The manual you gave me solved my problem. – rjm_wd Commented Oct 18, 2018 at 2:13
Add a comment  | 

1 Answer 1

Reset to default 0

You didn't set a name attribute in your input tag with the id = "amount". Set the name as "inpAmount" and try again.

<input id="amount" class="inpAmount" type="text" maxlength="15" />

should be

<input id="amount" class="inpAmount" type="text" maxlength="15" name="inpAmount" />

As previously mentioned, the path to admin-ajax.php looks wrong as well.

The wp_ajax nomenclature is also incorrect. The actions suffix needs to match the value of the input with the name attribute set to "action."

Should be:

add_action('wp_ajax_updateAmountOffered', 'updateAmountOffered');
add_action('wp_ajax_nopriv_updateAmountOffered', 'updateAmountOffered');

Articles related to this article

Post a comment

comment list (0)

  1. No comments so far