ajax function
<script type="text/javascript">
var timeOutID =0;
var checkScores = function () {
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/countScoreCh',
success: function(response) {
if(response == false){
timeOutID = setTimeout(checkScores, 3000);
} else {
jsn = JSON.parse(response);
score= jsn.scoreCH;
$('#progressbar').progressbar({
value: score
});
clearTimeout(timeOutID);
}
}
});
}
timeOutID = setTimeout(checkScores,1000);
</script>
Controller
public function countScoreCh(){
$id = $this->session->userdata('userID');
$data['getScore'] = $this->lawmodel->battleUserID($id);
foreach($data['getScore'] as $row){
$scoreCH = $row->challengerScore;
echo json_encode(array('scoreCH' => $scoreCH));
}
}
Im having a problem..im using a progress bar..my idea is making the progress bar like a Hit Point/Health bar..but it seems that when i put the $('#progressbar').progressbar it will not get the value from jsn.scoreCH..jst disregards the response == false it still working i tried using console log..But when i put this code..it will not be read and display the output..
$('#progressbar').progressbar({
value: score
});
You can omit JSON.parse(response). Just use dataType: 'json'
$.ajax({
url: "http://127.0.0.1/ProgVsProg/main/countScoreCh",
dataType: 'json'
success: function(response) {
if(response.scoreCH == undefined){
timeOutID = setTimeout(checkScores, 3000);
} else {
$('#progressbar').progressbar({
value: response.scoreCH
});
clearTimeout(timeOutID);
}
}
});
Related
I´m traying to do logging in my web with ajax. But i need generated google key when i do click in login, and before to do login. I have this function:
$('#main-login-form').on('submit', function(e){
renewKeyRecaptcha();
//e.preventDefault();
let key = $("#recaptchaResponse").val();
console.log(key);
if(key != null || key != ""){
var $this = $(this);
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
var data = $this.serializeArray();
data.push({name: 'currentName', value: config.url.currentName});
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: data,
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
$(location).attr('href', response.redirect);
}
console.log(response);
},
error: function (jqXHR) {
var response = JSON.parse(jqXHR.responseText);
if (response.errors.password) {
$($this).find('input[name="password"]').addClass('is-invalid');
$($this).find('.password-error').html(response.errors.password);
} else if (response.errors.email) {
$($this).find('input[name="email"]').addClass('is-invalid');
$($this).find('.email-error').html(response.errors.email);
} else if (response.errors.gRecaptchaResponse) {
$($this).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$($this).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}
});
this function call to renewKeyRecaptcha(); that generated key, but i need to do click login twice and before i´m login... i need to do once click in login and generate key and login... But i can´t. I don´t know if i´m doing well or i would do to another way.
My function that generate key:
function renewKeyRecaptcha(){
// add key google to input
var key = config.url.recaptchaGoogle;
grecaptcha.ready(function() {
grecaptcha.execute(key, {action: 'login'}).then(function(token) {
$("#recaptchaResponse").val(token);
$("#recaptchaResponseRegister").val(token);
});
});
}
this function run ok.
Thanks for help.
I resolve my question with:
$("#submitLogin").on("click", function(e){
renewKeyRecaptcha();
e.preventDefault();
setTimeout(function(){
$(this).find('input').removeClass('is-invalid');
$(this).find('.error').html('');
$this = $('#main-login-form');
var data = $this.serializeArray();
data.push({name: 'currentName', value: config.url.currentName});
$.ajax({
type: $this.attr('method'),
url: $this.attr('action'),
data: data,
dataType: $this.data('type'),
success: function (response) {
if(response.success) {
$(location).attr('href', response.redirect);
}
console.log(response);
},
error: function (jqXHR) {
var response = JSON.parse(jqXHR.responseText);
if (response.errors.password) {
$($this).find('input[name="password"]').addClass('is-invalid');
$($this).find('.password-error').html(response.errors.password);
} else if (response.errors.email) {
$($this).find('input[name="email"]').addClass('is-invalid');
$($this).find('.email-error').html(response.errors.email);
} else if (response.errors.gRecaptchaResponse) {
$($this).find('input[name="g-recaptcha-response"]').addClass('is-invalid');
$($this).find('.g-recaptcha-response-error').html(response.errors.gRecaptchaResponse);
}
}
});
}, 3000);
I am validating a form with ajax and jquery in WordPress post comments textarea for regex. But there is an issue when i want to alert a error message with return false. Its working fine with invalid data and showing alert and is not submitting. But when i put valid data then form is not submit. May be issue with return false.
I tried making variable and store true & false and apply condition out the ajax success block but did not work for me.
Its working fine when i do it with core php, ajax, jquery but not working in WordPress .
Here is my ajax, jquery code.
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And i'm using wordpress wp_ajax hook.
And here is my php code.
<?php
function nmp_process_func (){
$comment = $_REQUEST['comment'];
preg_match_all("/(->|;|=|<|>|{|})/", $comment, $matches, PREG_SET_ORDER);
$count = 0;
foreach ($matches as $val) {
$count++;
}
echo $count;
wp_die();
}
?>
Thanks in advance.
Finally, I just figured it out by myself.
Just put async: false in ajax call. And now it is working fine. Plus create an empty variable and store Boolean values in it and then after ajax call return that variable.
Here is my previous code:
require 'nmp_process.php';
add_action('wp_ajax_nmp_process_ajax', 'nmp_process_func');
add_action('wp_ajax_nopriv_nmp_process_ajax', 'nmp_process_func');
add_action('wp_head', 'no_markup');
function no_markup() {
?>
<script type="text/javascript">
jQuery(document).ready(function () {
jQuery('form').submit(function (e) {
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}
}
});
return false;
});
});
</script>
<?php
}
And the issue that i resolved is,
New code
var returnval = false;
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
async: false, // Add this
data: 'action=nmp_process_ajax&comment=' + comment,
Why i use it
Async:False will hold the execution of rest code. Once you get response of ajax, only then, rest of the code will execute.
And Then simply store Boolean in variable like this ,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
returnval = false;
} else {
returnval = true;
}
}
});
// Prevent Default Submission Form
return returnval; });
That's it.
Thanks for the answers by the way.
Try doing a ajax call with a click event and if the fields are valid you submit the form:
jQuery(document).ready(function () {
jQuery("input[type=submit]").click(function (e) {
var form = $(this).closest('form');
e.preventDefault();
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: {'action':'nmp_process_ajax','comment':comment},
success: function (res) {
var count = parseInt(res);
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
} else {
form.submit();
}
}
});
});
});
note : you call need to call that function in php and return only the count!
Instead of submitting the form bind the submit button to a click event.
jQuery("input[type=submit]").on("click",function(){
//ajax call here
var comment = jQuery('#comment').val();
jQuery.ajax({
method: "POST",
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: 'action=nmp_process_ajax&comment=' + comment,
success: function (res) {
count = res;
if (count > 10) {
alert("Sorry You Can't Put Code Here.");
return false;
}else{
jQuery("form").submit();
}
}
});
return false;
})
Plus also its a good idea to put return type to you ajax request.
Let me know if this works.
I have a function which gets the value of each checked checkbox i was able to get the value successfully by using an alert example it results to 1,2,3 which is correct but when i get it from php the array size is always 1.
HTML CODE:
function doit() {
var p = [];
$('input.cb').each(function () {
if ($(this).is(':checked')) {
p.push($(this).attr('rel'));
}
});
$.ajax( {
url:'page.php',
type:'POST',
data: {list:p},
success: function(res) {
alert(res);
}
});
alert(p)
}
PHP CODE:
<?php
$list = $_POST['list'];
echo count($list);
?>
Use this code :
var jsonData = JSON.stringify(p);
$.ajax( {
url:'page.php',
type:'POST',
data: {list:jsonData},
success: function(res) {
alert(res);
}
});
And in PHP :
$list = json_decode($_POST['list']);
i am new to cakephp and trying to send data from ajax to my controller action..
i have a popup model in which there is a input box ..i want to grab that value and send to controller without page refresh
here is my code ..
<a class="button anthracite-gradient" onclick="openPrompt()">submit </a>
my javascript
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
url:"/cakephp/controller/action/",
success : function(data) {
alert(value); //value right now is in this variable ... i want to send this variable value to the controller
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
myController
public function action(){
if( $this->request->is('ajax') ) {
$new = $this->request->data;
echo "ok"
return;
}
}
i want to first get the value here and then send the response to may ajax request
Its simple post the value to the controller and do what you want , in ajax request bind the value in data:{value_to_send:value} and get in controller
function openPrompt()
{
var cancelled = true;
$.modal.prompt('Please enter a value:', function(value)
{
$.ajax({
type:"POST",
data:{value_to_send:value},
url:"/cakephp/controller/action/",
success : function(data) {
alert(data);// will alert "ok"
},
error : function() {
alert("false");
}
});
}, function()
{
});
};
</script>
public function action(){
if( $this->request->is('ajax') ) {
// echo $_POST['value_to_send'];
echo $value = $this->request->data('value_to_send');
//or debug($this->request->data);
echo "ok"
die();
}
}
For more see accessing-post-data
I will give you some example. In my case, list out book list as a smart search while typing on text box.
$( ".selectBook" ).each(function(){
$(this).keyup(function( event ) {
var tri = $(this).val();
var oPrnt = $(this).parents('.smartsearch');
var str = '';
if(tri.length > 2){
$.ajax({
type: "POST",
url: "/utility/getbooks/",
data: JSON.stringify({string: tri, activeonly:false}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$.each(data, function(key, val) {
str += '<li id="a'+key+'" term="'+val+'" data-did="'+key+'">'+val+'</li>';
});
oPrnt.find("ul.result").html(str);
},
error: function (errormessage) {
oPrnt.find("ul.result").html('<li><b>No Results</b></li>');
}
});
oPrnt.find("ul.result").slideDown(100);
}
});
});
And in the controller, action (getbooks Action in UtilityController in my case)
public function getbooks($string = '', $activeonly = true){
$this->autoRender = false;
if( $this->request->is('ajax') ) {
$data = $this->request->input('json_decode');
$string = $data->string;
$activeonly = $data->activeonly;
}
$aReturn = array();
// ... fetch books data from DB goes here...
$aResult = $this->Book->fetch('list');
foreach($aResult as $r){
if(isset($r['bookname'])){
$aReturn[$r['id']] = $r['bookname'];
}
}
return json_encode($aReturn);
}
I have multiple ajax requests and when one of them can't get data I want , I re-send it until it can get data .
the problem that I can't stop it after it gets data . Is there's a break or something equivalent to it in ajax ?
I tried clearinterval but it didn't work
here's my functions :
function ajaxGetServerDatabase(Div,val,interval){
console.log(val);
dbs[val]=new Array();
$('#bck_action').val('get_DB');
$('#server_ip').val(val);
post_data = $('#'+Div+' *').serialize();
$.ajax({
type: "POST",
url: document.URL,
data: post_data,
dataType: "text",
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(this.interval); // ????
}
}
});
return false;
}
function ajaxGetDatabase(Div,ips,interval){
$.each(ips,function(i,val){
dbs[val]=new Array();
$('#bck_action').val('get_DB');
$('#server_ip').val(val);
post_data = $('#'+Div+' *').serialize();
// console.log(post_data);
$.ajax({
type: "POST",
url: document.URL,
data: post_data,
dataType: "text",
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
}
else
{
setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
}
});
});
return false;
}
I call it :
ajaxGetDatabase('tab_backup',ips,3000);
var timer = null;
function ajaxGetServerDatabase(Div,val,interval){
//...
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(timer); // ????
}
//....
else
{
timer = setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
clearInterval has nothing to do with ajax. It's only a timer function which scope is to clear the timer set earlier with setInterval. If you really want to use a timer function you need either to attach a variable to the setInterval function, which you can clear with clearInterval setting as a parameter the id defined earlier in the setInterval.
var id = " ";
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(id);
}
else
id= setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
Or you can abort the code with ajax abort.
Maybe something close to this?
...
var stopAjax = 0; //switch is on
if(stopAjax == 0){
$.ajax({
...
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response);
stopAjax = 1; //switch is off
}
else{
setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"','"+interval+"')", interval);
}
}
});
}
Are you looking for the timeout setting perhaps? eg
$.ajax({
timeout: 10000,
...
});
http://api.jquery.com/jQuery.ajax/
here's the answer :
in ajaxGetDatabase :
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
}
else
{
id=setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"')", interval);
}
in ajaxGetServerDatabase :
success: function(response) {
if (response!='no_connection'){
dbs[val]=JSON.parse(response)
clearInterval(id);
}
}
with out scope parameter
var id;
to make it general and work for more than one server had stopped (more than one ajax request is failed) I used an array to save ids like this :
var ids=new Array();
ids[val]=setInterval("ajaxGetServerDatabase('"+Div+"','"+val+"')", interval);
clearInterval(ids[val]);