Skip Navigation

[Resolved] Custom code not executing when triggered through JS/JQuery

This support ticket is created 5 years, 2 months ago. There's a good chance that you are reading advice that it now obsolete.

This is the technical support forum for Toolset - a suite of plugins for developing WordPress sites without writing PHP.

Everyone can read this forum, but only Toolset clients can post in it. Toolset support works 6 days per week, 19 hours per day.

Sun Mon Tue Wed Thu Fri Sat
- - 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00 14:00 – 20:00
- - - - - - -

Supporter timezone: Asia/Ho_Chi_Minh (GMT+07:00)

This topic contains 5 replies, has 2 voices.

Last updated by Beda 5 years, 1 month ago.

Assisted by: Beda.

Author
Posts
#1364479
ss002.JPG
ss001.JPG

I am trying to:

I'm having the same issue with two similar views, I'll use the more involved example for this ticket. I'm creating a pos system for a gentlemen's club, and there is a view that shows all dances for that day (Screenshot001), you can filter the dances by entertainer, then I used some JS with an onclick event to add up the total cash paid which is working fine, but there is a second button that is supposed to allow the user to mark the dances as paid (Screenshot002).

By clicking the "Mark Paid" button, the JS calls a custom PHP snippet that is stored in the toolset custom code section. The JS appears to work correctly and even displays the success message, but the status never gets updated to "Paid", so it looks like the PHP function is not firing correctly, but it is echoing back a null value which is seen as a response so the JS sees the function as completed without errors.

JS Code from the view:


function markPaid(index) {
  columnTh = $("table th:contains('ID')");
  columnIndex = columnTh.index() + 1;
  var arr = []; 
  $('table tr td:nth-child('+ columnIndex +')').each(function(index, element) {
		var text = $(element).html();
         var value = parseInt(text);
    
    	arr.push(value);
    	//alert(value);

      });
  //alert(arr);
  var jsonString = JSON.stringify(arr);
  alert(jsonString);
     $.ajax({
        type: "POST",
        url:'<em><u>hidden link</u></em>',
        data: { data : jsonString },
        dataType: 'JSON',
        success: function (response) {
			alert(response);
            $('#markPaid').html("These Dances have been marked as paid");
          	location.reload(true, 2);
        },
        error: function () {
          
            $('#markPaid').html("There was an error marking these dances paid");
        },
       
    });
    return false;
}

PHP snippet - name markpaid.php:

<?php
/**
 * New custom code snippet (replace this with snippet description).
 */



// Put the code of your snippet below this comment.


function markpaid() {
    $data = $_POST['data'];


    $array = json_decode("$data", true);


     foreach ($array as $value) {
        //error_log("passed data is: " . $value);
        update_post_meta( $value, 'wpcf-paid', "Paid" );
   
	 }
  
  echo $data;
}


?>

Note that I also attempted to do this by creating individual php files manually and placing them in my child theme folder and pointing to them in the ajax call but that was unsuccessful as well. I had limited success when working on this in my local environment, but none at all on my live server. I'm sure I'm missing something obvious, any help would be greatly appreciated.

Thanks,
Matt

#1364567

We can't help with this sort of customization, this is something that is subject to custom code.
Our Support Policy doesn't include support of such custom code.
https://toolset.com/toolset-support-policy/

I suggest to contact a contractor if you require help for this.

Note that the PHP code, as posted above, will fail if there is no $_POST['data'] (Which is a input field in a form called "data").
If there is no such field in the form or no value, then your subsequent code will fail because it does not check if there is in fact a $_POST['data'].
The foreach would then throw a PHP error in that case, as it tries to foreach over a non-array.
You could avoid that by adding some checks before that foreach (is array, for example).

update_post_meta( $value, 'wpcf-paid', "Paid" ); then, will try to update the Post Meta "wpcf-paid" of each post with ID $value (which comes from the array of $_POST['data']

I am wondering though, how you ensure that $_POST['data'] is an array of Post IDs.
I suspect you maybe have a list or commaseparated ID's in $_POST['data'], hence you'd need to do some more before you have a valid array, a var_dump() of $_POST['data'] would tell.
It's however subject to custom code, we cannot help with this directly.

I finally suggest to consult this post to create proper AJAX calls to your actions, that then can in turn call the PHP Code:
https://wordpress.stackexchange.com/questions/121432/use-an-id-on-a-button-to-update-post-meta-in-post

Thank you for understanding that we cannot be of more help in the Support Forum for Toolset. This is something that the Certified Contractors are best involved, if you require custom help for this.
https://toolset.com/contractors/

A hint:
You could maybe avoid this using a Toolset Form (where you display only a "mark paid" submit button.
The Toolset Form would then edit that post, and update the field to "paid".
Since Toolset Forms can use AJAX submit, it could be a similar experience to the current goal.

Please let me know if you need more information about how to update posts or meta data with Toolset Forms.
You can also consult the Documentation here:
https://toolset.com/documentation/getting-started-with-toolset/publish-content-from-the-front-end/forms-for-editing/

#1365689

Beta,

I appreciate your response, but it seems like you guys are constantly pushing additional contractor services whenever I submit a support request. I'm a long time developer trying to navigate the ins and outs of toolset and what it can and cannot do. Simply paying someone else to do it for me is not at all the point, I'm trying to learn why these things are not working to become as proficient as possible myself. If there are classes or a certification you offer I'd be more than happy to learn as much as possible from you, and potentially become a contractor myself down the road. Please advise on that front if you don't mind 🙂

"Note that the PHP code, as posted above, will fail if there is no $_POST['data']" - Yes absolutely, the code is paired down and the if/else statement was removed for simplicity. I had already tested through alerts and php console log errors to ensure the correct data was being passed in as you'll see in the error log below. You'll also see what appears to be the fatal error in question, it looks like the toolset function 'update_post_meta' is not being recognized for some reason. Is that something you can speak to? Am I missing something I should be including in the file so it recognizes toolset functions? Seems odd that a snippet that I wrote in your editor wouldn't recognize your own function.

"[21-Oct-2019 13:38:21 America/New_York] markpaid function fired
[21-Oct-2019 13:38:21 America/New_York] [218,216,213,206]
[21-Oct-2019 13:38:21 America/New_York] passed data is: 218
[21-Oct-2019 13:38:21 America/New_York] PHP Fatal error: Uncaught Error: Call to undefined function update_post_meta() in C:\wamp64\www\LDPOS\wp-content\toolset-customizations\markpaid.php:24
Stack trace:
#0 {main}
thrown in C:\wamp64\www\LDPOS\wp-content\toolset-customizations\markpaid.php on line 24"

I'm going to keep at it, and will update you if I make any progress.

Thanks,
Matt

#1366149

Well, these are our support policies:
https://toolset.com/toolset-support-policy/

Please read them, to understand why we cannot offer custom code of this kind.
The request of code you have is not related to Toolset.

1. If there are classes or a certification you offer I'd be more than happy to learn as much as possible from you, and potentially become a contractor myself down the road.

In fact we have trainings for aspiring contractors, but you first would need to qualify as one.
That is only possible if your profile qualifies, which I am not sure - but you can see it in your profile when you open the main profile page, if you are qualified for it you will see a message inviting you to participate
See also https://toolset.com/2017/11/toolset-contractors-are-waiting-for-your-projects/#comment-329425

I hope you understand that we cannot train you here in this support forum so later we can send other users to consult you as a contractor.

2. I am actually asking since a while for exactly what you request (paid training for people aspiring to learn more about generic coding, and WordPress) - I believe not only there is a great interest but also (last but not least) a great opportunity for the community if we would proactively train people in custom coding and other things, but - I am not at a position to decide this, and it is not currently the path Toolset goes as a WordPress plugin, or it's support.
I will mention the requirement again to our management and you can always as well ask for changes (even in support) at https://toolset.com/home/contact-us/suggest-a-new-feature-for-toolset/

3. the toolset function 'update_post_meta' is not being recognized for some reason

update_post_meta is not a Toolset function, as much I would like it to be.
The code you use is pure PHP and WordPress API, of which we cannot help here - we can explain and instruct but not debug such custom code or write it for you.
Toolset API has no update_post_meta function.

4. Call to undefined function update_post_meta() in C:\wamp64\www\LDPOS\wp-content\toolset-customizations\markpaid.php:24

That means you call the update_post_meta too soon or at a moment where the core files of WordPress holding that function are not loaded

I suggest to consult the excellent Stackoverflow article I shared with you earlier that shows precisely how to construct such a custom logic where you call a PHP method with JS (basically this is AJAX).
This is not a simple topic, but it will help you to understand how this works and how to set it up in a simple example, which you can then adapt to your custom situation.

I apologies that I cannot be of better help here, at this moment.
Please let me know if you have questions related to Toolset and it's plugins/API, with which I can help much "more in depth".

Thank you for understanding

#1372393

Beda,

I apologize I thought I responded and closed this thread some time ago. I was able to get everything working as needed, your first example provided (https://wordpress.stackexchange.com/questions/121432/use-an-id-on-a-button-to-update-post-meta-in-post) was exactly what I needed. Many thanks for all your help, and I'll update my profile here eventually to see if I qualify to become an aspiring contractor.

Thanks again,
Matt

#1372871

That's great!

I'm happy you could resolve the issue, and please don't hesitate to ask us for assistance in future 🙂
"Despite" our rules we often can help or at least indicate the right path.