jQuery AJAX request returns object - php

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.

Related

Ajax call to PHP action/function with array as data (in wordpress)

I'm trying to push an array from jquery to a php function and I'm out of options to make it work. I've tried multiple options; $_request, $_post, with JSON.stringify, without JSON.stringify, ...
But I keep getting 'null'; can't figure out the right combination. Someone who's willing to explain me why it's not working and how to fix?
JQuery code:
var userIDs = [];
$( "tr.user-row" ).each(function() {
var userID = $(this).attr("data-userid");
userIDs.push(userID);
});
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : {data:jsonIDs},
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP code:
function built_ranking(){
if ( isset($_REQUEST) ) {
$data = json_decode(stripslashes($_REQUEST['data']));
foreach($data as $d){
echo $d;
}
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );
If I print the $testResult it returns the array and I can use the data back in jquery, so the function is called.
I've based the code on Send array with Ajax to PHP script
I've multiple ajax calls with $_request instead of $_post and they are working fine. But maybe they can't handle arrays? I've no idea... ^^
What I learned from this question and the help I got: don't guess, debug. try to find ways to see what is posted, what is received, ...
You can read how to 'debug' in the comments of the original question. Useful for starters as me ;)
Working code:
JQuery
var jsonIDs = JSON.stringify(userIDs);
$.ajax({
type: 'POST',
url: ajaxurl, // Since WP 2.8 ajaxurl is always defined and points to admin-ajax.php
data: {
'action':'built_ranking', // This is our PHP function below
'data' : jsonIDs,
},
dataType:"json",
success:function(data){
// This outputs the result of the ajax request (The Callback)
//$("tr[data-userid='"+userID+"'] td.punten").html(data.punten);
//$("tr[data-userid='"+userID+"'] td.afstand").html(data.afstand);
console.log(data);
},
error: function(errorThrown){
window.alert(errorThrown);
}
});
PHP
function built_ranking(){
if ( isset($_POST) ) {
$data = json_decode(stripslashes($_POST['data']));
print json_encode($data);
//$testResult = array("points"=>"test", "afstand"=>"test");
//print json_encode($testResult);
}
// Always die in functions echoing AJAX content
die();
}
add_action( 'wp_ajax_built_ranking', 'built_ranking' );

extjs4 store set extraParam dynamically not working

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)

JSON PHP decode not working

I have seen many examples, but for whatever reason, none seem to work for me.
I have the following sent from a app, via ajax, to a php file. This is how it looks when its sent:
obj:{"ClientData":
[{
"firstName":"Master",
"lastName":"Tester",
"email":"me#me.com",
"dob":"1973-01-22",
"age":"51",
}],
"HealthData":
[
"condition : Prone to Fainting / Dizziness",
"condition : Allergic Response to Plasters",
],
"someData":
[{
"firstName":"Male",
"lastName":"checking",
}]
}
Code as is:
{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDate":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}
This comes in one long line into a php file, here is the code:
<?php
header('Content-Type: application/json');
header("Access-Control-Allow-Origin: *");
//var_dump($_POST['obj']);
$Ojb = json_decode($_POST['obj'],true);
$clientData = $Ojb['ClientData'];
$healthData = $Ojb->HealthData;
$someData = $Ojb->someData;
print_r($clientData['firstName']);
?>
No matter what I have tried, I am unable to see any of the information, I don't even get an error, just blank! Please can someone point me in the right direction.
Thank you :)
UPDATE
Here is the code that creates the object:
ClientObject = {
ClientData : [
{
firstName : localStorage.getItem('cfn'),
lastName : localStorage.getItem('cln'),
email : localStorage.getItem('cem'),
dob : localStorage.getItem('cdo'),
age : localStorage.getItem('cag'),
pierceType : localStorage.getItem('cpt'),
street : localStorage.getItem('cst'),
city : localStorage.getItem('cci'),
county : localStorage.getItem('cco'),
postcode : localStorage.getItem('cpc')
}
],
HealthData : health,
PiercerData : [
{
firstName : localStorage.getItem('pfn'),
lastName : localStorage.getItem('pln'),
pierceDate : localStorage.getItem('pda'),
jewelleryType : localStorage.getItem('pjt'),
jewelleryDesign : localStorage.getItem('pjd'),
jewellerySize : localStorage.getItem('pjs'),
idChecked: localStorage.getItem('pid'),
medicalChecked: localStorage.getItem('pmh'),
notes: localStorage.getItem('poi')
}
]
};
And here is how its sent:
function senddata() {
$.ajax({
url: 'http://domain.com/app.php',
type: 'POST',
crossDomain: true,
contentType: "application/json; charset=utf-8",
dataType: 'jsonp',
data: 'obj='+JSON.stringify(ClientObject),
success : function(res) {
console.log(res);
},
error: function(err) {
}
});
}
There are a few things that will cause problems:
why dataType: 'jsonp'? If you don't intend to utilize jsonp, don't instruct jQuery to do this. See the docs: https://api.jquery.com/jQuery.ajax/
"jsonp": Loads in a JSON block using JSONP. Adds an extra
"?callback=?" to the end of your URL to specify the callback. Disables
caching by appending a query string parameter, "_=[TIMESTAMP]", to the
URL unless the cache option is set to true.
'obj='+JSON.stringify(ClientObject), this will guarantee invalid json.
For reference, have a look at this question: jQuery ajax, how to send JSON instead of QueryString on how to send json with jquery.
That said, try the following:
function senddata() {
$.ajax({
url: 'app.php',
type: 'POST',
crossDomain: true,
contentType: 'application/json; charset=utf-8"',
data: JSON.stringify(ClientObject),
success : function(res) {
console.log(res);
},
error: function(err) {
}
});
}
And in app.php use
$input = json_decode(file_get_contents('php://input'));
to get the data. Use it like:
var_dump($input->ClientData[0]->firstName); // => string(6) "Master"
$Ojb = json_decode($_POST['obj'],true);
makes it array so u need to get them using array index instead of object
UPDATE1
With your update here how it could be done
$str ='{"ClientData":[{"firstName":"Master","lastName":"Tester","email":"me#me.com","‌​dob":"1973-01-22","age":"51","pierceType":"Vici","street":"number of house","city":"here","county":"there","postcode":"everywhere"}],"HealthData":[["‌​condtion : Prone to Fainting / Dizziness","condtion : Allergic Response to Plasters","condtion : Prone to Fainting / Dizziness"]],"PiercerData":[{"firstName":"Male","lastName":"checking","pierceDat‌​e":"2013-02-25","jewelleryType":"Vici","jewelleryDesign":"Vidi","jewellerySize":"‌​Vici","idChecked":null,"medicalChecked":null,"notes":"This is for more info"}]}' ;
$obj = json_decode($str,true);
echo $obj["ClientData"][0]["firstName"];
You can get other elements as above
UPDATE2
You are sending the data as JSONP and this will make the request as
?callback=jQuery17108448240196903967_1396448041102&{"ClientData"
Now you are also adding data: 'obj=' which is not correct.
You can simply send as json not jsonp
and on the php file you can do as
$Ojb = json_decode(file_get_contents('php://input'),true);

onchange F(x) to php to Highchart on same page

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);

Cannot populate form with ajax and populate jquery plugin

I'm trying to populate a form with jquery's populate plugin, but using $.ajax
The idea is to retrieve data from my database according to the id in the links (ex of link: get_result_edit.php?id=34), reformulate it to json, return it to my page and fill up the form up with the populate plugin. But somehow i cannot get it to work. Any ideas:
here's the code:
$('a').click(function(){
$('#updatediv').hide('slow');
$.ajax({
type: "GET",
url: "get_result_edit.php",
success: function(data)
{
var $response=$(data);
$('#form1').populate($response);
}
});
$('#updatediv').fadeIn('slow');
return false;
whilst the php file states as follow:
<?php
$conn = new mysqli('localhost', 'XXXX', 'XXXXX', 'XXXXX');
#$query = 'Select * FROM news WHERE id ="'.$_GET['id'].'"';
$stmt = $conn->query($query) or die ($mysql->error());
if ($stmt)
{
$results = $stmt->fetch_object(); // get database data
$json = json_encode($results); // convert to JSON format
echo $json;
}
?>
Now first thing is that the mysql returns a null in this way: is there something wrong with he declaration of the sql statement in the $_GET part? Second is that even if i put a specific record to bring up, populate doesn't populate.
Update:
I changed the populate library with the one called "PHP jQuery helper functions" and the difference is that finally it says something. finally i get an error saying NO SUCH ELEMENT AS
i wen into the library to have a look and up comes the following function
function populateFormElement(form, name, value)
{
// check that the named element exists in the form
var name = name; // handle non-php naming
var element = form[name];
if(element == undefined)
{
debug('No such element as ' + name);
return false;
}
// debug options
if(options.debug)
{
_populate.elements.push(element);
}
}
Now looking at it one can see that it should print out also the name, but its not printing it out. so i'm guessing that retrieving the name form the json is not working correctly.
Link is at http://www.ocdmonline.org/michael/edit_news.php with username: Testing and pass:test123
Any ideas?
First you must set the dataType option for the .ajax call to json:
$.ajax({dataType: 'json', ...
and then in your success function the "data" parameter will already be a object so you just use it, no need to do anything with it (I don't know why you are converting it into a jQuery object in your code).
edit:
$( 'a' ).click ( function () {
$( '#updatediv' ).hide ( 'slow' );
$.ajax ( {
type: "GET",
url: "get_result_edit.php",
success: function ( data ) {
$( '#form1' ).populate ( data );
},
dataType: 'json'
} );
$( '#updatediv' ).fadeIn ( 'slow' );
return false;
}
also consider using $.getJSON instead of $.ajax so you don't have to bother with the dataType
Try imPagePopulate (another jquery plugin). It may be easier to use:
http://grasshopperpebbles.com/ajax/jquery-plugin-impagepopulate/

Categories