Not able to get JS variable to PHP using AJAX - javascript

I have a requirement in a wordpress website (PHP) where on select of a dropdown, two radio buttons show up and depending on the radio button selected a select dropdown will be made available.
I reached the stage where I have the radio buttons are made available. I use jQuery ON event to identify which radio button is checked and have the respective value in a javascript variable. I am trying to pass this JS variable to my php using ajax. Success attribute of ajax works fine but $_POST['name'] does not show the value. I tried to use .html() inside the success attribute of ajax but that just replaces my div element with the value of javascript variable. I need this JS variable value in my PHP code so that I can run a condition based on which I decide which dropdown I need to display on the website.
I have been trying a solution since few days but not able to find a solution. Request some guidance
Edit:
Based on the suggestion received
I tried the following changes. I see the value in my input type=hidden elements but only if I use Inspect in Chrome. However using View Source does not show me these values.. What am I missing? Can someone please give some guidance..
Ajx-script.js
$.ajax({
type : "POST",
url : myAjaxData.ajaxurl,
data : {
action : "sProdOrRegion_ajax_action",
selectedProdReg : selectedProdReg
},
success : function(data) {
$("#radioValueHidd1").val(selectedProdReg);
// $('#stakeholderParentData').load( urlValue + " " +"#stakeholderData");
//$("input[id=radioValueHidd3][value="+ selectedProdReg +"]").html();
$("input[id=radioValueHidd2]").val(selectedProdReg);
}
});
functions.php
add_action('wp_enqueue_scripts', function() {
wp_enqueue_script('my-ajax', get_template_directory_uri() . '/library/js/ajx-script.js', array('jquery') );
wp_localize_script(
'my-ajax',
'myAjaxData',
array( 'ajaxurl' => admin_url('admin-ajax.php') )
);
});
add_action( 'wp_ajax_singleIdeaProdOrRegion_ajax_action', 'callback_singleIdeaProdOrRegion' );
add_action('wp_ajax_singleIdeaProdOrRegion_ajax_action', 'callback_singleIdeaProdOrRegion');
function callback_singleIdeaProdOrRegion() {
if(isset($_POST['selectedProdReg'])) {
$selectedProdReg = $_POST['selectedProdReg'];
$selectedProdReg1 = $_POST['selectedProdReg'];
die();
}
}
single-car.php
<div id="stakeholderParentData" class="stakeholderParentData">
<div id="stakeholderData" class="stakeholderData">
<?php $selectedProdReg = $wpdb->escape($_POST['selectedProdReg']); ?>
<?php
if (isset ( $selProdReg )) {
if ($selProdReg === "custom_post_prod_company") {

Using Ajax in WordPress is usually done in the following manners:
1- You have to submit your ajax data to the admin-ajax.php. Sometimes you can use the global js variable ajaxurl, predefined by WordPress for that URL. But more reliably I'd use the output of admin_url( 'admin-ajax.php' ).
2- Your data object must contain an action value that have a unique string to represent this ajax submission. I'll use AJAX_ACTION here: data = { action: 'AJAX_ACTION', your_var: 'your_val' };
3- Receive the data by using hooks that contain the action name that you've specified:
add_action( 'wp_ajax_AJAX_ACTION', 'callback_function' );
add_action( 'wp_ajax_nopriv_AJAX_ACTION', 'callback_function' );
4- Use your callback_function to receive the data:
function callback_function() {
// $_POST['your_var'] is accessible here
}
By the way, using echo inside the callback_function would result in the response being sent to the success function.
wp_ajax_nopriv_AJAX_ACTION is for submission for visitors that do not have the WordPress account or are not logged in, while wp_ajax_AJAX_ACTION is for logged in users.
Please check: WordPress Codex

I am not sure if these will help you but I have 2 ideas. First is you might be getting the value of radio button false. Second is maybe you should write your data like this.
data: { "selRegProd" : selRegProd },

Related

PHP and WooCommerce Issue

If any of you are familiar with WooCommerce you may know that we have a [add_to_cart id="product_id"] shortcode to automatically add an item of given product_id to the cart.
This works fine while I give the specific ID in the html code, but I want it to be automated, for example getting the ID from a cookie.
The problem with this is that using JavaScript it is not possible to get function because it has to come from the server side but I've been mumbling for hours and getting nowhere with PHP...
What Can I do?
EDIT 1:
what I have is the following:
document.addEventListener('DOMContentLoaded', function () {
document.getElementById('test').innerHTML= '[add_to_cart id="4158"]';
})
and this does not work. Nontheless dinamically with cookies.
You don't give enough information about how you need to retrieve the product ID, but once you have it you could use do_shortcode() to automatically insert it into the shortcode:
if( isset( $_COOKIE['product_id'] ) ) {
$product_id = $_COOKIE['product_id']; // Get this from your cookie somehow
$shortcode = sprintf( '[add_to_cart id="%d"]', $product_id );
echo do_shortcode( $shortcode );
}
Solved the issue with an AJAX request to the server sending all the product information I had, it then answered with the
do_shortcode()
function and I was able to write that answer into some html element to view the button I needed.

Sub Total is not getting the changed value from database to input box

I am trying to get the sub total updated, when adding the items to the database from java-script. But, currently it displays the first amount and not updates when adding items. (But when runs the query from phpMyAdmin it works correctly)
java-script code
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
HTML code
<input name="txtSubTotal" type="text" id="txtSubTotal" size="15" / >
<button type="button" name="btnSave" id="btnSave" onclick="submitdata(); check_qty(); showSubTotal();">ADD</button></td>
The problem is, that when you declare the function with PHP, the function cannot be refreshed by using PHP again... because everything that PHP does, happens before the page is loaded, therefore, let's say as an example:
function showSubTotal() {
<?php $resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
?>
document.getElementById("txtSubTotal").setAttribute('value','');
document.getElementById("txtSubTotal").setAttribute('value',"<?php echo $rowT[0]; ?>");
}
this 'value' from $rowT[0] = 10 from the first query, it will always be 10, because that is what PHP read from the database when it checked upon page load. You will have to use something like jquery or ajax to read the contents of another php file that contains the value (the mysqli_fetch_row).
PHP is literally named hypertext preprocessor, meaning everything that is processed before the html is printed to the user. (before the page has finished loading)
try experimenting with this: https://api.jquery.com/jquery.get/
ShowSubTotal() will bring only the value when the page loads. Dynamic actions will not make any changes, because php needs an server request to operate.
You should bring the subtotal through a dynamic request (ajax) call.
Or:
Use javascript to sum the values and set the value in your txtSubTotal field. If you go for this option, remember to not rely on this value on your server side processing, as it may be adulterated by users.
I found the solution, added the do_onload(id) to calculate the total on loadComplete event which is triggered after each refresh (also after delete)
function do_onload(id)
{
//alert('Simulating, data on load event')
var s = $("#list").jqGrid('getCol', 'amount', false, 'sum');
jQuery("#txtSubTotal").val(s);
}
And changed the phpgrid code accordingly.
$opt["loadComplete"] = "function(ids) { do_onload(ids); }";
$grid->set_options($opt);
try this code
$("#btnSave").click(function(){
$.ajax({
url : file_url.php,
type : 'post',
data : {
get_subtotal:"subtotal",
},
success : function( response ) {
alert(response);
$("#txtSubTotal").val(response );
},
error: function(response) {
console.log(response);
}
});
});
file_url.php
if(isset($_POST['get_subtotal'])){
$resultT=mysqli_query($connection, "SELECT SUM(amount) FROM sales_temp");
$rowT = mysqli_fetch_row($resultT);
echo $rowT[0];
}

Facebook js SDK send with ajax variabiles to PHP

First of all thank you for your atention.
What I would like is to use the Facebook js SDK to get the user's name and id and send them to php in the same page (index.php). I manage to get the username and id and save them in 2 variables in JS (js_fb_id and js_fb_name), but when I try to make the ajax call and sent them to php, nothing happens.
So, on my index.php i have the ajax script
var js_fb_id = response.id;
var js_fb_name = response.name; //this variables are set after the user is loged in
$.post( 'index.php',
{
php_fb_id: js_fb_id,
php_fb_id: js_fb_name
},
function (data){
console.log(data);
}
)
Later on, I want to get the variables send via AJAX
<?php if ( isset( $_POST['php_fb_id'] ) ) {
echo $_POST['php_fb_id'];
}
?>
Is this possible? It works when I use a separate page to make the AJAX call, but I cannot get the php variables from there to my index.php page.
Thank you
So basically what is happening here is that the ajax script is triggered on page load.
However this is only after the dom has already been rendered.
To fix this you will need to trigger the ajax function on a specific event , for eg: button click.
Also note that since your entire page is in html you ajax function is returning the entire page as 'data' and not spacifically the php variables that you are trying to set.(You will be able to see this in the console)
Also note that if you want to print the values on the page you will have to modify the html in the callback function through ajax for eg:
$(document).ready(function() {
$('#post').click(function() {
$.post( 'text.php',
{
php_fb_id: js_fb_id,
php_fb_name: js_fb_name
},
function (data, status){
$("#txt").html(data); //you can print returned data
console.log(data);
}
)
});
});
This should go in a separate php file say text.php
<?php
if ( isset( $_POST['php_fb_id'] ) ) {
echo $id = $_POST['php_fb_id'];
}
?>
Your code looks fine, except that you passing php_fb_id twice in the parameter.
$.post( 'index.php', {
php_fb_id: js_fb_id,
php_fb_id: js_fb_name
},
Except this, parameter are passing into index.php and getting captured too. so you can go ahead with php operation there. Do let me know what is the problem you facing in this code? will definitely try to help
Do Something like this:
if ($_SERVER['REQUEST_METHOD'] === 'POST') { //check if it's Post request
if( isset( $_POST['php_fb_id'] && isset( $_POST['php_fb_name']) {
$name = $_POST['php_fb_name'];
$id = $_POST['php_fb_id'];
....
echo "OK";
}else{
echo "ERROR, need input";
}
else{
//Your Index Code Here
}

Run PHP Query with Ajax return data in modal

This is my first fully attempting to use ajax. I have looked all over Google and cannot seem to find an answer. I am not even sure if what I am trying to do is possible.
I am trying to populate a modal window with data from a mysql table.
Using this javascript below, I an able to print the DATA-ID in a modal window with an HREF click:
<script type="text/javascript">
$(document).on("click", ".open-RestrictModal", function () {
var myId = $(this).data('id');
$(".modal-body #Id").val( myId );
});
</script>
I would like to add to this code is the ability to run a PHP/MySQL query, get the results, and print it in the modal window.
I think I have to use AJAX, but I am not sure. How can I add to the existing code the ability to send the javascript variable to an AJAX page and return the results in a modal window?
Please help.
It doesn't appear that you are even using ajax here, assuming you are using the jQuery library you can build a call like this:
function some_ajax_call(your_param) {
$.ajax({
type: "POST", // We want to use POST when we request our PHP file
url : "some/url/to/your/file.php",
data : { query : your_param }, // passing an array to the PHP file with the param, value you passed, this could just be a single value i.e. data: your_param
cache: false, // disable the cache optional
// Success callback if the PHP executed
success: function(data) {
// do somethig - i.e. update your modal with the returned data object
$('.modal-body #id').val(data);
}
});
}
You can then write you file.php file to handle the query
<?php
// Capture the variable we passed in via AJAX
$param = $_POST['query'];
// Build a query
$query = "SELECT * FROM some_table WHERE val ='" . $param . "'";
// I assume you know how to run a query, this would be fetching an assoc array
$results = $DB->run__query($query);
// Check we have some results, then echo back to the AJAX call
if(sizeof($results) > 0) {
echo $results;
}
echoing at the $results array at the end of our PHP script if we have any results will populate the data array in our success callback with the returned rows, you can then perform any DOM manipulation in the success callback to update your modal, hope this helps.

How to display WordPress post content in multiple block elements without page refresh

I'm gonna post a fiddle because it's easier to explain.
http://jsfiddle.net/EhNKM/84/
$("#focus a").mouseenter(
function(){
this.style.color = '#cc0000';
$('<p>content from post that the hovered-over link points to.</p>').replaceAll('#child p');
}
);
How can I access post information that is referenced by a link to that post content? I'd like to use that information to load that post content into another div, but I'm just not sure where to begin with this (what WordPress PHP can I use? JS?). Anything, even screaming at me for being dumb, would be helpful!
To clarify what's going on in the fiddle,
Once a user hovers over a link (to another post), the child div loads that linked-to post content.
Don't worry about the .click() event. I'm sure solving the above would provide insight into this.
Thanks!
EDIT:
I also believe I should use
this.getAttribute('href')
to get the linked-to post, but I'm not sure what wp function I should (or could!) use to get the content of that post once I have the reference.
You can do it using jQuery ajax, well, follow my instructions step by step.
1. Create a folder in your theme folder js, suppose your theme folder is twentytwelve, so it should be
http://yourDomain.com/wp-content/themes/twentytwelve/js
2. Create a file into your js folder and name it myScript.js
3. In your functions.php file add
add_action('wp_enqueue_scripts','my_theme_scripts_function');
function my_theme_scripts_function() {
wp_enqueue_script('myScriptHandler', get_stylesheet_directory_uri() . '/js/myScript.js');
wp_localize_script( 'myScriptHandler', 'myAjax', array( 'ajaxUrl' => admin_url( 'admin-ajax.php' ) ) );
}
4. Also add following code in your functions.php
function do_myAjaxFunction()
{
$post_id = url_to_postid($_POST['post_url']);
$post = get_post( $post_id, OBJECT);
$response = apply_filters( 'the_content', $post->post_content );
echo $response;
die();
}
add_action( 'wp_ajax_nopriv_myAjaxHandler', 'do_myAjaxFunction' );
add_action( 'wp_ajax_myAjaxHandler', 'do_myAjaxFunction' );
5. Now in the myScript.js file, add following code
$('.your_post-entry a').click(function(e){
e.preventDefault();
var currentUrl = $(this).attr('href');
$.ajax({
type : 'post',
url : myAjax.ajaxUrl,
data: {
action: 'myAjaxHandler',
post_url: currentUrl
},
success: function(data){
$('#ajax_post').html(data);
}
});
});
Put the above code inside jQuery(function($){...}); function (the ready event of jQuery). It' done! Now you can fetch your post content using ajax.
Explanation :
When you'll click any link inside the element (assume a div) with class name your_post-entry, the click event will fire (You know that) and it'll send a post request to http://yourDomain.com/wp-admin/admin-ajax.php because myAjax.ajaxUrl contains that url and it's (myAjax object) available to our script through wp_localize_script that we have in our functions.php. The ajax request will also send some variables to the $_POST array and those are action and post_url, the post_url contains the permalink of the post and admin-ajax.php will run our do_myAjaxFunction which will fetch the content of the post and send it back to the browser because we've added actions using add_action( 'wp_ajax_myAjaxHandler', 'do_myAjaxFunction' ), which tells the WordPree that whenever you get an ajax request for myAjaxHandler action, please run the do_myAjaxFunction function. The first add_action is wp_ajax_nopriv_myAjaxHandler, which is required to make the ajax request work even when user is not login in the wordpress backend, without wp_ajax_nopriv_myAjaxHandler the ajax request won't work if the user is not logged in. Notice the line $('#ajax_post').html(data); in the success callback, it'll insert the returned data into the element/div with an id of ajax_post, so make sure to use appropriate id and class name in the click event.
If you don't want to use ajax for every post then you can add/generate a class for those post links that you want to use ajax, for example, ajaxPost and in the click event you can use
$('.your_post-entry a.ajaxPost').click(function(e){ ... });
Now you know how to do it so I think you can do it using mouseenter instead of click if you need to do this way (you gave an example of mouseenter).
Some usefull links : wp_ajax_ and how-to-use-ajax-in-wordpress

Categories