How do I assign jQuery event handlers properly? - javascript

I am still learning how to use AJAX so would display a novice code here...
I got this div (which repeats itself as a list of checkbox):
<div class="updateTask fs11">
<input type="checkbox" name="taskStatusRadio" id="taskStatus" value="<?php echo $taskId; ?>" <?php echo $done; ?> >
<?php _e('Task Done', 'sagive'); ?>
</div>
Which activates this:
jQuery(function($){
$('.updateTask').click(function () {
$.post(ajax_object.ajaxurl, {
action: 'action_update_task',
task_id: $("input[name=taskStatusRadio]:checked").map(function () {return this.value;}).get()
}, function(data) {
// USE DATA RETURNED //////////
var $response = $(data);
var message = $response.filter('div#message').html();
var taskid = $response.filter('div#taskid').html();
// SUCCESS RESPOND //////////
setTimeout(function(){
$('#success ul li').append(message + taskid);
$('#success').fadeIn();
$('#success').css("display", "block");
}, 1000);
setTimeout(function(){
$('#success ul li').empty();
$('#success').fadeIn();
$('#success').css("display", "none");
}, 30000);
hideTask = "#" + taskid;
$(hideTask).hide("slow");
hideTask = '';
});
});
});
And uses this php file:
wp_enqueue_script( 'ajax-update-task', get_stylesheet_directory_uri().'/ajaxLoops/ajax-update_task.js', array('jquery'), 1.0 ); // jQuery will be included automatically
wp_localize_script( 'ajax-update-task', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
add_action( 'wp_ajax_action_update_task', 'ajax_update_task' ); // ajax for logged in users
function ajax_update_task() {
global $current_user;
get_currentuserinfo();
$task_user = $current_user->display_name;
if($taskUser == '') {$taskUser = $current_user->user_login;}
$task_id = $_POST["task_id"];
$task_id = $task_id[0];
$task_status = 'done';
$task_title = get_the_title($task_id);
$task_title = mb_substr($task_title, 0 ,35).'...';
update_post_meta($task_id, '_sagive_task_radio_selector', $task_status);
update_post_meta($task_id, '_sagive_task_user_changed', $task_user);
echo '<div id="message">'.__('The task: ', 'sagive').$task_title.__('Was Marked Completed!', 'sagive').'</div>';
echo '<div id="taskid">'.$task_id.'</div>';
die(); // stop executing script
}
It all works fine the first time. But the second checkbox I mark after the first one disappears as expected does nothing. It doesn't activate the php script and doesn't return a response.
Since I'm still new using AJAX, I would appreciate an example using my code or a good example with explanation.
Revision 1:
This is the structure of the page where the checkboxes are at

I think your problem comes from your selector :
$("input[name=taskStatusRadio]:checked").map(function () {return this.value;}).get();
which returns all the taskStatusRadio input checked and not just the one you click.
Your php script receive all the taskid checked in an array an pick the first one to treat it and send a response.
So the first time, it's ok, you just have one checkbox checked. But when you check a second checkbox, all checked taskid will be send and only the $_POST["task_id"][0] will be treated.
Same response from your php script and no change in the front view.
So, i think, you just have to modify a little bit your code, to post only taskid of the checkbox you click on it.
jQuery(function($) {
// we listen only the checkbox, not the div click action
$(':checkbox', '.updateTask').click(function () {
// if the checkbox is checked
if ($(this).attr('checked') == "checked") {
$.post(ajax_object.ajaxurl, {
action: 'action_update_task',
task_id: $(this).val() },
function(data) {
// SUCCESS RESPOND //////////
setTimeout(function() {
$('#success ul li').append( $(data).html());
$('#success').fadeIn();
$('#success').css("display", "block");
}, 1000);
setTimeout(function() {
$('#success ul li').empty();
$('#success').fadeIn();
$('#success').css("display", "none");
}, 30000);
// we hide the checkbox
$(this).hide("slow");
});
}
});
});
And because of this change in the front javascript, we have to simplify your php script like this :
wp_enqueue_script( 'ajax-update-task', get_stylesheet_directory_uri().'/ajaxLoops/ajax-update_task.js', array('jquery'), 1.0 ); // jQuery will be included automatically
wp_localize_script( 'ajax-update-task', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); // setting ajaxurl
add_action( 'wp_ajax_action_update_task', 'ajax_update_task' ); // ajax for logged in users
function ajax_update_task() {
global $current_user;
get_currentuserinfo();
$task_user = $current_user->display_name;
if($taskUser == '') {$taskUser = $current_user->user_login;}
$task_id = $_POST["task_id"];
$task_status = 'done';
$task_title = get_the_title($task_id);
$task_title = mb_substr($task_title, 0 ,35).'...';
update_post_meta($task_id, '_sagive_task_radio_selector', $task_status);
update_post_meta($task_id, '_sagive_task_user_changed', $task_user);
// Note : now we send the message directly well-formed with the task_id
echo __('The task: ', 'sagive').$task_title.__('Was Marked Completed!', 'sagive'). $task_id;
die(); // stop executing script
}
I hope my answer will solve your problem ;)
ps: i apologize for my poor english...

Related

Disable downlaod link after 5 time clicks Wordpress | Javascripts | Ajax

I am creating a custom wordpress theme and what i want is that; there is a download link, what i want is that users can download only 5 times when the user clicks that link only for 5 times, if the user tries to click the link for the 6th time it automatically hides. I dont have any idea how to do this, also didn't find any relevant solution on google.
here below is my testing code:
<script type="text/javascript">
function myFunction() {
$(document).ready(function(){
$(".gotocls").click(function(){
alert("Hello! I am an alert box!!");
});
});
}
</script>
<a class="dkpdf-button gotocls" onclick="myFunction()" href="downlaod/image.com" target="_blank"><span class="dkpdf-button-icon"><i class="fa fa-file-pdf-o"></i></span> <?php echo $pdfbutton_text;?></a>
i think this might be done with ajax, but i dont have much knowledge of ajax
you don't need onClick in this code I add document.getElementsByClassName('gotocls')[0].style.display = 'none'; when i equals 5 .
$(document).ready(function(){
var i = 0
$(".gotocls").click(function(){
i++
if(i == 5)
document.getElementsByClassName('gotocls')[0].style.display = 'none';
alert("Hello! I am an alert box!!" + i);
});
});
</script>
<a class="dkpdf-button gotocls" id="myLink" href="downlaod/image.com" target="_blank"><span class="dkpdf-button-icon"><i class="fa fa-file-pdf-o"></i></span> <?php echo $pdfbutton_text;?></a>
If you only want to hide the download link in the current session, then simple javascript should do your job.
<script type="text/javascript">
var counter = 0;
function myFunction() {
if(counter === 5){
document.getElementsByClassName('gotocls')[0].style.display = 'none';
}
counter = counter +1;
}
</script>
However when the user refreshes the site, then the download link will be visible again. If you want to store information permanently then you have to use a database.
I wrote the code needed real quick with no tests but it should give you a starting point at least, in your PHP:
/**
* Enqueue a JS file using WP proper action and functions
* 'my-custom-script' can be any name of your fantasy, prepend it with your vendor name and you are good to go
* 'url_to_js_file' MUST be a full URL to your .JS file containing the ajax you need
*/
function our_custom_scripts() {
wp_register_script( 'my-custom-script', 'url_to_js_file.js', array( 'jquery' ), false, true );
wp_localize_script( 'my-custom-script', 'myJsVarName', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ), // Used to make ajax call in WP
) );
wp_enqueue_script( 'my-custom-script' );
}
// Load script
add_action( 'wp_enqueue_scripts', 'our_custom_scripts' );
/**
* What the ajax call will actually trigger thanks to WP AJAX handle
*/
function my_ajax_action() {
/** #var wpdb $wpdb */
global $wpdb;
$clickedLink = $_POST["clicked_link"];
$userId = get_current_user_id();
/*
* Query for the pressed link, that's up to you on how to store data in the database, im going with an easy one
* saving the full link (i would really NOT recommend this :D, its just to show)
*/
$sql = "SELECT * FROM {$wpdb->prefix}my_table_name WHERE link = %s";
$res = $wpdb->get_row( $wpdb->prepare( $sql, array( $clickedLink ) ) );
if ( $canClick = $res["num_pressed"] < 5 ) {
$wpdb->update(
$wpdb->prefix . "my_table_name",
array(
'num_pressed' => ( $res["num_pressed"] + 1 ),
'string_col' => 'val2', //example string col
'int_col' => 3, //example int col
),
array( "user_id" => $userId ), // Where condition
array( "%d", "%s", "%d" ), // updated values format. %s are for strings, %d for integers
array( "%d" ) );// Where condition format
wp_send_json_success();
} else {
wp_send_json_error();
}
}
add_action( 'wp_ajax_my_ajax_action', array( $this, 'my_ajax_action' ) );
add_action( 'wp_ajax_nopriv_my_ajax_action', array( $this, 'my_ajax_action' ) );
Then in your .js file add this:
$(document).ready(function () {
$(".gotocls").click(function (evt) {
var $pressedLink = $(this);
evt.preventDefault(); // Stop doing w/e the browser was trying to do
$.ajax({
url: myJsVarName.ajaxurl,
type: 'POST',
data: {
action: 'my_ajax_action',
clicked_link: $pressedLink.attr("href")
},
timeout: 5000
dataType: 'json',
success: function (response) {
console.log('Your response content', response);
if (response.success) {
window.location.href = $pressedLink.attr("href"); // Proceed with click
}
},
error: function (jqXHR, textStatus, errorThrown) {
}
});
});
});
})(jQuery);
This should cover the PHP and the JS side of your stuff. The rest is up to you, stackoverflow is not a coding factory, it's a community for advices :D

(populate dropdown in contact form 7 getting this error - Warning: array_keys() expects parameter 1 to be array, null given in

Ok where to start, I will try and explain as much as I can.
I am using wordpress with contact form 7 and I am trying to populate 3 dropdown items on the contact form, I found some code that I was able to use with no problem but the problem with this was that it was getting the information from a excel file, the file is now to big and will not run on my website anymore so I would like to get the information from my database now.
I have made a table in my database "vehicle_information" with 3 columns "vehicle_type", "vehicle_make", vehicle_model"
I have code in my functions.php and code in my footer to be able to use the cf7 shortcodes.
Code from funtions.php
function ajax_cf7_populate_values() {
//MySQLi information
$db_host = '***';
$db_username = '***';
$db_password = '***';
$vehicles_makes_models = array();
//connect to mysqli database (Host/Username/Password)
$connection = mysqli_connect($db_host, $db_username, $db_password) or die('Error ' . mysqli_error());
//select MySQLi dabatase table
$vehicles_makes_models = mysqli_select_db($connection, 'vehicle_information') or die('Error ' . mysqli_error());
$sql = mysqli_query($connection, 'SELECT * FROM vehicle_type');
while($row = mysqli_fetch_array($sql)) {
$vehicles_makes_models[$row[0]][$row[1]][] = $row[2]; }
}
// setup the initial array that will be returned to the the client side script as a JSON object.
$return_array = array(
'vehicles' => array_keys($vehicles_makes_models),
'makes' => array(),
'models' => array(),
'current_vehicle' => false,
'current_make' => false
);
// collect the posted values from the submitted form
$vehicle = key_exists('vehicle', $_POST) ? $_POST['vehicle'] : false;
$make = key_exists('make', $_POST) ? $_POST['make'] : false;
$model = key_exists('model', $_POST) ? $_POST['model'] : false;
// populate the $return_array with the necessary values
if ($vehicle) {
$return_array['current_vehicle'] = $vehicle;
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
if ($make) {
$return_array['current_make'] = $make;
$return_array['models'] = $vehicles_makes_models[$vehicle][$make];
if ($model) {
$return_array['current_model'] = $model;
}
}
}
// encode the $return_array as a JSON object and echo it
echo json_encode($return_array);
wp_die();
// These action hooks are needed to tell WordPress that the cf7_populate_values() function needs to be called
// if a script is POSTing the action : 'cf7_populate_values'
add_action( 'wp_ajax_cf7_populate_values', 'ajax_cf7_populate_values' );
add_action( 'wp_ajax_nopriv_cf7_populate_values', 'ajax_cf7_populate_values' );
Code from my footer
<script>
(function($) {
// create references to the 3 dropdown fields for later use.
var $vehicles_dd = $('[name="vehicles"]');
var $makes_dd = $('[name="makes"]');
var $models_dd = $('[name="models"]');
// run the populate_fields function, and additionally run it every time a value changes
populate_fields();
$('select').change(function() {
populate_fields();
});
function populate_fields() {
var data = {
// action needs to match the action hook part after wp_ajax_nopriv_ and wp_ajax_ in the server side script.
'action' : 'cf7_populate_values',
// pass all the currently selected values to the server side script.
'vehicle' : $vehicles_dd.val(),
'make' : $makes_dd.val(),
'model' : $models_dd.val()
};
// call the server side script, and on completion, update all dropdown lists with the received values.
$.post('<?php echo admin_url( 'admin-ajax.php' ) ?>', data, function(response) {
all_values = response;
$vehicles_dd.html('').append($('<option>').text(' -- choose vehicle -- '));
$makes_dd.html('').append($('<option>').text(' -- choose make -- '));
$models_dd.html('').append($('<option>').text(' -- choose model -- '));
$.each(all_values.vehicles, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_vehicle == this) {
$option.attr('selected','selected');
}
$vehicles_dd.append($option);
});
$.each(all_values.makes, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_make == this) {
$option.attr('selected','selected');
}
$makes_dd.append($option);
});
$.each(all_values.models, function() {
$option = $("<option>").text(this).val(this);
if (all_values.current_model == this) {
$option.attr('selected','selected');
}
$models_dd.append($option);
});
},'json');
}
})( jQuery );
The problem is I am still learning and this is the first time I have had to use this funtion.
and I am getting an error on my website
Warning: array_keys() expects parameter 1 to be array, null given in /customers/4/0/0/motobid.co.uk/httpd.www/wp-content/themes/storevilla-child/functions.php on line 38 {"vehicles":null,"makes":[],"models":[],"current_vehicle":false,"current_make":false}
any help would be very greatful.
Just like to say code was supplied by BDMW.
Where you use the method array_keys(), instead of:
$return_array['makes'] = array_keys($vehicles_makes_models[$vehicle]);
Try this:
$return_array['makes'] = ! empty($vehicles_makes_models[$vehicle]) ? array_keys($vehicles_makes_models[$vehicle]) : [];
From what I've read, the array_keys() has been an issue depending on php versions. Hope this helps!

wordpress plugin jquery ajax call to function not working

JQuery Code:
jQuery("#dmhsc-form").on("submit", function () {
var form = this;
if (jQuery("input[name='url']", form).val() == "") {
jQuery("div[id='results']", form).html('<div class="not-available">Please, Enter site address.</div>');
return false;
}
var url = jQuery("input[name='url']", form).val();
jQuery("div[id='results']", form).css('display', 'none');
jQuery("div[id='results']", form).html('');
jQuery("div[id='loading']", form).css('display', 'inline');
var data = {
'action': 'dmhsc_show',
'url': url,
'security': badnc_ajax.dmhsc_nonce
};
jQuery.post(badnc_ajax.ajaxurl, data, function (response) {
var x = JSON.parse(response);
if (x.status >= 0) {
display = x.text;
} else {
display = "Error occured." + x;
}
jQuery("div[id='results']", form).css('display', 'block');
jQuery("div[id='loading']", form).css('display', 'none');
jQuery("div[id='results']", form).html(unescape(display));
});
return false;
});
Plugin File
function badnc_load_styles() {
wp_enqueue_script( 'badnc-script', plugins_url( 'script.js', __FILE__ ), array('jquery')); // script.js contains jquery code
wp_localize_script( 'badnc-script', 'badnc_ajax', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'dmhsc_nonce' => wp_create_nonce( 'dmhsc_nonce' ))
);
}
add_action( 'wp_loaded', 'badnc_load_styles' );
add_action( 'admin_enqueue_scripts', 'badnc_load_styles' );
function dmhsc_show() {
check_ajax_referer( 'dmhsc_nonce', 'security' );
if(isset($_POST['url']))
{
$url = sanitize_text_field($_POST['url']);
if(!$url || !is_string($url) || ! preg_match('/^(https?:\/\/)?(www\.)?\w+\.[a-z]{2,6}(\/)?$/i', $url)) {
$result = array('status'=>0,'url'=>$url, 'text'=> '<div class="not-available">Please, Enter valid domain name.</div>');
echo json_encode($result);
} else {
/*$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$url.'</div>');
echo json_encode($result);*/ //It display the message without calling to fucntion
check_https($url); //function call
}
}
die();
}
add_action('wp_ajax_dmhsc_show','dmhsc_show');
add_action('wp_ajax_nopriv_dmhsc_show','dmhsc_show');
function check_https($host) {
$result = array('status'=>0, 'text'=> '<div class="not-available">Domain: '.$host.'</div>');
echo json_encode($result);
}
Problem
I want to show "Domain: domain name" when I submit the form. Form contains url field and submit button.
but I don't know it is not displaying the message written in check_https() function.
I am also getting error in console:
Uncaught SyntaxError: Unexpected token { in JSON at position 74
at JSON.parse (<anonymous>)
If I display the message without calling to function check_https(), it works.
What should be the problem.

Best method for firing and refiring AJAX via php

I'm trying to transcribe what my programmer told me. He and I may be doing this all wrong, so I need to make sure he and I am doing it in the right manner. Here is what we are trying to do:
I have a page on a website and within that page, I have a button. When you click on it, I want it to (via AJAX so the page doesn't refresh)
Send data (time capture) to the DB
See that the DB recorded the change and in turn return a different value back to the site
This would in turn change the button, noting that it is in a recording mode.
Think of it in this way, the button is a timer. On click, it records the time in the DB, and in the DB it also changes the state to recording. Since it is in the recording phase, somehow it gets sent back to the website page and changes the button showing that it is recording. Naturally clicking again would stop it and record the time in the DB.
Here is how the snippets are set up (not working I think) ATM:
*sidenote: This is in Joomla
Page:
<script src="js/ajax_link.js" type="text/javascript"></script>
<div id="ajaxlink" onclick="loadurl('php/ticket_timer.php',<?php echo $row->id?>)">Start Time</div>
ajax_link.js
function loadurl(dest,ticket_id) {
jQuery.ajax({
url: dest,
type: "POST",
data: "ticket_id="+ticket_id,
success: function(msg){
alert(msg);
jQuery('#ajaxlink').text("Timer Stop");
}
});
}
ticket_timer.php
<?php
define( '_JEXEC', 1 );
define( 'DS', DIRECTORY_SEPARATOR );
define( 'JPATH_BASE', $_SERVER[ 'DOCUMENT_ROOT' ] );
require_once( JPATH_BASE . DS . 'includes' . DS . 'defines.php' );
require_once( JPATH_BASE . DS . 'includes' . DS . 'framework.php' );
require_once( JPATH_BASE . DS . 'libraries' . DS . 'joomla' . DS . 'factory.php' );
$mainframe =& JFactory::getApplication('site');
$ticket_id = $_POST['ticket_id'];
$user =& JFactory::getUser();
$user_id=$user->get('id');
//DB Query
$db = JFactory::getDbo();
$query = $db->getQuery(true);
$query->select($db->quoteName(array('id', 'ticket_id', 'user_id', 'times','current_time')));
$query->from($db->quoteName('#__support_ticket_times'));
$query->where($db->quoteName('ticket_id') . ' LIKE '. $db->quote($ticket_id));
$query->where('ticket_id = '. $ticket_id, 'AND')
->where('user_id=' . $user_id );
$db->setQuery($query);
// Load the results as a list of stdClass objects (see later for more options on retrieving data).
$results = $db->loadObjectList();
$current_time=$results[0]->current_time;
$times=$results[0]->times;
$id_results = $db->loadColumn();
$db->setQuery($idquery);
$timesString = $times . ',' . date('Y-m-d g:i');
echo($timesString);
if(empty($results[0])){
$values = array(max($id_results)+1, $ticket_id, $user_id, $db->quote(date('Y-m-d g:i')),$db->quote(date('Y-m-d g:i')));
//echo "YOU GET NOTHING, MAKING NEW ROW";
$columns = array('id', 'ticket_id', 'user_id', 'times','current_time');
// Prepare the insert query.
$insert_query = $db->getQuery(true);
$insert_query
->insert($db->quoteName('#__support_ticket_times'))
->columns($db->quoteName($columns))
->values(implode(',', $values));
// Set the query using our newly populated query object and execute it.
$db->setQuery($insert_query);
$db->query();
}else{
//echo("CURRENT TIME" . $current_time);
if($current_time=='0000-00-00 00:00:00'){
echo "NO TIME";
$fields = array(
$db->quoteName('current_time'). '=' . $db->quote(date('Y-m-d g:i'))
);
}
// . $db->quote(date('Y-m-d g:i'))
else{
echo "ADD TIME";
$fields = array($db->quoteName('times') . '=' . $db->quote($timesString) ,
$db->quoteName('current_time'). "='0000-00-00 00:00:00'"
);
}
$update_query = $db->getQuery(true);
$conditions = array(
$db->quoteName('user_id') . '=' . $db->quote($user_id),
$db->quoteName('ticket_id') . '=' . $db->quote($ticket_id)
);
$update_query->update($db->quoteName('#__support_ticket_times'))->set($fields)->where($conditions);
$db->setQuery($update_query);
$db->query();
//echo $update_query;
}
?>
Can anyone suggest how to get the timer to fire back that the timer has started? Are we butchering this and is there a better way to code this?
You need to exchange some data between the PHP and the HTML page. The HTML page can be modified with Javascript, of course. The notation typically used for this kind of an exchange is JSON. In this example, we're using JSON to:
Send a boolean timerRunning to the PHP,
change the value in PHP,
send a reply,
modify the HTML page, and
store the timerRunning value in the HTML element.
So, for starters, we pass some data from the HTML element to Javascript using the HTML5 data- attributes, like this:
<div id="ajaxlink" data-url="php/ticket_timer.php" data-ticketId="<?php echo $row->id; ?> " data-timerRunning="false">Start Time</div>
In your Javascript, we access the parameters set above and send them to your PHP script via AJAX:
jQuery(document).ready(function($){
// Add an 'onClick' handler to the element
jQuery('#ajaxlink').on('click', function(event) {
// Get the url and ticket_id from the element's 'data-' attributes
var url = jQuery(this).data( 'url' );
var data = {
'ticketId' : jQuery(this).data( 'ticketId' ),
'timerRunning' : jQuery(this).data( 'timerRunning' )
}
// Send an AJAX request
jQuery.ajax({
type: 'POST',
url: url,
data: data
}).done( function(response) {
// This runs when the AJAX request succeeds
if ( 'undefined' == typeof( response.timerRunning ) ) {
alert( 'The server didn\'t tell the timer state' );
return;
}
// Store the value in the element
jQuery('#ajaxlink').data( 'timerRunning', response.timerRunning );
// Change the element HTML
if ( response.timerRunning )
jQuery('#ajaxlink').html( 'Stop Timer' );
else
jQuery('#ajaxlink').html( 'Start Timer' );
}).fail( function(jqXHR, textStatus, errorThrown ) {
// This runs when the AJAX request fails
alert( 'The AJAX request failed with the error ' + errorThrown );
});
});
});
In your PHP script, check the timerRunning value and react accordingly:
if ( isset( $_POST['timerRunning'] ) ) { // Check that we got some value for 'timerRunning'
if ( $_POST['timerRunning'] ) {
// The 'timerRunning' value is TRUE, the timer is running, now stop it
your_code_here_to_stop_the_timer();
$reply = array( 'timerRunning' => false );
} else {
// The 'timerRunning' value is FALSE, the timer isn't running, now start it
your_code_here_to_start_the_timer_and_whatever();
$reply = array( 'timerRunning' => true );
}
// Send the correct header for a JSON response
header('Content-type: application/json');
// Send the $reply array encoded as JSON
echo json_encode( $reply );
}

ajax not able to pass variable to php

I have a slider which uses javascript. I am trying to update the display of my web page based on the slider values. I tried to use ajax function to send the data to another PHP page to update the display. But I am not getting anything in my page. Here is my code so far.
<?php
$i = 1;
while (++$i <= $_SESSION['totalcolumns']) {
$range = $_SESSION["min-column-$i"] . ',' . $_SESSION["max-column-$i"];?>
<br><?php echo "Keyword" ?>
<?php echo $i -1 ?>
<br><input type="text" data-slider="true" data-slider-range="<?php echo $range ?>" data-slider-step="1">
<?php } ?>
<button type="button" onclick="loadXMLDoc()">Update</button>
<script>
$("[data-slider]")
.each(function () {
var range;
var input = $(this);
$("<span>").addClass("output")
.insertAfter(input);
range = input.data("slider-range").split(",");
$("<span>").addClass("range")
.html(range[0])
.insertBefore(input);
$("<span>").addClass("range")
.html(range[1])
.insertAfter(input);
})
.bind("slider:ready slider:changed", function (event, data) {
$(this).nextAll(".output:first")
.html(data.value.toFixed(2));
});
</script>
<script>
function loadXMLDoc()
{
alert "Am I coming here";
$.ajax({
type: "POST",
url: 'update.php',
data: { value : data.value },
success: function(data)
{
alert("success!");
}
});
}
</script>
I read in another post that javascript variables are available across functions and so I am trying to use the variable data.value inside my another javascript function loadXMLDoc(). But I do not see the value getting displayed in my update.php page. My update.php file is as below.
<?php
if(isset($_POST['value']))
{
$uid = $_POST['value'];
echo "Am I getting printed";
echo $uid;
}
?>
Can someone please help me on this?
In the loadXMLDoc function I don't see data defined anywhere. I think that could be one of the problems. Also, when you're doing jquery ajax requests be sure to have a fail callback. The fail callback will tell you if the request fails which can be very informative.
var jqxhr = $.ajax( "example.php" )
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
To make the data variable accessible in the XMLLoadDoc function you could try putting it in the global scope (kind of a 'no-no', but its OK for a use case like this). So, at the top, declare var masterData, then when you have data in the .bind callback set masterData = data; and then in loadXMLDoc refer to masterData

Categories