-1

On my single-product.php page, I have a dropdown select. There's also a button on the page to save the post to your favorites. Is there a way I can update the post's meta information with the currently selected value from the dropdown when the favorite button is clicked with something like below?

update_post_meta( get_the_ID(), 'newcolor', $value );
Joshua
  • 40,822
  • 8
  • 72
  • 132
PaulC
  • 185
  • 1
  • 1
  • 8

1 Answers1

0

Of course. You will need to use AJAX here, which will allow you to run a PHP script without refreshing this page.

First, you need to create a new PHP script, called add_favorite.php which will contain :

$id = $_POST['id'];
update_post_meta($id, 'newcolor', $value); 

Then you can use the $.ajax() function from jQuery to call this script asynchronously and update the post meta in the database. On return, you will be able to change with javascript a specific element of your HTML to reflect the change (added to favorites).

request = $.ajax({
    url: "add_favorite.php",
    type: "post",
    data: // send the id here
});

// Callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
    console.log("Hooray, added to favorites!");
});

See this answer to learn how to send AJAX data : jQuery Ajax POST example with PHP

This is from jQuery API documentation. Data can be of type string or Array. Use array if multiple values ['id'=> $id] :

data
Type: PlainObject or String or Array
Data to be sent to the server. It is converted to a query string, if  not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).

http://api.jquery.com/jquery.ajax/

Community
  • 1
  • 1
BassMHL
  • 8,523
  • 9
  • 50
  • 67