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¶2=4353¶3=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
Related
I am trying to create an autocomplete input using AJAX / PHP but the array returned from PHP seems to be breaking it.
The idea is to have the flavour name and flavour company name show in a dropdown / expanded div that the user can select.
The Array as it is returned to AJAX success (data):
The Array as JSON:
I want to get the flavour_name value and the flavour_company_name value to put in the box as a string, then on selection grab them both as an array consisting of - flavour_name / flavour_company_name to put into a DB later.
I've tried using JSON.stringify, creating a var obj I have got it to return 1 value but not a list like I want.
All help appreciated, thanks in advance.
My AJAX
$("#flavour-name-input").keyup(function(){
var token = '<?php echo json_encode($token); ?>';
var search = $(this).val();
$.ajax({
type: "POST",
url: "controllers/recipeControl.php",
data: { token: token, search: search },
beforeSend: function(){
$("#search-box").css("background","#FFF no-repeat 165px");
},
success: function(data){
//var obj = JSON.parse(data);
$("#suggesstion-box").show();
$("#suggesstion-box").html(data);
//$("#suggesstion-box").html(obj['flavour_name']);
$("#search-box").css("background","#FFF");
}
});
});
My PHP Controller
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
echo json_encode($flavours->getAllFlavoursSearch($search));
}
}
My PHP Function
/**
GET ALL FLAVOURS FOR SEARCH
*/
public function getAllFlavoursSearch($search) {
$query = 'SELECT flavour_name, flavour_company_name FROM flavours WHERE flavour_name LIKE :search ORDER BY flavour_name ASC LIMIT 0,100';
$stmt = $this->queryIt($query);
$stmt = $this->bind(':search', '%'.$search.'%', PDO::PARAM_STR);
return $this->resultset();
}
I think that you have to achieve this in your controller. Now you are returning the json and this is treated like a string. I would create an array in the controller and then you loop it and create the html.
<?php
if(isset($_POST['search'])) {
if($_SERVER['HTTP_X_REQUESTED_WITH'] == 'XMLHttpRequest' && isset($_POST['token'])
&& json_decode($_POST['token']) === $_SESSION['token']){
$search = $_POST['search'];
$html = '<ul>';
$content = $flavours->getAllFlavoursSearch($search);
foreach ($content as $con) {
$html .= '<li>'.$con['flavour_name'].'-'.$con['flavour_company'].'</li>';
}
$html .= '</ul>';
echo $html;
}
}
?>
I have not tested it but is something like this, maybe you have to check that the query returns an array.
Regards.
I am using the following code to send to a php script which adds to mysql database. The php code is working fine and set up to receive two variables but I am unsure how to change the ajax code to pass over 2 (or more) variables rather than 1 to the php script.
I have named the variable that is passed 'taskA' and want to add a 'taskB'
function add_task() {
$('.add-new-task').submit(function(){
var new_taskA = $('.add-new-task select[name=new-taskA]').val();
if(new_taskA != ''){
$.post('add-task.php', { taskA: new_taskA }, function( data ) {
$('.add-new-taskA select[name=new-taskA]').val('');
$(data).appendTo('.task-list ul').hide().fadeIn();
delete_task();
});
}
return false;
});
}
function delete_task() {
$('.delete-button').click(function(){
var current_element = $(this);
var id = $(this).attr('id');
$.post('delete-task.php', { task_id: id }, function() {
current_element.parent().fadeOut("fast", function() { $(this).remove(); });
});
});
}
Many thanks in advance
{ taskA : new_taskA } is one variable (one object). But an object can have many key/value pairs : { taskA: new_taskA , taskB : new_taskB} is still one object you pass, but contains more stuff. You can pass as much data as you want this way : strings, numbers, objects, whatever.
Server-side, get this data back using :
$taskA = $_POST['taskA'];
$taskB = $_POST['taskB'];
Or even a generic loop to convert all your POST variables to PHP variables :
foreach ($_POST as $var => $value) $$var = $value;
This will automatically set the $taskA, $taskB, $taskWhatever variables with corresponding values. Mind security though, and don't forget to sanitize the content.
you can pass mulple value via , symbol
{ taskA: new_taskA ,taskB:new_taskB}
How about:
$.post('add-task.php', { taskA: new_taskA, taskB: new_taskB }, function(...
Just add ',' between the variables.
Can be found from the bottom of the jQuery API-page:
http://api.jquery.com/jquery.ajax/
i.e:
$.ajax({
method: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
})
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++;
});
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
How do I submit an array from dojo to php.
I'm submitting these values:
["a", "b", "c"]
Here's what I got so far:
btn_send.onclick(function(){
var name_array = name_looper();
console.log(name_array);
dojo.xhrPost({
url: "dojo_phpform.php",
content: {names: name_array},
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
});
function name_looper(){
var names = dojo.query('input[type=text]');
var name_array = [];
names.forEach(function(element, index, array){
name_array[index] = dojo.attr(element, 'value');
});
return name_array;
}
I tried to echo $_POST['names'] from the php file(dojo_phpform.php) and it didn't return any errors. It seems like the array isn't actually submitted. The only thing that's returned is the last item in the array. What do I do?Please help, Thanks in advance!
I just tested this with grails and php. In grails I have no problem getting an array submitted through a dojo xhrPost : I retrieve the array properly parsed with all its values as expected.
If I post :
dojo.xhrPost({
content : {
names : ['foo', 'bar']
},
url : "mygrailscontroller"
});
I get an array param on the other side. Which proves the problem hasn't to be solved on the dojo side, but on the php side.
In php, if a form input has a variable of type array, its name parameter has to be set with square brackets, like : "names[]" rather than "names".
So... in your case the solution is not to flatten the array into a string (sorry), but to name your array argument with brackets. So it would be :
dojo.xhrPost({
content : {
"names[]" : ['foo', 'bar']
},
url : "myphpcontroller"
});
As far as I've been able to see, dojo's xhr functions don't support it. I'm using a helper function to "flatten" parameters myself.
_flattenXhrParams: function(params)
{
var newParams = {};
for(var key in params)
{
if(dojo.isObject(params[key]))
{
for(var innerKey in params[key])
{
newParams[key + "[" + innerKey + "]"] =
params[key][innerKey];
}
}
else if(dojo.isArray(params[key]))
{
for(var i = 0, l = params[key].length; i < l; i++)
{
newParams[key + "[]"] = params[key][i];
}
}
else
{
newParams[key] = params[key];
}
}
return newParams;
}
It's butt ugly, I know, and obviously only works on one dimensional arrays/objects. In your case, you'd do:
dojo.xhrPost({
url: "dojo_phpform.php",
content: _flattenXhrParams({names: name_array}),
load: function(result) {
var x = dojo.byId('results');
x.innerHTML = result;
}
});
.. and you'd get POST parameters like names[]=a&names[]=b&names[]=c. For objects, you'd get names[somekey]=a&names[otherKey]=b etc. PHP handles both nicely.
I'm pretty sure the values of the content object only take strings. If you want to submit an array, you'd have to turn it into JSON and then json_decode it on the server.