Crazy Horse
asked on
How to post value to function with ajax and jQuery
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(but tontext);< /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;
?>
ASKER
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.
So, php `$myValue` needs to be set to whatever jQuery `var Myvalue` is.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
ASKER
Alright. I am trying to use ajax but having a problem.
This is how you would create a custom smart tag in wp forms:
jQuery/ajax
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.phpfunction 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
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 :
try simple, do hard after
also start by checking what is passed to your function :
function my_action_callback($content) {
var_dump($content);
}
ASKER
Doing that gives me:
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/
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/
ASKER
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.
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
ASKER
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?
I think the problem is that the function needs 2 arguments, and I am only giving it one via ajax?
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
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
ASKER
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...
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 ?
ASKER
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 );
finding a solution with this :
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 ?
function my_action_callback() {
and not this :function my_action_callback($content, $tag='') {
...is your current issueyou'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 ?
ASKER
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/
https://wpforms.com/developers/how-to-create-a-custom-smart-tag/
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
you can just use JavaScript to replace the {foo} my the user myValue, no need ajax mainly because it's a user action
ASKER
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:
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.
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);
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);
ASKER
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/
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/
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
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
ASKER
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.
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.
why not storing the value with the radio button ?
<input type="radio" value="10"
<input type="radio" value="10"
ASKER
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">
what is : data-amount="10"
the value?
you can get it using :
or in an event :
the value?
you can get it using :
jQuery("#wpforms-32-field_15_2").data("amount")
ordocument.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
});
ASKER
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.
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.
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;
?>
ASKER
Yes, we are getting back now to my initial question, which is how to not escape $myValue.
Because the output I get is:
instead of an actual value like 100, or 95 or 76 etc.
Here is what I have:
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 );
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 :
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;
}
ASKER
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.
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);
});
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
ASKER
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.
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
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;
}
ASKER
Your code still gives me 0 as a response.
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
}
if you still get 0, go back to test your code :
echo "hello"; // finish with this
}
ASKER
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.
Open in new window