Good day. I have an unsettling error that I've encountered recently and I do not know where it came from or how it came about.
I have a form where I want to save data to the database upon button press which is handled by the controller. This is what I do in my controller:
var personStore = Ext.getStore('personBaseDetails');
var caStore = Ext.getStore('creditApplication');
var form = button.up('form').getForm();
var userId = personStore.first().get('ID');
//use this to update
if(caStore.count() < 1){
var creditApplication = Ext.ModelManager.create({
}, 'appName.model.creditApplicationModel');
caStore.add(creditApplication);
}
var record = caStore.first();
form.updateRecord(record);
console.log("user id to be edited is = " + userId);
console.log("caStore count = " + caStore.getCount());
caStore.getProxy().extraParams = {
selectedUserID: userId
};
// caStore.load();
caStore.sync({
success: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
},
failure: function(batch) {
console.log(batch.operations[0].request.scope.reader.jsonData['message']);
}
});
Here, I set the store extra param in order to use it in the php code query. However, the issue I have is that when I get the selectedUserID in the php code I have, I couldn't seem to get the extra parameter. If I commented out the if(isset($_GET['selectedUserID'])){ .... }, the query works (though the values are hardcoded as of now).
Here is what my store looks like:
Ext.define('app.store.creditApplication', {
extend: 'Ext.data.Store',
requires: [
'app.model.creditApplicationModel',
'Ext.data.proxy.Ajax',
'Ext.data.reader.Json',
'Ext.data.writer.Json'
],
constructor: function(cfg) {
var me = this;
cfg = cfg || {};
me.callParent([Ext.apply({
autoLoad: false,
model: 'app.model.creditApplicationModel',
storeId: 'creditApplication',
clearOnPageLoad: false,
proxy: {
type: 'ajax',
api: {
create: 'data/person/creditApplication/createCreditApplication.php',
read: 'data/person/creditApplication/readCreditApplication.php',
update: 'data/person/creditApplication/updateCreditApplication.php'
},
url: '',
reader: {
type: 'json',
root: 'data'
},
writer: {
type: 'json',
encode: true,
root: 'data'
}
}
}, cfg)]);
}
});
Now I'm dumbfounded since I have another code which is similar in the sense that I set the extraParam in the controller and the php code was able to receive and read it just fine. Note that both my stores do not have any extraParam property.
I've been stuck with this problem and I don't know how to go about it. Any help would be greatly appreciated.
Store does not have extraParam(s), proxy does. You can set it with:
store.getProxy().setExtraParam(name, value)
Related
Hello all and thanks in advance,
Short story, I am using a plugin to dynamically populate select options and am trying to do it via an ajax call but am struggling with getting the data into the select as the select gets created before the ajax can finish.
First, I have a plugin that sets up different selects. The options input can accept an array or object and creates the <option> html for the select. The createModal code is also setup to process a function supplied for the options input. Example below;
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
let dueDate = {};
for (let i = 1; i < 32; i++) {
dueDate[i] = i;
}
return dueDate;
}
}
});
What I am trying to do is provide an object to the options input via AJAX. I have a plugin called postFind which coordinates the ajax call. Items such as database, collection, etc. are passed to the ajax call. Functions that should be executed post the ajax call are pass through using the onSuccess option.
(function ($) {
$.extend({
postFind: function () {
var options = $.extend(true, {
onSuccess: function () {}
}, arguments[0] || {});
options.data['action'] = 'find';
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof options.onSuccess === 'function') {
options.onSuccess.call(this, obj);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
}
});
}(jQuery));
The plugin works fine as when I look at the output it is the data I expect. Below is an example of the initial attempt.
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
$.postFind({
data: {
database: 'dashboard',
collections: {
accountTypes: {
where: {status: true}
}
}
},
onSuccess: function (options) {
let dataArray = {};
$.each(options, function (key, val) {
dataArray[val._id.$oid] = val.type;
});
return dataArray;
}
})
}
}
});
In differnt iterations of attempting things I have been able to get the data back to the options but still not as a in the select.
After doing some poking around it looks like the createModal script in executing and creating the select before the AJAX call can return options. In looking at things it appears I need some sort of promise of sorts that returns the options but (1) I am not sure what that looks like and (2) I am not sure where the promise goes (in the plugin, in the createModal, etc.)
Any help you can provide would be great!
Update: Small mistake when posted, need to pass the results back to the original call: options.onSuccess.call(this, obj);
I believe to use variables inside your success callback they have to be defined properties inside your ajax call. Then to access the properties use this inside the callback. Like:
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
myOptions: options,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof this.myOptions.onSuccess === 'function') {
this.myOptions.onSuccess.call(this);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
It's not clear to me where the problem is without access to a functional example. I would start with a simplified version of what you want to do that demonstrates the proper functionality. My guess is the callbacks aren't setup exactly correctly; I would want to see the network call stack before making a more definitive statement. A few well-placed console.log() statements would probably give you a better idea of how the code is executing.
I wrote and tested the following code that removes most of the complexity from your snippets. It works by populating the select element on page load.
The HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select data-src='test.php' data-id='id' data-name='name'></select>
</body>
</html>
<html>
<script>
$('select[data-src]').each(function() {
var $select = $(this);
$select.append('<option></option>');
$.ajax({
url: $select.attr('data-src'),
data: {'v0': 'Alligator', 'v1': 'Crocodile'}
}).then(function(options) {
options.map(function(option) {
var $option = $('<option>');
$option
.val (option[$select.attr('data-id')])
.text(option[$select.attr('data-name')]);
$select.append($option);
});
});
});
</script>
And the PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
echo json_encode([
[ 'id' => 0, 'name' => 'Test User 0' ],
[ 'id' => 3, 'name' => $_GET['v0'] ],
[ 'id' => 4, 'name' => $_GET['v1'] ]
]);
Here's a fiddle that also demonstrates the behavior.
I am trying to validate list of dynamic text fields.
Validation needs an AJAX call to interact with server.
At the backend I have written just one php file that reads the input request data and performs operation. Below is the example.
abc.js
row_count = 6
for (i = 1; i <=row_count; i++) {
id = "#val"+i.toString() ;
$(id).change(function(){
input_val="random";
$.ajax({
url:"url.php",
type:post,
async:true,
dataType: 'json',
data : {temp:input_val},
success:function(result){},
error: function (request, status, error) {}
});
});
}
url.php
<?php
$random_val = $_POST['temp'];
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
if ($flag == 0){
echo json_encode(array("status"=>'Fail'));
}
else{
echo json_encode(array("status"=>'Success'));
}
?>
It works fine when the row_count = 1 (Just one text field) but fails when the input is more than 1.
When the count is more than 1, the php script is not able to read the request data(The key in JSON data "temp"). it is blank in that case.
Any lead or help should be appreciated.
Thanks
Your javascript bit needs some adjusting, because you do not need to define an ajax for every single element. Use events based on a class. Also, since input behave differently than select, you should setup two different event class handlers.
function validateAjax ( element ) {
var input_val = element.val();// get the value of the element firing this off
$.ajax({
url: "url.php",
type: 'post',
async: true,
dataType: 'json',
data : { temp: input_val },
success: function(result) {
// check your result.status here
},
error: function (request, status, error) { }
});
}
$(".validate_change").on("change",function() { // for selects
validateAjax( $(this) );
});
$(".validate_input").on("input",function() { // for text inputs
validateAjax( $(this) );
});
And for your select or input you add that appropriate class.
<select class="validate_change" name="whatever"><options/></select>
<input class="validate_input" name="blah">
PS
I really worry about this code you have:
$cmd = 'systemcommand '.$random_val;
$flag = exec($cmd);
So, you are just executing anything that is coming in from a webpage POST var??? Please say this website will be under trusted high security access, and only people using it are trusted authenticated users :-)
I have the following AJAX request:
$(function(){
$("#MPrzezn").typeahead({
hint: true,
highlight: true,
minLength: 3
},
{
name: 'test',
displayKey: 'value',
source: function(query, process){
$.ajax({
url: 'sprawdzKraj.php',
type: 'POST',
data: 'query=' + query,
dataType: 'JSON',
async: true,
success: function(data){
process(data);
console.log(data);
}
});
}
});
});
... and the following php on backend:
<?php
require_once 'core/init.php';
$user = new User(); //current User
if($user->isLoggedIn()){
if(isset($_POST['query'])){
$query = $_POST['query'];
$delegacja = new Delegacja();
$dataListaDelegacji = $delegacja->listujMiasta($query);
header('Content-Type: application/json');
$json_response = json_encode($dataListaDelegacji);
echo $json_response;
}
} else {
$isLoggedIn = false;
$smarty->assign("userid","",true);
$smarty->assign("isLoggedIn",$isLoggedIn,true);
Redirect::to('login.php');
}
The php script returns a proper json:
[{"ID":"66","IDKraju":"117","NazwaMiasta":"Inowroc\u0142aw","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"251","IDKraju":"117","NazwaMiasta":"\u015awinouj\u015bcie","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"2222","IDKraju":"74","NazwaMiasta":"Rhinow","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null},
{"ID":"3508","IDKraju":"94","NazwaMiasta":"San Bernardino","MiastoTlumaczenie1":null,"MiastoTlumaczenie2":null}]
The picture below shows how the json is being picked up by browser:
There are 4 cities that match the query - each object is a city entry
My goal is to pass values of "NazwaMiasta" to a typeahead input, but I get "undefined" entries. I tried different things but it always keeps showing undefined like this:
Red arrows show all 4 json nodes
I hope I described my problem well. I understand that I'm pretty close, but I cannot find the solution myself. I'll appreciate any help.
Thanks
You have to put right displayKey value!
insted of :
displayKey: 'value',
set :
displayKey: 'NazwaMiasta',
EDIT :
Detailed explanation : When you return data via ajax call, typeahead doesn't know what value to display. So you must set where is value for that key. Your return array of object that have structure like this :
['key1':'value1', 'key2':'value2',...]
By setting ie 'key1' , typeahead knows how to access value ie :
currentElement['key1']...
and than put that value to html.
I need to be able to select a country in a selectbox, and then get all the states from that country.
I'm trying to do something like this: how-to-display-json-data-in-a-select-box-using-jquery
This is my controller:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
and my javascript:
$.ajax({
url: 'settings/express_locale',
type: 'POST',
data: { code: location, type: typeLoc },
success: function (data) {
console.log(data);
}
});
console.log shows me something like this:
["71","SomeState0"]["72","SomeState"]["73","SomeState2"]["74","SomeState3"]
So, what i need is to append all states in a new selectbox.
But I'm trying to read this array doing this in the success callback:
$.each(data, function(key,val){
console.log(val);
});
In the result, each line is a word, like this:
[
"
7
1
"
,
"
s
....
]
Why does that happen, and what am I missing?
JSON is not made of independent blocks. So this will never do:
foreach($this->settings_model->get_state_list() as $state)
{
echo json_encode(array($state->CODSTA, $state->STANAM));
}
The output will be treated as text, and the iterator will loop the object's elements... which are the single characters.
You need to declare a list, or a dictionary. I have included some examples, depending on how you use the data in the jQuery callback. Note: PHP-side, you may also need to output the proper MIME type for JSON:
$states = array();
foreach($this->settings_model->get_state_list() as $state)
{
// Option 1: { "71": "SomeState0", "72": "Somestate2", ... }
// Simple dictionary, and the easiest way IMHO
$states[$state->CODSTA] = $state->STANAM;
// Option 2: [ [ "71", "SomeState0" ], [ "72", "SomeState2" ], ... ]
// List of tuples (well, actually 2-lists)
// $states[] = array($state->CODSTA, $state->STANAM);
// Option 3: [ { "71": "SomeState0" }, { "72": "SomeState2" }, ... ]
// List of dictionaries
// $states[] = array($state->CODSTA => $state->STANAM);
}
Header('Content-Type: application/json');
// "die" to be sure we're not outputting anything afterwards
die(json_encode($states));
In the jQuery callback, you specify the datatype and content type with charset (this will come in handy as soon as you encounter a state such as the Åland Islands, where a server sending data in ISO-8859-15 and a browser running a page in UTF8 can lead to a painful WTF moment):
$.ajax({
url: 'settings/express_locale',
type: 'POST',
data: { code: location, type: typeLoc },
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#comboId").get(0).options.length = 0;
$("#comboId").get(0).options[0] = new Option("-- State --", "");
// This expects data in "option 1" format, a dictionary.
$.each(data, function (codsta, stanam){
n = $("#comboId").get(0).options.length;
$("#comboId").get(0).options[n] = new Option(codsta, stanam);
});
},
error: function () {
alert("Something went wrong");
}
have you tried using $.map() instead?
http://api.jquery.com/jQuery.map/
$.map(data, function(index, item) {
console.log(item)
})
You should use GET not POST since you are not actually creating anything new serverside.
Read a bit about REST and why using GET is the proper noun here.
I've added a JSFiddle example that you can run straight away.
http://jsfiddle.net/KJMae/26/
If this is the JSON that the PHP service returns:
{
"success":true,
"states":[
{
"id":71,
"name":"California"
},
{
"id":72,
"name":"Oregon"
}
]
}
This is our HTML code:
<select id="country">
<option value="">No country selected</option>
<option value="1">USA</option>
</select>
<select id="states">
</select>
This is what the code to add that to the select could look like:
// Bind change function to the select
jQuery(document).ready(function() {
jQuery("#country").change(onCountryChange);
});
function onCountryChange()
{
var countryId = jQuery(this).val();
$.ajax({
url: '/echo/json/',
type: 'get',
data: {
countryId: countryId
},
success: onStatesRecieveSuccess,
error: onStatesRecieveError
});
}
function onStatesRecieveSuccess(data)
{
// Target select that we add the states to
var jSelect = jQuery("#states");
// Clear old states
jSelect.children().remove();
// Add new states
jQuery(data.states).each(function(){
jSelect.append('<option value="'+this.id+'">'+this.name+'</option>');
});
}
function onStatesRecieveError(data)
{
alert("Could not get states. Select the country again.");
}
As for the PHP, here's a simple example that should give the same result as JSON used in example above. (Haven't tested it, from top of my head, no php here.)
$result = new stdClass;
$result->states = array();
foreach($this->settings_model->get_state_list() as $state)
{
$stateDto = new stdClass();
$stateDto->id = $state->CODSTA;
$stateDto->name = $state->STANAM;
$result->states[] = $stateDto;
}
$result->success = true;
die(json_encode($result));
I am continuing a previous question that was asked onclick -> mysql query -> javascript; same page
This is my onchange function for a drop down of names. it is called when each drop down is changed. The idea is to send each runners name into the php page to run a mysql query then return 3 arrays to be entered into javascript.
function sendCharts() {
var awayTeam = document.getElementById('awayRunner').value;
var homeTeam = document.getElementById('homeRunner').value;
if(window.XMLHttpRequest) {
xmlhttp14 = new XMLHttpRequest();
}
else {
xmlhttp14 = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp14.onreadystatechange = function() {
if(xmlhttp14.readyState == 4 && xmlhttp14.status == 200) {
var parts = xmlhttp14.responseText.split(','); //THIS IS WHAT IS RETURNED FROM THE MYSQL QUERY. WHEN I ALERT IT, IT OUTPUTS IN THE FORM 14,15,18,16,17,12,13
... code that generates the chart
series: [ {
name: document.getElementById('awayRunner').value,
data: [parts,','], //THIS IS WHERE AN ARRAY MUST BE ENTERED. THIS OUPUTS ONLY ONE NUMBER
type: 'column',
pointStart: 0
//pointInterval
},
{
name: document.getElementById('homeRunner').value,
data: parts, // TRIED THIS
type: 'column',
pointStart: 0
//pointInterval
},
{
name: 'League Avg',
data: [], //THIS IS WHERE 3rd ARRAY MUST BE ENTERED
type:'spline',
pointStart: 0
//pointInterval
},
]
});
}
}
xmlhttp14.open("GET", "getCharts.php?awayRunner="+awayRunner+"&homeRunner="+homeRunner, true);
xmlhttp14.send();
}
my php code looks like this. As you'll see, there are 3 arrays that must be returned to be entered into different spots in the javascript to generate the code.
$away=$_GET['awayRunner'];
$home=$_GET['homeRunner'];
$db=mydb;
$homeRunner=array();
$awayRunner = array();
$totalOverall= array();
$getHome="select column from $db where tmName = '$home'";
$result2 = mysql_query($getHome);
while($row = mysql_fetch_array($result2)){
$homeRunner[]= $row['column'];
}
$getAway="select column from $db where tmName ='$away'";
$result22 = mysql_query($getAway);
while($row2 = mysql_fetch_array($result22)){
$awayRunner[]= $row2['column'];
}
$week = 0;
while($week<20){
$week++;
$teamCount = "select count(column) from $db where week = $week";
$resultTeam = mysql_query($teamCount);
$rowTeam = mysql_fetch_array($resultTeam);
$t = $rowTeam['count(column)'];
$getLeague = "select sum(column) from $db where week = $week";
$resultLeague = mysql_query($getLeague);
while($row3 = mysql_fetch_array($resultLeague)){
$totalOverall[]=$row3['sum(column)']/$t;
}
}
echo join(',',$awayRunner);
currently, by doing it this way, the chart only outputs the second value in the array. for instance, if var parts is equal to 23,25,26,24,23...only 25 is shown.
A previous question resulted with the following answer -
Load the page.
User chooses an option.
An onChange listener fires off an AJAX request
The server receives and processes the request
The server sends back a JSON array of options for the dependent select
The client side AJAX sender gets the response back
The client updates the select to have the values from the JSON array.
I'm lost on #'s 5 - 7. Can someone provide examples of code that gets this done? Normally, I would just ask for direction, but I have been stuck on this problem for days. I'm about ready to scrap the idea of having charts on my site. Thanks in advance
EDIT
this is the first change that I have made to send and receive just one request
<script>
$(function(){
$("#awayRunner").change(function(){
$.ajax({
type: "POST",
data: "data=" + $("#awayRunner").val(),
dataType: "json",
url: "/my.php",
success: function(response){
alert(response);
}
});
});
});
The data displayed in the alertbox is in the form 12,15,16,15. Now, when I enter in
data: response,
only the second number from each is being displayed in the chart. Any ideas?
EDIT
OK, so i figured out that the info in response is a string. It must be converted to an INT using parseInt to be usable in the chart. currently, I have
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayTeam").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var asdf = [];
asdf[0] = parseInt(response[0]);
asdf[1] = parseInt(response[1]);
asdf[2] = parseInt(response[2]);
asdf[3] = parseInt(response[3]);
alert(asdf);
will have to write a function to make this cleaner.
I can't believe it, but I finally got it. here is how I used an onchange method to stimulate a MYSQL query and have the Highchart display the result. The major problem was that the returned JSON array was a string that needed to be converted into an INT. The resultArray variable is then used in the data: portion of the highChart.
$(function(){
$("#awayTeam").change(function(){
$.ajax({
type: "POST",
data: "away=" + $("#awayRunner").val(),
dataType: "json",
url: "/getCharts.php",
success: function(response){
var arrayLength = response.length;
var resultArray = [];
var i = 0;
while(i<arrayLength){
resultArray[i] = parseInt(response[i]);
i++;
}
In the PHP code, the array must be returned as JSON like this
echo json_encode($awayRunner);