Pass values into session.php - javascript

I'm trying to pass some values into session.php.
Below is my code. type_oq is a dropdown menu. I want to save certain values if the dropdown selection is equal to "fruit".
The problem: Not sure what is the problem. No errors shown. The php file path is accurate. Button click works. My guess is that there might be a syntax error in the if condition?
$('#goBtn').click(function(){
alert("done!");
$.post('sessions.php',
{
if ($('#type_oq').val() == "fruit") {
a:$('#a_oq').val(),
b:$('#b_oq').val(),
}
from:$('#from_oq').val(),
to:$('#to_oq').val(),
radioG:$('#radioGroup').val()
} ,
function(response) {
$('#postrequest').html(response);
});
});

I would create the data object outside the $post and then just pass it as a variable:
$('#goBtn').click(function(){
alert("done!");
var data = {
from:$('#from_oq').val(),
to:$('#to_oq').val(),
radioG:$('#radioGroup').val(),
// If a and b are required then create them here with empty values.
a: "",
b: ""
};
if ($('#type_oq').val() == "fruit") {
data.a = $('#a_oq').val();
data.b = $('#b_oq').val();
};
$.post('sessions.php', data, function(response) {
$('#postrequest').html(response);
});
});
Just to be extra clear, it turns out that you can't use conditions inside of the object creation, e.g. this wouldn't work:
var data = {
if (true) {
a:"a",
}
b: "b"
};

Related

Restore Checkbox State from Dictionary

I am storing form data in json format. To allow changing values from a previously created json file, the (plain old javascript) function below will load the values into a form from a file. This method will restore the value of drop down lists but not with a checkbox.
I have tried storing the value of the checkbox ('on' or 'off') and the checked state ('true' or 'false') but neither works out of the box.
Also, I tried adding an if statement before the return, like so:
if (newArr[dataItem] === "true") {
document.getElementById(newArr[dataItem]).click();
} else {
return (inputItem.id === dataItem) ? (inputItem.value = newArr[dataItem]) : false;
}
Here is a stripped down version of the function that works to restore values:
function receivedText(e) {
let lines = e.target.result;
var newArr = JSON.parse(lines);
Object.keys(newArr).map(function (dataItem) {
inputs.map(function (inputItem) {
return (inputItem.id === dataItem) ? (inputItem.value = newArr[dataItem]) : false;
});
});
}
The json data would look like this:
{ "foo": "ws", "bar": "ws", "checkbox_value": "on", "other_data": "apple" }
So in short, when loading data from a file and evaluating the json dictionary, the checkbox_value does not seem to select or deselect the checkbox.
You need to update the checked attribute, and it needs to be set to the booleans true and false, not the strings. You should store the checked attribute as a boolean in the JSON. To load the values, consider the following code:
Object.keys(newArr).map(function (dataItem) {
var inputItem = document.getElementById(dataItem);
if (inputItem.type === "checkbox") {
inputItem.checked = newArr[dataItem];
} else {
inputItem.value = newArr[dataItem];
}
});

ComboBox typeAhead works but valueField is null under certain behavioral conditions

Requesting a sanity check here please...
ExtJS 4.2 comboBox Typeahead works but having issues retrieving the valueField under the following conditions:-
1) If a user types a value and then instead of hitting enter or clicking on the select combo list, they click elsewhere then the valueField is empty but the selected value is present.
2) Assuming that the combobox item was selected correctly, If I enter an additional character and then backspace that character, the combo box can no longer find the valueField..its almost like it has reset itself.
Fiddle example
https://fiddle.sencha.com/#fiddle/je1
How to reproduce
If you enter Maggie in the combo box, you will see the valueField ID in the console window, if you append a character and then backspace the character, the ID in the console window is null
(You will need to open the console window to see the output)
forceSelection does not resolve this issue as I have a template and it will not accept an entry in the combobox that is not part of the store, and I need to use sumID for my valueField as I need to retrieve and pass that value to the server.
Thank you everyone, awesome to have such a great community!!
I was able to get around this by using forceSelection and overriding the setValue thus allowing template items not in the store but in the combo to be selected via forceSelection. From playing around with the combobox, IMO, for a good look and feel, forceSelection is the way to go.
Here is my override, refer to statement //start of override
This was a quick fix, I will refine statement when I am back in the office, below I am pasting the solution from memory, you get the idea.
setValue: function(value, doSelect) {
var me = this,
valueNotFoundText = me.valueNotFoundText,
inputEl = me.inputEl,
i, len, record,
dataObj,
matchedRecords = [],
displayTplData = [],
processedValue = [];
if (me.store.loading) {
// Called while the Store is loading. Ensure it is processed by the onLoad method.
me.value = value;
me.setHiddenValue(me.value);
return me;
}
// This method processes multi-values, so ensure value is an array.
value = Ext.Array.from(value);
// Loop through values, matching each from the Store, and collecting matched records
for (i = 0, len = value.length; i < len; i++) {
record = value[i];
if (!record || !record.isModel) {
record = me.findRecordByValue(record);
}
// record found, select it.
if (record) {
matchedRecords.push(record);
displayTplData.push(record.data);
processedValue.push(record.get(me.valueField));
}
// record was not found, this could happen because
// store is not loaded or they set a value not in the store
else {
//start of override
// 'Select All Names' is the template item that was added // to the combo box, it looks like an entry from the store
// but it is not in the store
if (me.forceSelection && me.getDisplayValue() === 'Select All Names'){
processedValue.push(value[i]);
dataObj = {};
dataObj[me.displayField] = value[i];
displayTplData.push(dataObj);
}
//end of override
if (!me.forceSelection) {
processedValue.push(value[i]);
dataObj = {};
dataObj[me.displayField] = value[i];
displayTplData.push(dataObj);
// TODO: Add config to create new records on selection of a value that has no match in the Store
}
// Else, if valueNotFoundText is defined, display it, otherwise display nothing for this value
else if (Ext.isDefined(valueNotFoundText)) {
displayTplData.push(valueNotFoundText);
}
}
}
// Set the value of this field. If we are multiselecting, then that is an array.
me.setHiddenValue(processedValue);
me.value = me.multiSelect ? processedValue : processedValue[0];
if (!Ext.isDefined(me.value)) {
me.value = null;
}
me.displayTplData = displayTplData; //store for getDisplayValue method
me.lastSelection = me.valueModels = matchedRecords;
if (inputEl && me.emptyText && !Ext.isEmpty(value)) {
inputEl.removeCls(me.emptyCls);
}
// Calculate raw value from the collection of Model data
me.setRawValue(me.getDisplayValue());
me.checkChange();
if (doSelect !== false) {
me.syncSelection();
}
me.applyEmptyText();
return me;
},
Look at the sources of Combobox and try override this method as follows
doLocalQuery: function(queryPlan) {
var me = this,
queryString = queryPlan.query;
if (!me.queryFilter) {
me.queryFilter = new Ext.util.Filter({
id: me.id + '-query-filter',
anyMatch: me.anyMatch,
caseSensitive: me.caseSensitive,
root: 'data',
property: me.displayField
});
me.store.addFilter(me.queryFilter, false);
}
if (queryString || !queryPlan.forceAll) {
me.queryFilter.disabled = false;
me.queryFilter.setValue(me.enableRegEx ? new RegExp(queryString) : queryString);
}
else {
me.queryFilter.disabled = true;
}
me.store.filter();
if (me.store.getCount()) {
if (me.rawValue === me.lastSelection[0].get(me.displayField)){
me.setValue(me.lastSelection);
} else {
if(me.store.getCount() === 1){
me.setValue(me.store.first());
}
me.expand();
}
} else {
me.collapse();
}
me.afterQuery(queryPlan);
},

How to make 1 variable is equal to multiple values?

Hello I want to add friends on facebook using tokens..
I found this code.
edprens: function(a) {
if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: USER ID/NAME I WANT TO ADD,
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}
},
example I have.. ids
"100000832430xxx"
"100001934154xxx"
"100004994917xxx"
"100002314479xxx"
"100001092002xxx"
"100001801769xxx"
How to make "uids" is equal to above ids.. so I can add them.?
Thank you
It's too big to post it in comment. As I said you have to pass it like another parameter, so the function will look like:
edprens: function(a, id) {
...
uids: id, // USER ID/NAME YOU WANT TO ADD
...
}
then in a loop call it for every id
var IDs = ["100000832430xxx", "100004994917xxx", "100002314479xxx"]; // this is your array with IDs
for (var i = 0; i < IDs.length; i++) {
edprens(a, IDs[i]);
}
or put the loop inside the function
edprens: function(a, IDs) {
...
for (var i = 0; i < IDs.length; i++) {
$.getJSON("https://graph.facebook.com/me/friends", {
...
uids: IDs[i], // USER ID/NAME YOU WANT TO ADD
...
});
}
...
}
edprens("ids###");edprens("ids###");edprens("ids###"); is not a loop. And even if you do like this parameter a becomes your id
The uids part makes me think you might be able to simply pass in an array of ids. Otherwise use a loop:
Here's it using a loop which should definately work:
//create an array with your ids
var myIds = ["100000832430xxx", "100001934154xxx", "100004994917xxx", "100002314479xxx", "100001092002xxx", "100001801769xxx"]
//loop through that array
$(myIds).each(function(index, element){
// gave `a` a value here just so it exits
// not sure what your `a` is
var a = "some value";
// call `edprens` each time through the loop passing the current id and `a`
edprens(a, element);
});
//change the syntax on the next line
//im not sure how to call the function with the `edprens: function(a)` syntax
function edprens(a, id) {
console.log('function would have been called with id:'+id);
// im commenting out the rest since it requires other code not present
/*if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: id,
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}*/
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's it passing an array which might work?...:
//second method (possible but not sure)
//the `uids` part makes me think you might be ale to simply pass in an array of ids like:
var myIds = ["100000832430xxx", "100001934154xxx", "100004994917xxx", "100002314479xxx", "100001092002xxx", "100001801769xxx"]
var a = "some value";
// im commenting out the funnction call
// on the next line since it requires other code not present
//edprens(a, myIds)
//changed
function edprens2(a, id) {
if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: myIds, //here we supply the whole array, might work but Im not familar with the rest of the process so I cant say for sure
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}
};

Delete button when it's clicked javascript

I have some code which is creating a button when a line is added to a chart. When the button is clicked, I want to remove the line from the chart and delete the button. The example can be viewed here.
To wit, the code that successfully adds the button is:
function getChartData(option){
var category = $('#category').val();
var option = option.value;
var seriesTitle = category+option;
$.ajax({
url: "getData.php?action=getChartData",
type: "GET",
dataType:"json",
data: {
category:category,
option:option
},
success: function(json){
chart.addSeries({
name: seriesTitle,
data : []
});
$.each(json.Data,function(){
chart.series[chart.series.length-1].addPoint([parseFloat(this.Year), parseFloat(this[option])]);
});
}
});
var series = document.createElement('button');
series.onclick = function(){
removeLine(seriesTitle);
}
series.setAttribute('id',seriesTitle);
series.innerHTML=seriesTitle;
$('#removeLine').append(series);
}
Then when the button is clicked, this code does not do anything:
function removeLine(seriesTitle){
chart.series[seriesTitle].remove();
$(seriesTitle).remove();
}
The error is:
Uncaught TypeError: Cannot call method 'remove' of undefined
removeLine oil.js:172
series.onclick
Bonus points for anyone who knows how I call a particular line in highcharts based on a variable e.g. this works:
chart.series[chart.series.length-1].remove();
This doesn't:
chart.series[seriesTitle].remove();
When you use chart.series[something].remove(); 'something' have to be the serie position as you can see here. So you have to pass the position thrue the parameter. That's why chart.series[0].remove(); works.
So if you want to fix this problem you can found the serie position according to the title before remove it, like the following.
function removeLine(seriesTitle){
for(var postion = 0; position < chart.options.series.length; position++) {
if(chart.options.series[position].name == seriesTitle) {
chart.options.series[position].remove();
break;
}
}
}
or
function removeLine(seriesTitle){
$.each(chart.options.series, function(pos, serie){
if(serie.name == seriesTitle) {
chart.series[pos].remove();
}
});
}
To solve the problem when you remove the button you have to do add a hash tag, like the following:
$('#' + seriesTitle).remove();
So, your function will be the following:
function removeLine(seriesTitle){
for(var postion = 0; position < chart.options.series.length; position++) {
if(chart.options.series[position].name == seriesTitle) {
chart.options.series[position].remove();
break;
}
}
$('#' + seriesTitle).remove();
}
I think the problem is in the lines
seriesTitle = chart.addSeries({
name: seriesTitle,
data : []
});
seriesTitle here refers to the the seriesTitle created by
var seriesTitle = category+option;
and overwrites its value. I would guess that addSeries is returning an object or undefined. seriesTitle is passed to removeLine with this value, and you're using it as a key to the array chart.series.
Try removing the assignment there (it really looks like you don't want it), or just prefix it with var (it will become local to the anonymous function).
If you're unsure about the key-value pairs of chart.series then pass it to console.log() and you can inspect it to see what your keys should look like (and also what the values are).

Handling no results in jquery autocomplete

Hey I'm trying to return a message when there are no results for the users current query! i know i need to tap into the keyup event, but it looks like the plugin is using it
This question is really out of date, anyways I'm working with the new jQuery UI 1.8.16, autocomplete is now pretty different:http://jqueryui.com/demos/autocomplete/#default
Anyways if you're trying to the do the same thing as the question asks, there is no more parse function, as far as I know there is no function that is called with the search results.
The way I managed to pull this off is by overriding the autocomplete's filter function - Note: this will affect all your autocompletes
$.ui.autocomplete.filter = function(array, term) {
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(term), "i" );
var aryMatches = $.grep( array, function(value) {
return matcher.test(value.label || value.value || value);
});
if (aryMatches.length == 0){
aryMatches.push({
label: '<span class="info" style="font-style: italic;">no match found</span>',
value: null
});
}
return aryMatches;
};
The function is slightly modified from the source, the grep call is the same, but if there are no results I add an object with a value of null, then I override the select calls to check for a null value.
This gives you an effect where if you keep typing and no matches are found you get the 'no matches found' item in the dropdown, which is pretty cool.
To override the select calls see jQuery UI Autocomplete disable Select & Close events
$(this).data('autocomplete').menu.options.selected = function(oEvent, ui){
if ($(ui.item).data('item.autocomplete').value != null){
//your code here - remember to call close on your autocomplete after
}
};
Since I use this on all my autocompletes on a page, make sure you check if value is null first! Before you try to reference keys that aren't there.
You could try supplying a parse option (function to handle data parsing) and do what you need when no results are returned to parse.
This example assumes you're getting back an array of JSON objects that contain FullName and Address attributes.
$('#search').autocomplete( {
dataType: "json",
parse: function(data) {
var array = new Array();
if (!data || data.length == 0) {
// handle no data case specially
}
else {
for (var i = 0; i < data.length; ++i) {
var datum = data[i];
array[array.length] = {
data: datum,
value: data.FullName + ' ' + data.Address,
result: data.DisplayName
};
}
}
return array;
}
});
I'm using the following code for the same purpose (the message is shown in the autocomplete list):
success: function(data, status, xhr){
if(!data.length){
var result = [
{
label: 'There are no matches for your query: ' + response.term,
value: response.term
}
];
response(result);
}
else{
// normal response
}
}
You can also utilize the "response" event to examine this. Simple but powerful. http://api.jqueryui.com/autocomplete/#event-response
response: function (event, ui) {
if (ui.content.length == 0) {
//Display an alert or something similar since there are no results
}
},

Categories

Resources