So below are some of the actions that my plugin is supposed to perform when submitting the survey. On my console I should get 'response saved', but I get absolutely nothing, not even 'Could not save response'. I have looked through the code, but I can't see why ajax is not performing the function of saving the response. Can anyone else see what is going on here?
// 5.3
// hint: ajax form handler for saving question responses expects: $_POST['survey_id'] and $_POST['response_id']
function ssp_ajax_save_response() {
$result = array(
'status'=>0,
'message'=>'Could not save response.',
'survey_complete'=>false
);
try {
$survey_id = (isset($_POST['survey_id'])) ? (int)$_POST['survey_id']: 0;
$response_id = (isset($_POST['response_id'])) ? (int)$_POST['response_id']: 0;
$saved = ssp_save_response($survey_id, $response_id);
if($saved) {
$survey = get_post($survey_id);
if(isset($survey->post_type) && $survey->post_type = 'ssp_survey') {
$complete = true;
$html = ssp_get_question_html($survey_id);
$result = array(
'status'=>1,
'message'=>'Response saved!',
'survey_complete'=>$complete,
'html'=>$html
);
} else {
$result['message'].='Invalid survey.';
}
}
} catch(Exception $e) {
// php error
}
ssp_return_json($result);
}
// 5.4
// hint: saves single question response
function ssp_save_response($survey_id, $response_id) {
global $wpdb;
$return_value = false;
try {
$ip_address = ssp_get_client_ip();
// get question post object
$survey = get_post($survey_id);
if($survey->post_type == 'ssp_survey'):
// get current timestamp
$now = new DateTime();
$its = $now->format('Y-m-d H:i:s');
// query sql
$sql = "INSERT INTO {$wpdb->prefix}ssp_survey_responses (ip_address, survey_id, response_id, created_at) VALUES (%s, %d, %d, %s) ON DUPLICATE KEY UPDATE survey_id = %d";
// prepare query
$sql = $wpdb->prepare($sql, $ip_address, $survey_id, $response_id, $ts, $survey_id);
// run query
$entry_id = $wpdb->query($sql);
// If response saved successfully...
if($entry_id):
// return true
$return_value = true;
endif;
endif;
} catch(Exception $e) {
// php error
ssp_debug('ssp_save_response php error', $e->getMessage());
}
return $return_value;
}
Someone made me aware that I need to add the jQuery code and so here it is and thank you in advance.
jQuery(document).ready(function($){
// do something after jQuery has loaded
ssp_debug('public js script loaded!');
// hint: displays a message and data in the console debugger
function ssp_debug(msg, data) {
try {
console.log(msg);
if(typeof data !== "undefined") {
console.log(data);
}
} catch(e) {
}
}
// setup our wp ajax URL
var wpajax_url = document.location.protocol + '//' + document.location.host + '/wp-admin/admin-ajax.php';
// bind custom function to survey form submit event
$(document).on('submit', 'ssp-survey-form', function(e){
// prevent form from submitting normally
e.preventDefault();
$form = $(this);
$survey = $form.closest('.ssp-survey');
// get selected radio button
$selected = $('input[name^="ssp_question_"]:checked', $form);
// split field name into array
var name_arr = $selected.attr('name').split('_');
// get the survey id from the last item in name array
var survey_id = name_arr[2];
// get the response id from the value of the selected item
var response_id = $selected.val();
var data = {
_wpnonce: $('[name="wp_nonce"]', $form).val(),
_wp_http_referer: $('[name="wp_http_referer"]', $form).val(),
survey_id: survey_id,
response_id: response_id
};
ssp_debug('data', data);
// get the closest dl.ssp-question element
$dl = $selected.closest('dl.ssp-question');
// submit the chosen item via ajax
$.ajax({
cache: false,
method: 'post',
url: wpajax_url + '?action=ssp_ajax_save_response',
dataType: 'json',
data: data,
success: function(response) {
// return response in console for debugging...
ssp_debug(response);
// If submission was successful...
if(response.status) {
// update the html of the current li
$dl.replaceWith(response.html);
// hide survey content message
$('.ssp-survey-footer', $survey).hide();
} else {
// If submission was unsuccessful...
// notify user
alert(response.message);
}
},
error: function(jqXHR, textStatus, errorThrown) {
// output error information for debugging...
ssp_debug('error', jqXHR);
ssp_debug('textStatus', textStatus);
ssp_debug('errorThrown', errorThrown);
}
});
});
});
Related
I have this codes in process.php:
$users = $_POST['users']; // Sample: "user1, user2, user5"
$users = explode(', ', $users);
$step = 0;
foreach ($users as $r) {
$user_email = get_user_email($r); // Get email of each user
if (!empty($user_email)) {
send_w_mail(); // Send email to each user
$step++;
echo json_encode(
['step' => $step, 'all' => count($users)]
); // echo output
}
}
And this is my ajax call in index.php:
$("#send-message").click(function () {
$.ajax({
url: global_base_url + 'process.php', // global_base_url defined.
async : true,
type: 'POST',
data: {'users': input_users}, // input_users is val() of a input.
encoding: 'UTF-8',
success: function (data) {
data = $.trim(data);
if (data){
data = $.parseJSON(data);
var p_value = parseInt(data.step*100)/data.all;
set_progressbar_value(p_value); // set progressbar value. sample: 23%
}
}
});
});
This codes don't have any problem for execute and showing result.
But I want to Continuously get output json data from process.php in order to show process of each $step in Percent unit in a bootstrap process-bar;
I found some function like ignore_user_abort(), ob_clean() and ob_flush() but don't know how can I solve my problem with them.
How Can I do this? Please help me to solve the problem.
Thanks a lot.
There are two ways of approaching this problem
Websocket
Long polling
I will be describing the long polling method here:
$users = $_POST['users']; // Sample: "user1, user2, user5"
$users = explode(', ', $users);
$step = 0;
foreach ($users as $r) {
$user_email = get_user_email($r); // Get email of each user
if (!empty($user_email)) {
send_w_mail(); // Send email to each user
$step++;
echo json_encode(
['step' => $step, 'all' => count($users)]
); // echo output
//Flush the output to browser
flush();
ob_flush();
}
Jquery does not provide api for XMLHttpRequest.readyState == 3 (Loading docs here) so we need to use raw XMLHttpRequest object
$("#send-message").click(function () {
var prev_response = "";
var xhr = new XMLHttpRequest();
xhr.open("POST", global_base_url + 'process.php', true);
//Send the proper header information along with the request
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.onreadystatechange = function() {//Call a function when the state changes.
if(xhr.readyState == 3) {
// Partial content loaded. remove the previous response
var partial_response = xhr.responseText.replace(prev_response,"");
prev_response = xhr.responseText;
//parse the data and do your stuff
var data = $.parseJSON(partial_response);
var p_value = parseInt(data.step*100)/data.all;
set_progressbar_value(p_value);
}
else if(xhr.readyState == 4 && xhr.status == 200){
set_progressbar_value(100);
console.log("Completed");
}
}
xhr.send("users="+ input_users);
});
I'm creating an ajax script to update a few fields in the database. I got it to a point where it worked but it sent the user to the php script instead of staying on the page so I did some googling, and people suggested using either return false; or e.preventDefault() however, if I do this, it breaks the php script on the other page and returns a fatal error. I might be missing something being newish to AJAX but it all looks right to me
JS:
$(document).ready(function() {
var form = $('form#edit_child_form'),
data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$('#submit_btn').on('click', function(e) {
e.preventDefault();
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'post',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = ". $parent_id ." ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = $child_row[0]");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
it's probably something really small that I've just missed but not sure what - any ideas?
my solution:
I var_dumped $_GET and it returned null - changed to $_REQUEST and it got my data so all good :) thanks for suggestions
Try the following instead.
I moved the form data inside click and enclosed the mysql queries values in single quotes.
JS:
$(document).ready(function() {
var form = $('form#edit_child_form');
$('#submit_btn').on('click', function(e) {
e.preventDefault();
var data = form.serializeArray();
data.push({'parent_id': $('input[name="parent_id"]').val()});
$.ajax({
url: form.prop('action'),
dataType: 'json',
type: 'get',
data: data,
success: function(data) {
if (data.success) {
window.opener.$.growlUI(data.msg);
}
},
error: function(data) {
if (!data.success) {
window.opener.$.growlUI(data.msg);
}
}
});
});
})
AJAX:
<?php
//mysql db vars here (removed on SO)
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
$get_child_ids = $dbi->query("SELECT child_ids FROM ids WHERE parent = '". $parent_id ."' ORDER BY id"); //returns as object
$count = 0;
$res = array();
while ($child_row = $get_child_ids->fetch_row())
{
try
{
$dbi->query("UPDATE ids SET description = '$descriptions[$count]', child_id = '$child_id[$count]' WHERE parent_id = '$child_row[0]'");
$res['success'] = true;
$res['msg'] = 'Success! DDI(s) updated';
} catch (Exception $e) {
$res['success'] = true;
$res['msg'] = 'Error! '. $e->getMessage();
}
$count++;
}
echo json_encode($res);
You are using an AJAX POST request so in your PHP you should be using $_POST and not $_GET.
You can just change this:
$descriptions = $_GET['descriptions'];
$child_id = $_GET['child_id'];
$parent_id = $_GET['parent_id'];
to this:
$descriptions = $_POST['descriptions'];
$child_id = $_POST['child_id'];
$parent_id = $_POST['parent_id'];
i am using a form validation plugin and in my js file i have this for input and checkbox value pass to json
$('form').submit(function(event) {
$('.form-group').removeClass('has-error'); // remove the error class
$('.help-block').remove(); // remove the error text
var chkbox = new Array();
$('input:checked').each(function() {
chkbox.push(parseint($(this).val()));
});
var formData = {
'company_name': $('input[name=company_name]').val(),
}
$.ajax({
type: 'POST', // define the type of HTTP verb we want to use (POST for our form)
url: 'process.php',
data: formData,chbox,
dataType: 'json',
encode: true
}).done(function(data) {
console.log(data);
if ( ! data.success) {
if (data.errors.company_name) {
$('#company_name-group').addClass('has-error');
$('#company_name-group').append('<div class="help-block">' + data.errors.company_name + '</div>');
Then in php
$errors = array();
$data = array();
if (empty($_POST['company_name']))
$errors['company_name'] = 'Company Name is required.';
if ( ! empty($errors)) {
// if there are items in our errors array, return those errors
$data['success'] = false;
$data['errors'] = $errors;
} else {
$company_name=mysqli_real_escape_string($con,$_POST['company_name']);
$chkbox = $_POST['chkbox'];
$chkNew = "";
foreach($chkbox as $chkNew1)
{
$chkNew .= $chkNew1 . ",";
}
$ins_query="insert into xxx(`company_name`,`Job`)values('company_name','$chkNew');"
retval = mysqli_query( $con , $ins_query);
$data['success'] = true;
$data['message'] = 'Success!';
}
echo json_encode($data);
This work perfectly fine for insert values of form on db values but it stops in my process.php file and doesnt show the message on page .When i remove chkbox from js file form is validated and shows message success in succesfull insertion to db .
The last character in $chkNew is ,.
You should remove it.
Try to add this after foreach:
$chkNew= trim($chkNew, ',');
The ajax call successfully update the record but doesn't return the string of echo. This script was working before but might be because of some upgrade it stops working. It is working fine on my local system but when I move it to bluehost server then it does not work.
Here is my Ajax call:
// call to ajax script to update site
function autopost_update_site() {
// get base directory url
var baseDir = jQuery('#baseDir').val();
var id = jQuery('#site_id').val();
var site_name = jQuery('#site_name').val();
var site_url = jQuery('#site_url').val();
var is_active;
if ( jQuery('#active_radio').is(':checked') ){
is_active = '1';
} else {
is_active = '0';
}
var username = jQuery('#login_username').val();
var login_pass = jQuery('#login_pass').val();
// call to ajax script to update script
jQuery.ajax( {
type: "POST",
url: baseDir + "/autopost_ajax_actions.php",
data: "id=" + id + "&site_name=" + site_name + "&site_url=" + site_url + "&is_active="+ is_active + "&username=" + username + "&login_pass="+login_pass +"&action=update_site",
beforeSend: function() {
jQuery('#update_site_button').attr("disabled", true);
// shortcode edit button
jQuery('#update_site_button').html('Updating...');
// admin page edit button
jQuery('#update_site_button').val('Updating...');
},
complete: function() {
jQuery('#update_site_button').attr("disabled", false);
// shortcode edit button
jQuery('#update_site_button').html('Update');
// admin page edit button
jQuery('#update_site_button').val('Update');
},
success: function(data) {
alert("Result: " + data); // NOTHING IS HAPPENING HERE, NO ALERT DATA
if (jQuery.trim(data) === "success") {
alert("Site updated.");
// refresh page
window.setTimeout('location.reload()', 200);
} else {
alert("Some error occured, Please try again.");
}
}
});
}
Here is my custom php script for ajax actions:
// update site
if ( $_POST['action'] == 'update_site' && isset ($_POST['id']) ) {
// collect site data
$site_name = $wpdb->escape($_POST['site_name']);
$site_id = intval($wpdb->escape($_POST['id']));
$site_url = $wpdb->escape($_POST['site_url']);
$username = $wpdb->escape($_POST['username']);
$login_pass = $wpdb->escape($_POST['login_pass']);
$is_active = $wpdb->escape($_POST['is_active']);
$query = $wpdb->prepare("UPDATE " . $autopost_sites_table_name . " SET site_name = %s, site_url = %s, username = %s, login_pass = %s, is_active = %s WHERE id = %s", $site_name, $site_url, $username, $login_pass, $is_active, $site_id);
#$log->LogDebug($query);
// execute query
$result = $wpdb->query($query);
#$log->LogDebug($result);
if ( $result !== FALSE || $result !== 0) {
// return success
$response = "success";
#$log->LogDebug($response);
echo $response; // THIS RESPONSE IS NOT SHOWING ON AJAX SUCCESS
} else {
$log->LogError("Failed to update site with ID: " . $_POST['id']);
echo "Failed to update site.";
}
}
Can anyone tell me what is missing?
Change data as follows
data:{
id:id,
site_name:site_name,
site_url:site_url ,
is_active:is_active ,
username:username,
login_pass:login_pass,
action:"update_site"
}
As It is mentioned that the script is working great on local but not working on server. So it was some server issue and I was getting error for "Access-Control-Allow-Origin" in chrome network.
I just added
header('Access-Control-Allow-Origin: *');
to my ajax action script and it worked! Thanks
after
echo $response;
put
die();
See http://codex.wordpress.org/AJAX_in_Plugins
In the example it says:
function my_action_callback() {
global $wpdb; // this is how you get access to the database
$whatever = intval( $_POST['whatever'] );
$whatever += 10;
echo $whatever;
die(); // this is required to return a proper result
}
I am getting a NaN error in my ajax callback function and can only think it has to do with an array in PHP. I have been trying to find ways to correct it but have come up against a brick wall.
What is supposed to happen is that PHP queries the database and if there are no results send a response to ajax and issue the error message. However, all I am getting is NaN. The error stems from the success code below.
I would be grateful if someone could point out my error.
PHP code:
$duplicates = array();
foreach ($boxnumber as $val) {
if ($val != "") {
mysql_select_db($database_logistor, $logistor);
$sql = "SELECT custref FROM boxes WHERE custref='$val' and status = 'In'";
$qry = mysql_query($sql) or die(mysql_error());
if (mysql_num_rows($qry) < 1) {
$duplicates[] = '[ ' . $val . ' ]';
$flag = 1;
} else {
$duplicates[] = $val;
}
}
}
//response array with status code and message
$response_array = array();
if (!empty($duplicates)) {
if ($flag == 1) {
//set the response
$response_array['status'] = 'error';
$response_array['message'] = 'ERROR: ' . implode(',', $duplicates) . ' needs to be in the database to be retrived.';
}
//if no errors
} else {
//set the response
$response_array['status'] = 'success';
$response_array['message'] = 'All items retrieved successfully';
$response_array['info'] = ' You retrieved a total of: ' . $boxcount . ' boxes';
}
//send the response back
echo json_encode($response_array);
Relevant ajax:
$("#brtv-result").html(msg.message+msg.info);
jQuery code:
$(function() {
$("#BRV_brtrv").submit(function() {
var send = $(this).serialize();
$.ajax({
type: "POST",
url: "boxrtrv.php",
cache: false,
data: send,
dataType: "json",
success: function(msg) {
if( msg.status === 'error') {
$("#brtv-result").fadeIn(1000).delay(1000).fadeOut(1000);
$("#brtv-result").removeClass('error');
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message);
}
else {
$("#brtv-result").fadeIn(2000).delay(2000).fadeOut(2000);
$("#brtv-result").removeClass('error');
$("#brtv-result").addClass('success');
$("#brtv-result").addClass(msg.status);
$("#brtv-result").html(msg.message+msg.info);
//location.reload(true);
//$('#brtv-result').addClass("result_msg").html("You have successfully retrieved: "+data.boxnumber).show(1000).delay(4000).fadeOut(4000);
$("#BRV-brtrv-slider").val(0).slider("refresh");
$("input[type='radio']").attr("checked",false).checkboxradio("refresh");
var myselect = $("select#BRV-brtrv-department");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
var myselect = $("select#BRV-brtrv-address");
myselect[0].selectedIndex = 0;
myselect.selectmenu("refresh");
}
},
error:function(){
$("#brtv-result").show();
$("#brtv-result").removeClass('success');
$("#brtv-result").addClass('error');
$("#brtv-result").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
});
NaN (pronounced nan, rhymes with man) only happens when you try to do an operation which requires a number operand. For example, when you try to Number('man') you'll get this error.
What you return from your PHP file, is simply an array which contains simply data. So, the problem is in your JavaScript. You have to send more parts of your JavaScript, so that we can see it thoroughly.
However, I recommend that you use Firebug and set a breakpint at the correct place (the callback function start), and check the stack trace of the calls to diagnose the problem.