Function doesn't echo variable - php

I'm currently learning basic php and jQuery.
I've created script which is getting url on mouse hover, and sends it to php.
The problem is, if I want to pass this data to php variable, it seems like it doesn't work because it echos only "'This is our JS Variable :'"
Script:
<script type="text/javascript">
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
console.log(hrefValue)
});
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
});
</script>
functions.php:
function our_tutorial(){
if(isset($_REQUEST)){
$testing = $_REQUEST['php_test'];
echo 'This is our JS Variable :'.$testing;
global $wpdb;
$wpdb->insert(
$wpdb->prefix.'lms_enroll',
[
'ID' => $testing
]
);
}
die();
}
add_action('wp_ajax_php_tutorial', 'our_tutorial');

Solution:
$.ajax({
url: 'jakubtrz-portfolio/wp-admin/admin-ajax.php',
type: 'post', // define type
data: {
'action': 'php_tutorial',
'php_test': hrefValue
},
success: function(data){
console.log("happy")
}
});
functions.php:
// post to et value
$test = $_POST['php_test'];

The problem was - when page loaded, value of a variable was empty. So solution is to call ajax in the moment of mouseover.
var hrefValue;
jQuery(document).ready(function($) {
$('#bio-box').find('a').mouseover(function() {
hrefValue = ($(this).attr('href'))
//console.log(hrefValue)
$.ajax({
url: frontendajax.ajaxurl,
type: 'POST',
data: {
'action': 'image',
'php_test': hrefValue
},
success: function(data){
$('#featured-image').html(data);
//console.log(data);
}
});
});
});

Related

Wordpress ajax request not working properly

I am new to wordpress, i make a ajax request on click button and it print the data, but ajax is not giving me any response. Please help me to find out the error.
Here is my code
add_action("wp_ajax_delivery_options", "delivery_options");
add_action("wp_ajax_nopriv_delivery_options", "delivery_options");
function delivery_options()
{
echo json_encode(array('type' => 'success'));
wp_die();
}
wp_enqueue_script("my-ajax-handle", get_stylesheet_directory_uri() . "/js/custom.js", array('jquery'));
wp_localize_script('my-ajax-handle', 'the_ajax_script', array('ajaxurl' => admin_url('admin-ajax.php')));
Ajax
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});
})(jQuery);
Any solution appreciated!
you have to pass "callback function name" in data: { action: 'delivery_options', delivery_option: data },
(function($) {
$(document).ready(function() {
$('#delivery_option button').on('click', function(e) {
e.preventDefault();
var data = e.currentTarget.id;
$.ajax({
type: 'POST',
dataType: 'json',
url: the_ajax_script.ajaxurl,
data: { action: 'delivery_options', delivery_option: data },
success: function(response) {
console.log(response);
}
});
});
});})(jQuery);

Jquery simple Ajax Post PHP not working

I have a simple code but is not working. I want to create a more complex function but I just need the basic structure.
HTML
<span class="cleanreport">Delete Record</span>
Javascript:
$( ".cleanreport" ).click(function() {
var token = "test";
$.ajax({
data: {"data": token},
type: "post",
url: "clean.php",
success: function (data) {
console.log(data);
$('.test').html(data);
}
});
});
PHP clean.php
$data = $_POST['data'];
echo $data;
What I am doing wrong?
This should work for you:
var token = "test";
$.ajax({
type: 'POST',
url: "clean.php",
data: {id: token},
dataType: "json",
success: function(response) {
// some debug could be here
},
error: function(a,b,c) {
// some debug could be here
}
});
If not, please debug success and error parameters using console.log().
Based on jquery documentation setting type is an alias for method so this could not be a problem in you case for sure.
$( ".cleanreport" ).click(function() {
var token = "test";
$.post('clean.php",
{
data: token
},
function (data,status) {
//console.log(data);
$('.test').html(data);
});
});

refresh div after sending data to db

i have a div that shows the total sum of some products:
<div class="total-price"><?php echo (!empty($cart)) ? $cart['total'] : '0'; ?> $</div>
with ajax, i'm adding products to cart ... se the page is not reloading.
How to refresh the div after I add the product to cart?
The ajax that i'm using:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
$(".total-price").something...;
}
});
})
</script>
Thank you!
You can do something like this:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
var oldPrice = $('.total-price').text() * 1;
var itemPrice = "15"; //the price that should be added
$('.total-price').text(oldPrice + itemPrice);
}
});
})
</script>
You should be returning a total basket value from your /tdt/order path.
In the PHP script you should echo some JSON data with all the required information, for example
echo json_encode(array("totalPrice" => "£10.01"));
Then you need to parse this information into your Javascript and update the pages elements;
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
$(".success-message").slideDown().delay(5000).slideUp();
$('.total-price').val(data.totalPrice);
}
});
})
</script>
The above ajax request will expect the data returned to be JSON, you will then use this to update the total-price element.
You can use something like angularjs or knockoutjs - for angular you would update your model - for knockout you would use the self.object.push(value) i.e.,
function OrderViewModel() {
var self = this;
self.myOrder = ko.observableArray([]);
self.addOrderItem = function () {
$.ajax({
type: "post",
url: "yourURL",
data: $("#YOURFORMFIELDID").serialize(),
dataType: "json",
success: function (value) {
self.myOrder.push(value);
},
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
}
}
ko.applyBindings(new orderViewModel());
</script>
</pre>

html link value retrieve by Js ajax send to php

I have a html link with a value inside like this.
<a data-toggle='modal' data-id='1' href='#myModal' class='marker' title='Edit'>Link</a>
I have a Js script that trigger a php that I want to send the value data-id
<script>
$(document).on("click", ".marker", function () {
var myBookId = $(this).data('id');
$.ajax({
type: "post",
url: "update.php", //
data: myBookId,
success: function(msg) {
$("#thanks").html(msg)
},
error: function() {
alert("failure");
}
});
});
</script>
And in my php I have this
if (isset($_POST['myBookId'])) {
$emp_id = strip_tags($_POST['myBookId']);
echo $emp_id;
But something is wrong the value is not pass.
Your problem is on the params of the AJAX call. Try this way:
data: { myBookId: myBookId },
try
$('.marker')click(function(){
var myBookId = $().attr('data-id');
$.ajax({
type: "post",
url: "update.php", //
data: myBookId,
success: function(msg){
$("#thanks").html(msg)
},
error: function(){
alert("failure");
}
});
return false;
});

AJAX POST: echoing posted anchor tag value

HTML/jQuery:
Friends
<script type="text/javascript">
$(document).ready(function() {
$('a#friends').click(function() {
$.ajax({
type: "POST",
url: "data.php",
data: $('#friends').html(),
success: function(data) {
$('#questions').html(data);
},
dataType: "HTML"
});
});
});
</script>
data.php:
<?php
echo $_POST['#friends'];
?>
How do I return this POST value of an id in an anchor tag? The variable is being passed to PHP because I can alert it, but the problem is getting it back.
You need to specify the name of the value you are sending across in your AJAX request. Try this:
$.ajax({
type: "POST",
url: "data.php",
data: { 'friends': $('#friends').html() }, // Note the value is sent in an object with a key of 'friends'
success: function(data) {
$('#questions').html(data);
},
dataType: "HTML"
});
<?php
echo $_POST['friends']; // retrieve the 'friends' value
?>
How you are passing the data to PHP,
please use the following code,
Friends
<script type="text/javascript">
$(document).ready(function() {
$('a#friends').click(function() {
$.ajax({
type: "POST",
url: "data.php",
data: {'friends' : $('#friends').html()},
success: function(data) {
$('#questions').html(data);
},
dataType: "HTML"
});
});
</script>
<?php
echo $_POST['friends'];
?>
Your syntax is wrong for passing friends value to data.php
Try this
$(document).ready(function() {
$('a#friends').click(function() {
$.ajax({
type: "POST",
url: "data.php",
data: "friends="+$('#friends').html(),
success: function(data) {
$('#questions').html(data);
},
dataType: "HTML"
});
});
<?php
echo $_POST['friends'];
?>
First of all you can't send data to the ajax page in this way
data: $('#friends').html(),
A more suitable way would be
data : {'key1':'val1', 'key2':'val2'}
Then on the php page, you can retrieve these values in this fashion
$key1 = $_POST['key1']; // will contain 'val1'
$key2= $_POST['key2']; // will contain 'val2'
alternatively you can use
Friends
<script type="text/javascript">
$(document).ready(function() {
$('a#friends').click(function() {
$.post("data.php",{
friends: $("#friends").html()
},function(data){
$("#questions").html($.trim(data)); // trim to be sure
});
});
});
</script>
and in the php:
<?php
echo $_POST['friends'];
?>
Pass the data variable in data field. For more info see below example
$(document).ready(function() {
$('a#friends').click(function() {
alert("");
$.ajax({
type: "POST",
url: "data.php",
data: "#friends="+$('#friends').html(),
success: function(data) {
alert(data);
$('#questions').html(data);
},
dataType: "HTML"
});
});
});

Categories