Support

Account

Home Forums General Issues Use update_field() with AJAX

Solved

Use update_field() with AJAX

  • Hi, I was wondering if there was a clean method where I could use “update_field” via AJAX?

    Essentially I have a form where the user can enter the desired name for the gallery:

    HTML

    <form id="galleryTitle" action="updatetitle.php">
    <input type="hidden" name="pageid" value="<?php echo get_the_ID(); ?>">
    <input type="hidden" name="olttitle" value="<?php the_field('gallery-title'); ?>">
    Change Gallery Title: <input type="text" name="newtitle" value="<?php the_field('gallery-title'); ?>">
    <input type="submit" value="Change Title">
    </form>

    Then have a php function that calls “update_field()”, like so:

    PHP

    $pageid = $_POST['pageid'];
    $oldtitle = $_POST['oldtitle'];
    $newtitle = $_POST['newtitle'];
    
    if (!isset($newtitle)) { $newtitle = $oldtitle; }
    
    update_field('gallery-title', $newtitle, $pageid);
    
    //TODO: Some sort of json_encode

    Then have a jQuery ajax function do something along these lines:

    jQuery

    var form = "#galleryTitle";
    $(form).submit(function(event) {
      event.preventDefault();
      $.ajax({
        url: $(form).attr('action'),
        type: 'post',
        data: $(form).serialize(),
        success: function(data) {
          // TODO: What is this?!
          if(typeof(data) != 'object') {
            data = JSON.parse(data);
          }
          if (data.success) {
            console.log("Title has been updated");
          } else {
            console.log("Title was NOT updated");
          }
        }
      });
    });

    There seems to be a million different ways to call AJAX, but it’s very new territory for me and I can’t seem to get further than this. I know the PHP file is being actioned, but the update_field() doesn’t do anything unless it’s directly on the page it’s trying to update.

    Any ideas?

    Thanks,

    Mark

  • In order to have access to WP functions in ajax you need to use it the way that WP considers “proper”. Your need to make all ajax requests through admin-ajax.php.

    The best information on using ajax in WP can be found here: http://codex.wordpress.org/AJAX_in_Plugins

    All the information about functions and add_actions and so forth can be used in your functions.php file as well as it can be used in a plugin.

  • Thanks Hube2, you’re spot on. This is what worked for me:

    I have a text input with the “Field Group” set as ‘test’

    HTML

    <form id="test-form" action="">
      <input type="text" name="input-test" value="<?php the_field('test'); ?>">
      <input type="submit" value="Update">
    </form>

    PHP (In the themes function.php file)

    function test_function() {
      // Set variables
      $input_test = $_POST['input-test'];
      // Check variables for fallbacks
      if (!isset($input_test) || $input_test == "") { $input_test = "Fall Back"; }
      // Update the field
      update_field('test', $input_test);
    }
    add_action( 'wp_ajax_nopriv_test_function',  'test_function' );
    add_action( 'wp_ajax_test_function','test_function' );

    Javascript

    var ajaxurl = 'http://'+window.location.host+'/wp-admin/admin-ajax.php';
    var form = "#test-form";
      $(form).submit(function(event) {
        event.preventDefault();
        $.ajax({
          url: ajaxurl + "?action=test_function",
          type: 'post',
          data: $(form).serialize(),
          success: function(data) {
            console.log("SUCCESS!");
          },
          error: function(data) {
            console.log("FAILURE");
          }
        });
      });
  • @marknotton Not to be nitpicky, but please localize your Ajax URL!

    as such:

    wp_localize_script('my_js_scripts', 'MyAjax', 
         array(
             'ajaxurl' => admin_url('admin-ajax.php'), 
    	 'postCommentNonce' => wp_create_nonce('myajax-post-comment-nonce')
         )
    );
    
  • Hello,
    I’m testing how to update a Custom Text Field using an input form as it is shown here, so I have followed these instructions, which are pretty clear.
    I don’t get an Error, I get the message ‘Success’ when I hit the update button.
    However, the field does not update.
    Any ideas on what could be the problem? I’m very new at Ajax so it could be something trivial.

Viewing 5 posts - 1 through 5 (of 5 total)

The topic ‘Use update_field() with AJAX’ is closed to new replies.