We help IT Professionals succeed at work.

Check out our new AWS podcast with Certified Expert, Phil Phillips! Listen to "How to Execute a Seamless AWS Migration" on EE or on your favorite podcast platform. Listen Now

x
Private

How to post value to function with ajax and jQuery

Black Sulfur
Black Sulfur asked
on
High Priority
64 Views
Last Modified: 2020-05-25
I am having to hook into a plugin and I need to actually output a value I get via jQuery. However, when I try to return it (I have to use return) it just escapes the javascript instead of actually giving me the value. So, the output on the screen is literally the text instead of the value ie: <script>document.write(buttontext);</script> instead of some value

<script>
var myValue = jQuery( '.my_value' ).val();
<?php 
     $myValue ="<script>document.write(myValue);</script>";             
 ?>
</script>
<?php
//.... some code.. $myValue ends up in $content which I return below
return $content;
?>

Open in new window

Comment
Watch Question

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:

<span id="____here"></span>    
<script>
   var myValue = jQuery( '.my_value' ).val();
   $("#____here").text(myValue);
</script>
<?php
//.... some code.. $myValue ends up in $content which I return below
return $content;
?>


Author

Commented:
Sorry, maybe I didn't explain properly. I need the php variable to get the value from jQuery and then return that in php.

So, php `$myValue` needs to be set to whatever jQuery `var Myvalue` is. 
Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
Unlock this solution with a free trial preview.
(No credit card required)
Get Preview

Author

Commented:
Alright. I am trying to use ajax but having a problem.

This is how you would create a custom smart tag in wp forms:
function ea_custom_smart_tags( $content, $tag ) {
    if( 'my_smart_tag' == $tag ) {
        $value = 'Testing 1 2 3';
        $content = str_replace( '{' . $tag . '}', $value, $content );
    }
    return $content;
}
add_filter( 'wpforms_smart_tag_process', 'ea_custom_smart_tags', 10, 2 );
I want to post a value via ajax instead of hard coding it.
jQuery/ajax
jQuery.ajax({
    type: 'POST',
    url: 'http://localhost:8888/mywebsite/wp-admin/admin-ajax.php',
    data: {
        action: 'my_action',
        theTotal: newTotal
    },
}).success(function (result) {
    alert(result);
});
functions.php
function my_action_callback($content, $tag){


if ( 'total' === $tag ) {

 $total = $_POST['theTotal'];

 $content = str_replace( '{total}', $total, $content );

}

return $content;
}
add_action( 'wp_ajax_my_action', 'my_action_callback' );
add_filter( 'wpforms_smart_tag_process', 'my_action_callback', 10, 2 );
This is however giving me an error: 
Uncaught ArgumentCountError: Too few arguments to function my_action_callback(), 1 passed in and exactly 2 expected



leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
remove this line 15 (add_filter) and do a test
try simple, do hard after
also start by checking what is passed to your function :

function my_action_callback($content) { 
    var_dump($content);
}

Author

Commented:
Doing that gives me:

string(0) ""
0

Also, in case this is helpful, I already have the first function in my functions.php file even though I did not put it in the question, I have it.

https://wpforms.com/developers/how-to-create-a-custom-smart-tag/

Author

Commented:
The problem seems to be if you pass both $content and $tag in together. If I just pass in $content, or just $tag, I don't get that 500 error. But var dumping either gives me the same result. 
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
But var dumping either gives me the same result.  

I though you noticed I put only ONE parameter in my code snippet, this is what the error message say : give me one

Author

Commented:
Yes, I did try with only one. I first tried with just $content and then I tried with only $tag.

I think the problem is that the function needs 2 arguments, and I am only giving it one via ajax?
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
no, the ajax is something completely different so you need to think different
the $content received is an empty string
so you can only play with what you're sending with Ajax using $_POST just the way you did it with "theTotal"
now, you need to find a way to send the "content" and the "tag" using Ajax from the client side
OR
get this from Wordpress from scratch/context (not by arguments sent to your function)
also you should use a dedicated function to Ajax so it don't accept any argument

Author

Commented:
I need to get the values from ajax but I don't know how to send both the tag and the content. The tag is a hardcoded value so I probably don't even need to send the tag? I can just hardcode that value in the function? I don't know, I am feeling very lost now...
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
I need to get the values from ajax but I don't know how to send both the tag and the content

what is supposed to be $content an $tag ?

Author

Commented:
So, I have tried to just leave tag out by passing in a default empty tag. I get no errors but the returning $content doesn't actually give me anything on the frontend even though I know $score has a value.

function my_action_callback($content, $tag='') {


    $score = $_POST['content'];
    $content = str_replace( '{score}', $score, $content );
    return $content;
   
}

add_action( 'wp_ajax_my_action', 'my_action_callback', 10, 2 );
add_filter( 'wpforms_smart_tag_process', 'my_action_callback', 10, 2 );
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
finding a solution with this :
function my_action_callback() {
and not this :
function my_action_callback($content, $tag='') { 
...is your current issue
you've not parameters, your only change is to read database for some value or use wordpress to get that value or read your server side html/php or get some data from the browser using $_POST
you've no $content and $tag available so do think with this, start from zero in your ajax function and ask you HOW to get that two variables ?
I will ask one more time :
what is supposed to be $content an $tag ?

Author

Commented:
I posted the link to show you how the functions are meant to work as that example is a better explanation than what I can give. Basically, that value is hardcoded in the example. I don't want to hardcode a value. It depends what the user does on the frontend. So, when they choose something it should post to the function via ajax and that value needs to be returned on the frontend.

https://wpforms.com/developers/how-to-create-a-custom-smart-tag/

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
so your goal is to replace on the fly something like {foo} by html content  (example "<div><h3>jjfjffj</h3></div> from the client side as the user specify the myValue
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
you can just use JavaScript to replace the {foo} my the user myValue, no need ajax mainly because it's a user action

Author

Commented:
I already tried something like that if I understand you correctly. But the form doesn't seem to acknowledge the value unless you type it in or use that smart tag. Since it is something that is meant to happen in the background, the user will never type it in. Basically when they select a radio button I use jQuery to count up the results of their answers and based on the total something should happen. But like I say, if I use the value I calculated it is ignored.

I am setting it like this:

$( '#wpforms-32-field_59' ).val(newTotal);
So, that then sets the field with the value. Then something should happen based on that value but it never does because the user didn't input something. 
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
you got me but it's not the way to go
if in your template/html you had :
<div id="wpforms-32-field_59 ">{my_smart_tag}</div>
you can use
$( '#wpforms-32-field_59' ). text(newTotal);

Author

Commented:
Thanks for that. I can see the value is in there but it is still not triggering.

It is meant to work based on the WP forms conditional logic. So, if the value is equal to the value I am injecting in there as per your example above, show something. But it never shows/hides as it should unless I physically type the value into the text field for some reason.

https://wpforms.com/docs/how-to-use-conditional-logic-with-wpforms/

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
so :
1 - always put the content to show from the server but hide it with CSS display:none by default
2 - always put the value to compare too (I'm talking about the value from php, for example in a hidden field : <input type="hidden" value="<?php your WP value ?>" />

and test to see if you show() the content once the user set myValue 

Author

Commented:
That is my issue, I cannot send the value from the server. That's the whole reason I was trying to send the value via ajax to the server and return it in the smart tag function.

Each radio button has a value attached (multiple choice question). When one is selected I get the value and the total is updated. This is on the client side, not on the server.


leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
why not storing the value with the radio button ?
<input type="radio" value="10"

Author

Commented:
This is the html WP forms outputs

<input type="radio" id="wpforms-32-field_15_2" class="wpforms-payment-price wpforms-valid" data-amount="10" name="wpforms[fields][15]" value="2" required="" aria-invalid="false">
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
what is : data-amount="10"
the value?
you can get it using :
jQuery("#wpforms-32-field_15_2").data("amount")
or
document.getElementById("wpforms-32-field_15_2 ").dataset.amount

or in an event :
jQuery(":radio.wpforms-payment-price").on("change", function() {
     var amount = jQuery(this).data("amount");
     // calculate the sum
});

Author

Commented:
Getting the value isn't the issue. I am getting the value and I am putting it into a text field. The WP forms condition is based on what that value is. So if the value is X show this or if it is Y then show something else.

But the issue is that even though the value is in the text field the conditional logic is not working. It only works if I literally type the value into the text field. So for some reason it ignores the value put in with jQuery and only actually seems to register the value should I type it in, even though the value I type is exactly the same as the one put there with jQuery. 
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
check line 8 :
<script>
var myValue = jQuery( '.my_value' ).val();
<?php
     $myValue ="<script>document.write(myValue);</script>";            
 ?>
</script>
<?php
// the logic you're talking about is here?
return $content;
?>

Author

Commented:
Yes, we are getting back now to my initial question, which is how to not escape $myValue.

Because the output I get is:

<script>document.write(myValue);</script>

instead of an actual value like 100, or 95 or 76 etc.

Here is what I have:

function wpf_dev_process_smarttag( $content, $tag) {
 
    if ( 'score' === $tag ) {


        ?>
       
        <script>
            var myValue = jQuery('#wpforms-32-field_46').val();
        <?php
             $myValue ="<script>document.write(myValue);</script>";            
         ?>
        </script>
       
        <?php
       
        $score = $myValue;
       
        $content = str_replace( '{score}', $score, $content );
    }
 
    return $content;
   
}
add_filter( 'wpforms_smart_tag_process', 'wpf_dev_process_smarttag', 10, 2 );
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
you still misunderstand where the client run and where server code run.
you should NEVER mix JavaScript and PHP so you know, you're away of bad logic

check this ajax :

function my_action_callback() {
    $score = $_POST['content'];
    $tag = $_POST['tag']; // not sure you can post the tag too as I don't know where it come from
    $content = ""; // or null ?
    if ( 'score' === $tag ) { // useless test but
        $content = str_replace( '{score}', $score, $content );
    }
    return $content;  
}

Author

Commented:
We tried the ajax earlier, but it also wasn't working. Maybe it just needs some tweaking.

at the moment the response is always 0. I am using the function you pasted above.

jQuery.ajax({
    type: 'POST',
    url: 'http://localhost:8888/mySite/wp-admin/admin-ajax.php',
    data: {
        action: 'my_action',
        content: newTotal,
        tag: 'score'
    }
}).success(function (result) {
    console.log(result);

});
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
We tried the ajax earlier, but it also wasn't working. Maybe it just needs some tweaking.
that sound you still want to mix PHP and JavaScript...

could you just try :

function my_action_callback() {
    return "hello";
} 

and let me know what you get back

Author

Commented:
If I return it I get 0. If I echo it and die() afterwards I get 'hello'. It seems that with the ajax call you can't return the value, you have to echo it. But that doesn't help me because I need to return it as part of that function. 
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
But that doesn't help me because I need to return it as part of that function.  

As I said previously you need to create separate function, you can share a function but mainly your ajax function is not the action function

function my_action_callback() {
    $score = $_POST['content'];
    $tag = $_POST['tag'];
    $content = "";
    if ( 'score' === $tag ) {
        $content = str_replace( '{score}', $score, $content );
    }
    echo $content;  
}




Author

Commented:
Your code still gives me 0 as a response. 
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
it should send back an empty string or the result you want
if you still get 0, go back to test your code :

    echo "hello"; // finish with this
}

Author

Commented:
I am going to change how I do this and not use this plugin as I don't think what I want is possible. Thank you for your patience throughout this. 
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a free trial preview!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.