Why won't this ajax.done() work? - php

I'm writing a "betting" script so-to-speak, and making an automated system.
The bettor will be able to choose to increase the amount or decrease the amount on win or loss.
The PHP script I wrote returns echo json_encode(array('result' => 'win')); or 'loss' for a loss.
Why won't the below code update that value of the amount dependent upon the result?
$(document).ready(function(){
function updateValuesAuto() {
// Grab all the value just incase they're needed.
var multiplier_auto = $('#multiplier_auto').val();
var percentage_auto = $('#percentage_auto').val();
var bet_amount_auto = $('#bet_amount_auto').val();
var profit_amount_auto = $('#profit_amount_auto').val();
multiplier_auto = (100-1)/percentage_auto;
profit_amount_auto = (bet_amount_auto*multiplier_auto)-bet_amount_auto;
$('#multiplier_auto').val(multiplier_auto);
$('#percentage_auto').val(percentage_auto);
$('#bet_amount_auto').val(bet_amount_auto);
$('#profit_amount_auto').val(profit_amount_auto);
}
$('#multiplier_auto').keyup(updateValuesAuto);
$('#percentage_auto').keyup(updateValuesAuto);
$('#bet_amount_auto').keyup(updateValuesAuto);
$('#profit_amount_auto').keyup(updateValuesAuto);
var runI = null;
var $run = $('#start');
var $times = $('#amount_bets');
var $stop = $('#stop');
$run.on('click', function() {
event.preventDefault();
$(this).attr('disabled', true);
$stop.attr('disabled', false);
var ran = 0;
var val = parseInt($times.val(), 10);
if(isNaN(val) || val === 0 ) return false;
runI = setInterval(function() {
if( ran < val ) {
$.ajax({
url: './requests/bet.php',
type: 'POST',
data: { amount: $('#bet_amount_auto').val(), chance: $('#percentage_auto').val(), multiplier: $('#multiplier_auto').val(), profit: $('#profit_amount_auto').val() },
}).done(function(result) {
var result = JSON.parse(result);
if( result === 'win' ) {
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#wini').val();
}
else if( result === 'loss' ) {
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#lossi').val();
}
ran++;
});
}
else {
clearInterval(runI);
$run.attr('disabled', false);
}
}, 500);
});
$stop.on('click', function() {
event.preventDefault();
clearInterval(runI);
$run.attr('disabled', false);
});
});
Thanks.

You may want to trim down the code to the specifics of the problem if the answer does not help, but would behoove you to actually look at the data that gets sent back. It will be:
{"result":"win"}
So to access the result in the .done function, you'd need to use result.result.
Additionally, if you are sending JSON back, jQuery may be parsing it automatically and JSON.parse may result in an error. To get jQuery to do this, send the JSON content-type header via PHP:
header("Content-type: application/json");

I believe the problem is === because three equals is a strict operator which means value and type must be equal.
In your case it seems you're trying to make sure that result is type of JSON and equals to STRING
Try double-equals == maybe?
EDIT:
Oh got that now...
Actually, you can't assign value to the result of a function. So,
Change this:
$('#bet_amount_auto').val() = $('#bet_amount_auto').val() * $('#wini').val();
to
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#wini').val());

Two things:
1.You cannot set value to functions (You cannot put functions in the left side of an assignment)
2.result is JSON and you need to use result.result
$.ajax({
url: './requests/bet.php',
type: 'POST',
data: { amount: $('#bet_amount_auto').val(), chance: $('#percentage_auto').val(), multiplier: $('#multiplier_auto').val(), profit: $('#profit_amount_auto').val() },
}).done(function(result) {
if( result.result === 'win' ) {
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#wini').val()) ;
}
else if( result.result === 'loss' ) {
$('#bet_amount_auto').val($('#bet_amount_auto').val() * $('#lossi').val()) ;
}
ran++;
});

Related

Get multiple filter value parameters

I'm using this SO question to handle my filter search using checkbox.
This is the JS
$('input[type="checkbox"]').on('change', function (e) {
var data = {},
fdata = [],
loc = $('<a>', { href: window.location })[0];
$('input[type="checkbox"]').each(function (i) {
if (this.checked) {
if (!data.hasOwnProperty(this.name)) {
data[this.name] = [];
}
data[this.name].push(this.value);
}
});
// get all keys.
var keys = Object.keys(data);
var fdata = "";
// iterate over them and create the fdata
keys.forEach(function(key,i){
if (i>0) fdata += '&'; // if its not the first key add &
fdata += key+"="+data[key].join(',');
});
$.ajax({
type: "get",
url: "/ajax/get",
data: {
"_token": "{{ csrf_token() }}",
"fdata": fdata
},
success: function (response) {
$('#d2d-results').html(response);
}
});
if (history.pushState) {
history.pushState(null, null, loc.pathname + '?' + fdata);
}
});
And now I try to get the value of fdata to PHP.
On PHP I get this value of variable echo $_GET['fdata'];:
discount=Y&brand=BR0006,BR0003
What I want
$discount="Y";
$brand="BR0006,BR0003";
Is it possible to do like that?
To do what you want, you have to do two steps:
parse the query string into an array:
parse_str($_GET['fdata'], $result);
And then, extract the array as variables:
extract($result);
A few things to note:
Using extract is very insecure (and somewhat ugly). The user can put things like (for example) isAdmin=1 in the URL and the will affect your code. Basically, you cannot trust your variables anymore.
I would skip step 2 (the extract thingy), and use $result directly, for example echo $result['discount'].
it sounds like you are mixing post and get, is it something like this that you're after?
via GET:
if(isset($_GET['discount'])) {
$discount = $_GET['discount'];
} else {
$discount = '';
}
if(isset($_GET['brand'])) {
$brand = $_GET['brand'];
} else {
$brand = '';
}
POST method:
if(isset($_POST['discount'])) {
$discount = $_POST['discount'];
} else {
$discount = '';
}
if(isset($_POST['brand'])) {
$brand = $_POST['brand'];
} else {
$brand = '';
}
in one way , you can use explode function in php to separate your item from fdata
you can define some character in your client JS app for example ( , ) and then in explode function in php you must set separator equal comma character
explode function in PHP
explode(separator,string,limit)
in your example separator is comma and string is fdata ( limit optional
)
$fdata = $_GET['fdata'];
$arr_ = explode('&',$fdata);
and if you have some thing like this in fdata string
para1=223&para2=4353&para3=234
then $arr_ variable like this
$arr_ = [para1=223 , para2=4353 , para3=234];
and if you want separate value and key , you can do this again and use loop

Wordpress / Jquery ajax, get works post fails with jquery error

Hi all the following function will work and do exactly as I want it to but I want this to be a .post not a .get can anyone see a problem with the following? its pretty much straight from another answer on stack overflow and should work fine.
jQuery(document).ready(function() {
//This function adds a development.
jQuery('#add_dev').bind('submit', function(e) {
e.preventDefault();
var data = {
action: 'AjaxAddDev',
security: AjaxHandler.ajaxnonce,
name: jQuery('#dev_name').val(),
desc: jQuery('#dev_desc').val()
};
//alert(data['name']+data['desc']);
jQuery.get(
AjaxHandler.ajaxurl,
data,
function(response) {
// ERROR HANDLING
if (!response.success) {
// No data came back, maybe a security error
if (!response.data) {
//$('#my-answer').html('AJAX ERROR: no response');
alert("Problem adding Development");
} else {
//$('#my-answer').html(response.data.error);
alert(response.data);
}
} else {
//$('#my-answer').html(response.data);
alert("Problem adding Development");
}
}
);
});
});
The error I get when I set it to .post is:
l.send(n.hasContent && n.data || null), r = function (e, i) {
Which is line 2963 of an un-minified version of jquery
/*! jQuery v1.10.2 | (c) 2005, 2013 jQuery Foundation, Inc. | jquery.org/license */
Can anyone point me in the right Direction?
Updated Code:
jQuery(document).ready(function() {
//This function adds a development.
jQuery('#add_dev').bind('submit', function(e) {
e.preventDefault();
var data = {
action: 'AjaxAddDev',
security: AjaxHandler.ajaxnonce,
name: jQuery('#dev_name').val(),
desc: jQuery('#dev_desc').val()
};
//alert(data['name']+data['desc']);
jQuery.ajax({
url: AjaxHandler.ajaxurl,
type: "POST",
data: data,
success:function(data) {
// This outputs the result of the ajax request
alert(data);
},
error: function(errorThrown){
alert(errorThrown['error']);
}
});
});
});
I am using firefox latest version,
I got the following returned as an errotThrowen['error']
function () {
if (l) {
var t = l.length;
(function i(t) {
x.each(t, function (t, n) {
var r = x.type(n);
"function" === r ? e.unique && p.has(n) || l.push(n) : n && n.length && "string" !== r && i(n)
})
})(arguments), n ? o = l.length : r && (s = t, c(r))
}
return this
}
if you want to ajax on change
$("#yourid").change(function () {
var p = {
postfieldname: value,
postfieldname: value,
postfieldname: value,
postfieldname: value,
postfieldname: value,
postfieldname: value,
postfieldname: value,
}
$.ajax({
url: "library/test.php",
type: "POST",
data: p,
success: function (e) {
var t = jQuery.parseJSON(e);
$("#id").val(t['a']);
}
})
})
and on test.php
$array = array("a" => "test", "b" => "array");
$encode = json_encode($aray);
echo $encode;
OK this was kind of an odd one,
To get it working I simply had to add the following as the post URL.
url: AjaxHandler.ajaxurl+"&security="+AjaxHandler.ajaxnonce,
If I left the security out of the url it would fail, I don't know why but this had me going around in circles for hours.

Datepicker Unavailable dates (data retrieved from database)

I'm trying to get dates from my database and put them in an array where it would be stored in json.
MAIN.PHP
$('#datepicker').focus(function(){
$.ajax({
url: 'getDates.php',
data: "artist_name="+$('#name').html(),
dataType: 'json',
success: function(data)
{
}
});
})
getDates.php
$fullname = $_GET['artist_name'];
$result = mysql_query("SELECT .... FROM .... WHERE ... ='$fullname'")
$arraydates = array();
while($details = mysql_fetch_assoc($result)) {
array_push($arraydates, $details['event_date']);
}
echo json_encode($arraydates);
I've managed to put all the dates from the selected artist in the "arraydates".
I found this on google:
var unavailableDates = ["21-8-2013"];
function unavailable(date) {
dmy = date.getDate() + "-" + (date.getMonth() + 1) + "-" + date.getFullYear();
if ($.inArray(dmy, unavailableDates) == -1) {
return [true, ""];
} else {
return [false, "", "Unavailable"];
}
}
That's fine. But now I'm trying to get the results from the array (within getDates.php) and use them in the "main.php". So basically I want to use the data like above with "unavailableDates" array. (and thus, disable the specific dates within the jquery date picker).
Instead of having "unavailableDates", I have the "arraydates". I don't really know how can I use my array inside the "unavailable" function.
I'm not really good with json, actually it's my first time I used json. So could anyone please help me with that?
you can use jquery:
//...
success: function(data){
var arrayLength=data.length;
for(var i=0;i<arrayLength;i++){
if(unavailable(data[i]){
//your code here
}
}
}
//...
The ajax will return $arraydates in a JSON format. Use parse.JSON(returned value)
for example
success: function(data)
{
var unavailableDates = parse.JSON(data);
//Your code ....
}
Hope that helped.

Use output value from php as variable in javascript?

I'm trying to take a value that a php page outputs and use it later as a variable in a calculation. Currently I am trying this:
var price = function() {
$.get('gox.php')
}
function toDol(elem) {
var btcToDol = parseFloat(elem.value) * price || '';
document.getElementById('dol').value = btcToDol.toFixed(2);
}
function toBtc(elem) {
var dolToBtc = parseFloat(elem.value) / price || '';
document.getElementById('btc').value = dolToBtc.toFixed(4);
}
The important part is I want the 'price' variable to equal the value gox.php outputs (e.g. 99.9999) so that I can use it later to do the math in functions 'toDol' and 'toBtc'.
Thank you for your help!
var price = 0;
$.get('gox.php').done(function(data) {
price = data;
});
Try the following code
var price=$.ajax({
type: 'GET',
url: 'gox.php',
global: false,
async:false,
success: function (data) {return data;}
}).responseText;
I always have issues with $.get and $.post

Jquery and ajax, my function for username checking?

I have written this ajax request for username checking...
function check_username() {
var username = $("#username").val();
$('.loading').fadeIn().delay(100);
$.post("ajax.php", {
username: $('#username').val(),
}, function (response) {
$('.error, .success').hide();
setTimeout(function () {
$('.loading').hide();
finishAjax('username', response);
}, 1000);
});
return false;
}
function finishAjax(id, response) {
$('#' + id).after(response).fadeIn(1000);
}
It all works fine just a couple of questions,
Can this code be improved in any way, this is the first ever one I have wrote so I wouldn't know.
Is there a way to make this a function for all my ajax requests rather than just username checking, so it can be used for email checking and such too. I am not sure on how to make a function like that would I have to pass variables on my onblur event which is attached to my form, at the minute it looks like this.
Is there a way to stop the ajax from running if the same error is there as previous, ie, string length should be over 3, so someone inputs AJ, and the error message 'must be over 3 characters' comes up, it the user then triggers the onblur event again, with the value of AJ, or CG, then the same error comes up, triggering a script that is useless and using memory.
Is there a way to make the ajax request with every character the user enters?
My ajax php is as follows...
<?php
require('dbc.php');
if (isset($_REQUEST['username'])) {
$q = $dbc -> prepare("SELECT username FROM accounts WHERE username = ?");
$q -> execute(array($_REQUEST['username']));
if (strlen($_REQUEST['username']) < 3) {
echo '<div class="error">Has to be at least 3 characters</div>';
}
elseif ($q -> rowCount() > 0) {
echo '<div class="error">Username already taken</div>';
}
else {
echo '<div class="success">Username available</div>';
}
}
?>
To answer 1 & 2. I would turn it into a plugin and do something along these lines.
$.fn.checkValid = function(options)
{
var response = function(response) {
var setClass = '';
var $span = $(this).data('checkValidTip');
if ($span)
{
$span.remove();
}
if (response === undefined) return;
setClass = (response.valid ? 'valid' : 'invalid');
var $span = $('<span>' + response.msg + '</span>');
$(this)
.data('checkValidTip', $span)
.after($span);
$span.hide()
.fadeIn(1000)[0]
.className = setClass;
};
var ajaxOptions = {
type: 'GET',
url: 'ajax.php',
success: response,
dataType: 'json'
};
this.each(function() {
var that = this;
var ajaxRequest = ajaxOptions;
ajaxRequest.data = {};
ajaxRequest.data[options.key] = this.value;
ajaxRequest.context = that
$.ajax(ajaxRequest);
});
};
Usage
$('#username, #email').blur(function() {
$(this).checkValid({ key: this.id });
});
PHP changes
You should make your PHP function return a JSON, instead of HTML i.e.
<?php
// Do your sql statements here, decide if input is valid or not
$arr = array('valid' => $is_valid,
'msg' => $error_or_good_msg
);
echo json_encode($arr);
/* For example will output:
{
"valid": "false",
"msg": "<b>Error: Must be at least 2 characters</b>"
}
Which can be read directly as response.valid
or response.msg from within response() function
*/
To answer question 3: short answer is no. For this to work, you should have basic validation in JS. The best option would be to use a plugin that uses objects for validation parameters, that way you can output your validation requirements dynamically from your database, from within PHP using json_encode i.e. your output format would be:
var validations = {
username: {
min_chars: 4,
max_chars: 10,
valid_chars: 'qwertyuiopasdfghjklzxcvbnm_-'
},
email: {
regex: /./ //your magic regex here
}
};
jsFiddle
http://jsfiddle.net/sqZfp/2/
To answer 4, just change the event as above from .blur to .keyup should do the trick.

Categories