JSON response into HTML - ajax

Could you please help me in forming the DIV block(HTML) for the response which i got in JSON format.
JSON format: [{"REL_NAME" : " 999999999","SO" : "","U_ID" : "105"}]
Snippet:
function ServiceSucceeded(result) {
$('#accNo12').empty();
if (DataType == "json") {
$('#accNo12').append("<div id=\"Search\" class=\"results\">"+
"<span id=\"lb\">Account No:"+result.U_ID+"</span></div>"+
"<label>RelMgr: </label>"+
"<span id=\"RID\">"+result.REL_NAME +"</span><br />"+
"<label>Off ID: </label><span id=\"OffId\">"+ result.SO+"</span><br/>");
}
}
As of now i am getting the output values as undefined.
Appreciate if you could help
Thanks

function ServiceSucceeded(result) {
$('#accNo12').empty();
if (DataType == "json") {
result = result[0];
...
basically, your result object is inside an array. alternatively you can use result[0].U_ID instead of result.U_ID

I think your problem here is that you don't parse the JSON data
Add this at the beginning of your function,
result = jQuery.parseJSON(result);

Basically you are checking for an inexistent DataType. I fiddled around and here are the results:
html:
<div id='accNo12'>hello</div>
javascript:
function ServiceSucceeded(result,DataType) {
alert(DataType);
$('#accNo12').empty();
if (DataType == "json") {
$('#accNo12').append("<div id=\"Search\" class=\"results\">"+
"<span id=\"lb\">Account No:"+result.U_ID+"</span></div>"+
"<label>RelMgr: </label>"+
"<span id=\"RID\">"+result.REL_NAME +"</span><br />"+
"<label>Off ID: </label><span id=\"OffId\">"+ result.SO+"</span><br/>");
}
}
$(document).ready( function () {
ServiceSucceeded(jQuery.parseJSON('{"REL_NAME" : " 999999999","SO" : "","U_ID" : "105"}'),'json');
});
result:
Account No:105
RelMgr: 999999999
Off ID:

Related

Read and Display values from json using ajax

Im trying to get data from a .json file that is recieved via post method to a external server, using ajax function and display it all on html (tags and data).
I can get the json data and display it via console log, however im not able to iterate over it, or simply display in on the html side.
I've tryed to create a public array and push the response to it, create a function, etc.. but looks like ajax function loads after it, and there's no data at all, then i've tried to concat a string with the values that i get on console, but no success.
I can't even get the actual data, only the tags. Im a little bit confused here. Can some one help me?
Here's my code and what it displays on console.
component.hmt:
<ul>
<li>{{res}}</li>
</ul>
component.ts
public res = "";
ngOnInit() {
let settings = {
"async": true,
"crossDomain": true,
"url": "ip/to/api",
"context": this, //added this
"method": "POST",
"data": "\"dataApi\"",
};
$.ajax(settings).done(function (response) {
console.log(response);
this.res = response; //added this
for(let i in response)
{
//console.log(i);
this.res += i + " - ";
for(let j in response[i])
{
//console.log(j);
this.res += j + " : \n ";
for(let t in response[i][j])
{
//console.log(t);
this.res += t +"\n";
}
}
}
console.log(this.res);
return this.res;
});
}
}
Here's the output on console.log:
the thing is that on console log i can get all the tags : data, but i can't never get the data on res string to display.
Console.log(response) : All the data i need to display.
this.res : the tags without any data.
Thanks in advance!!
Edit: Here's the output of {{res | json}} on html side:
{ "Challenges": [ { "Challenge.Closed": false,
"Challenge.EndSubmissionDate": "Sat Feb 13 00:00:00 GMT 2010",
"Challenge.Title": "net.Partner", "Challenge.CompositeId":
"Id=3_Tenant=103", "Challenge.Code": "2010/001"....
I have the json like text based..i want for example:
Challenge.Closed : false
....
Idea.id: 4
...
and access some of the tags that i know that exists, like id..
Do i have to map it?
So i think i am close, i know that with {{res | json }} i can print all the data and tags, including curly braces etc from the json file. (its like a json file to text)
But i need to print only the entity: tags and values. keep in mind that i neves know what comes on the json file. Here's what i have so far:
public entity = [];
public cont = [];
.Created and array and pushes all the entities:
this.res = response;
for(let i in response)
{
//array with entities inside json
this.entity.push(i);
}
return this.res;
the on the html side i can get:
<!-- all the data from json-->
<ng-container>
<li>{{res}}</li>
</ng-container>
<!-- all the Challenges or whatever comes after res --- res.HERE-->
<ng-container>
<li>{{res.Challenges | json}}</li>
</ng-container>
<!-- or (example with Ideas)-->
<ng-container *ngFor="let x of res.Ideas">
<li>{{x | json}}</li>
</ng-container>
<!-- print all the entities that come in the json
(challenges, Ideas, whatever.. that goes with res.HERE)-->
<ng-container *ngFor="let i of entity">
<li>{{i}}</li>
</ng-container>
so, i can get the entities, each entity has its own attributes, for example to entity Challenges:
Challenge.Closed
Challenge.EndSubmissionDate
Challenge.Title
etc..
but how can i acess the values to each attribute? with the html i've posted i can get what's inside the coments, so i could iterate each entity like:
<!-- json file has 2 entities -->
<ng-container *ngFor="let i of entity">
<!-- trying to print res.Challenges and res.Ideas -->
<ng-container *ngFor="let jsn of res.i">
<li>{{jsn | json}}</li>
</ng-container>
</ng-container>
but, no success. i don't see how can i solve it!
with that for loop i've posted earlier:
for(let i in response)
{
this.cont.push(i);
for(let j in response[i])
{
this.cont.push(j);
for(let t in response[i][j])
{
this.cont.push(t);
}
}
}
I've printed on the html side:
the best thing was to get the values for each "entity.attribute" and not only the tags like i have (showed on the image)
A little closer to the solution, i've found the way to retrive the values, for example to entity Challenge:
this.responseList.Challenges["0"]["Challenge.Code"]
gives me the challenge code.
But instead of challenge it can be whatever, that's the name of entity, for example Ideas:
this.responseList.Ideas["0"]["Idea.Code"]
gives me the idea code.
if i want to know the names of each entity:
this.responseList
>{Challenges: Array(13), Ideas: Array(1)}
The test was made on console with a debugger in the 'for loop' inside the code that follows:
html - Im just printing Challenges, but i neves knwo what entity i have.. it can me Ideas, or other..
<ul *ngFor="let res of responseList.Challenges">
<li> {{res | json}} </li>
</ul>
Component.ts
public entity = []; //has the entity names ideias, challenges whatever...
public responseList = ""; //the json that comes from the server
ngOnInit() {
let settings = {
"async": true,
"crossDomain": true,
"url": "ip/to/api",
"method": "POST",
"data": "\"dataApi\"",
};
$.ajax(settings).done((rest) => this.response(rest));
}
response(res){
this.responseList = res; //the json file with allt he information
for(let i in res)
{
//array with all entities inside json
this.entity.push(i);
}
debugger;
}
Based on that information, i have to work inside .ts with for loops and arrays and the just print the result on .html, right? Can somebody help me with that?
Edited for solution
If i could print the values on the console, i can print them too with my previous for loop:
component.ts:
for(let i in res)
{
for(let j in res[i])
{
this.singleArray.push({
tag: i,
value: val
});
for(let t in res[i][j])
{
this.singleArray.push({
tag: t,
value: this.responseList[i][j][t]
});
if(t.split(".",2)[1] === "CompositeId")
{
this.singleArray.push({
tag: "URL:",
value: this.moduleName + "/" + t.split(".",2)[0] + "/" + this.responseList[i][j][t].match(/=(.*)_/)[1]
});
}
}
}
}
with that 'for loop' i can get the tag and the value:
to print them on html side:
html
<ng-container *ngFor="let item of singleArray">
<li>
{{item.tag}} - {{item.value}}
</li>
<a *ngIf="item.tag.includes('URL')"> <li>- LINK -</li></a>
</ng-container>
You should use the $.ajax() context object here like:
let settings = {
"async": true,
"crossDomain": true,
"url": "ip/to/api",
"context": this,
"method": "POST",
"data": "\"dataApi\"",
};
try this:
all you have to do is to loop through response
.HTML
<div class="div1">
<ul class="r " *ngFor="let res of responseList.challenges">
<li>
{{res.closed}}
</li>
</ul>
</div>
.TS
public responseList = "";
ngOnInit() {
let settings = {
"async": true,
"crossDomain": true,
"url": "ip/to/api",
"method": "POST",
"data": "\"dataApi\"",
};
$.ajax(settings).done() = (res) => this.response(res);
response(res){
console.log(res);
this.responseList = res;
}

submit form if don't have error

i am using ajax for send active form by this function
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() { $.ajax({url: '".$url."',type: 'POST',success : function(res){ $('#".$dviId."').html(res);}});});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}
And want to show error if any happened else send form
There is a plugin in jquery to do client side validation if you are using javascript and want to do initial validation of the form.
http://jqueryvalidation.org/
Also you can use "required" attribute in your text tags to do some intial checks. More can be found here:
http://www.w3schools.com/tags/att_input_required.asp
Hope this helps a bit.
You can also set enableAjaxValidation to true in your form.
There is an example in the docs about that (see the controller part).
public function Link()
{
$id=$this->params['id'];
$url=$this->params['url'];
$dviId=$this->params['divId'];
if(isset($this->params['confirm'])) {
$confirm = "if(confirm('".$this->params['confirm']."')){";
$endConfirm = "}";
}
else
{
$confirm = "";
$endConfirm = "";
}
$url=Yii::$app->urlManager->createAbsoluteUrl($url);
$js2="$('#".$id."').on('click', function() {".$confirm."$.ajax({url: '".$url."',type: 'POST',beforeSend: function(){ $('body').addClass('wait');},complete: function(){ $('body').removeClass('wait');},success : function(res){ $('#".$dviId."').html(res);}});".$endConfirm."});";
$view = $this->getView();
AjaxAsset::register($view);
if ($js2 !== '') {
$view->registerJs($js2);
}
return ;
}

Ajax multiple response

I need to fetch the names using mysql query for which I'm trying to send some values via ajax to php.
Js file:
var dataselect = 'catg='+ $('#catg_list').val() + '&brand='+ $('#brand_list').val(); // get data in the form manual
$.ajax({
type="POST",
url:"check.php"
data: dataselect,
success: function(data) {
alert (data);
}
});
check.php file
<?php
include(database connection);
$catg_list= $_POST['catg'];
$brand_list= $_POST['brand'];
if ($catg_list!="") {
$catg_query = mysql_query("SELECT name FROM categories WHERE id='$catg_list'");
if ($catg_query) {
while ($row_catg=mysql_fetch_assoc($catg_query)) {
echo $row_catg['name'];
}
}
}
if ($brand_list!="") {
$brand_list = mysql_query("SELECT name FROM brand WHERE id='$brand_list'");
if ($brand_list) {
while ($row_brand=mysql_fetch_assoc($brand_list)) {
echo $row_brand['name'];
}
}
}
?>
Problem is I need to display both the above names separately in . Is it possible? I am very much new to ajax. Any help would be great.
Thanks
You should be sending your data back in JSON format. You can send back a JSON object, which is like an associative array in PHP. You could use this php code:
<?php
include(database connection);
$catg_list= $_POST['catg'];
$brand_list= $_POST['brand'];
$results = array('categories' => array(), 'brands' => array());
if ($catg_list!="") {
$catg_query = mysql_query("SELECT name FROM categories WHERE id='$catg_list'");
if ($catg_query) {
while ($row_catg=mysql_fetch_assoc($catg_query)) {
$results['categories'][] = $row_catg['name'];
}
}
}
if ($brand_list!="") {
$brand_list = mysql_query("SELECT name FROM brand WHERE id='$brand_list'");
if ($brand_list) {
while ($row_brand=mysql_fetch_assoc($brand_list)) {
$results['brands'][] = $row_brand['name'];
}
}
}
echo json_encode($results);
?>
Then, in your javascript success function, your data variable will be an object with two fields, each containing an array.
{
categories: [],
brands: []
}
You can access them by iterating over data.categories and data.brands.
Lastly, do not use SQL statements with data straight from your $_POST array. You have to sanitize that.
js
var dataselect = 'catg='+ $('#catg_list').val() + '&brand='+ $('#brand_list').val(); // get data in the form manual
var x, y;
$.ajax({
type="POST",
url:"check.php"
data: dataselect,
success: function(data) {
var x = data.categories[0];
var y = data.brand[0];
}
});

Bootstrap Typeahead with AJAX source (not working)

I'm trying to implement a search bar dropdown using bootstrap v3.0.0 with typeahead.js.
My search bar will take a student's firstname and lastname. I'm using a MYSQL database which consists of a table called practice with afirstname, alastname, aid as columns. The search bar should not only contain the firstname and lastname in the dropdown, but also the id associated with it in a second row. I've read all the examples on the typeahead.js page and I'm unable to do it with ajax call.
Below is the code of my index.php
JS
<script type="text/javascript">
$(document).ready(function() {
$('.cr.typeahead').typeahead({
source: header: '<h3>Select</h3>',
name: 'accounts',
source: function (query, process) {
return $.getJSON(
'localhost/resultly/source.php',
{ query: query },
function (data) {
return process(data);
});
});
});
</script>
HTML:
<body>
<div class="container">
<br/><br/>
<input type="text" name="query" class="form-control cr typeahead" id="firstname" />
<br/><br/>
</div>
</body>
Code for source.php : This should return the firstname and lastname from my database in the form of a json string or object?
<?php
$query = $_POST['query'];
try {
$conn = new PDO('mysql:host=localhost;dbname=practice','root','');
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
$stmt->execute();
}
catch (PDOException $e) {
echo 'ERROR:' . $e->getMessage();
}
foreach ($stmt as $row) {
$afirstname[] = $row['afirstname'];
$alastname[] = $row['alastname'];
}
echo json_encode($afirstname);
echo json_encode($alastname);
?>
result:
http://oi41.tinypic.com/50moi1.jpg
Nothing shows up. I've tried adding a prefetch:
prefetch: {
url: 'localhost/resultly/source.php',
filter: function(data) {
r1 = [];
for (var i = 0; i < data.length; i++) {
r1.push({
value: data[i].afirstname,
tokens: [data[i].afirstname, data[i]alastname],
afirstname: data[i].afirstname,
alastname: data[i].alastname,
template: '<p>{{afirstname}} - {{alastname}}</p>',
});
}
return r1;
}
}
Please do provide a solution or an example which I could refer.
Update:
The source.php should return a list of json encoded data. I debugged by looking at the output that the source.pho created. What I did wrong was whenever I was supposed to put a url I did localhost/source.php instead of just source.php.
Solution provided by Bass Jobsen works and now I have run into another problem.
I'm using
if(isset($_POST['query']))
{ $q_uery = $_POST['query'];
$query = ucfirst(strtolower($q_uery))};
to take the user's data and use it for searching logic
$stmt = $conn->prepare("SELECT * FROM actualtable WHERE afirstname LIKE '%($query)%'");
The updated source.php is http://pastebin.com/T9Q4m10g
I get an error on this line saying Notice: Undefined variable: stmt I guess the $query is not being initialized. How do I get this to work. Thanks.
Update 3
I used prefetch: instead of 'remote:' that did all the matching.
Your return is not correct:
echo json_encode($afirstname);
echo json_encode($alastname);
See for example Twitter TypeAhead.js not updating input
Try echo json_encode((object)$stmt);, see: typeahead.js search from beginng
Update
I tried echo json_encode((object)$stmt);still doesn't work.
Do you use any kind of debugging? What does? source.php return? Try to follow the steps from
typeahead.js search from beginng without the filter.
html:
<div class="demo">
<input class="typeahead" value="" type="text" spellcheck="off" autocomplete="off" placeholder="countries">
</div>
javascript:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10
});
php (source.php):
<?php
$people = array();
$people[] = array("lastname"=>"Inaw",
"firstname"=>"Dsajhjkdsa");
$people[] = array("lastname"=>"Dsahjk",
"firstname"=>"YYYsgbm");
$people[] = array("lastname"=>"Dasjhdsjka",
"firstname"=>"JHJKGJ");
$datums = array();
foreach($people as $human)
{
$datums[]=(object)array('value'=>$human['firstname'],'tokens'=>array($human['firstname'],$human['lastname']));
}
echo json_encode((object)$datums);
This should work
update2
Thanks, it worked. How do I display 2 or more 'value'?
add some values to your datums in source.php:
foreach($people as $human)
{
$datums[]=(object)array
(
'value'=>$human['firstname'],
'tokens'=>array($human['firstname'],$human['lastname']),
'firstname'=>$human['firstname'],
'lastname'=>$human['lastname']
);
}
firstname and lastname now are field you csn use in your templates
Add a template and template engine to your javascript declaration:
$('.typeahead').typeahead({
remote: 'http://testdrive/source.php?q=%QUERY',
limit: 10,
template: [
'<p>{{firstname}} - {{lastname}}</p>'
].join(''),
engine: Hogan
});
The above make use of https://github.com/twitter/hogan.js. You will have to include the template engine by javascript, for example:
<script src="http://twitter.github.io/typeahead.js/js/hogan-2.0.0.js"></script>
It is working for me. please follow below step.
Please add below Js and give proper reference.
bootstrap3-typeahead
--- Ajax Call ----
$("#cityId").keyup(function () {
var al = $(this).val();
$('#cityId').typeahead({
source: function (valuequery, process) {
var states = [];
return $.ajax({
url: http://localhost:4000/GetcityList,
type: 'POST',
data: { valueType: "", valueFilter: valuequery },
dataType: 'JSON',
success: function (result) {
var resultList = result.map(function (item) {
states.push({
"name": item.Value,
"value": item.Key
});
});
return process(states);
}
});
},
});
});
---- Cs Code ---
public JsonResult SearchKeyValuesByValue(string valueType, string valueFilter)
{
List<KeyValueType> returnValue = SearchKeyValuesByValue(valueType, valueFilter);
return Json(returnValue);
}
Auto suggest of Bootstrap typehead will get accept only "name" and "value" so create reponse accordinly

How to pass complex search criteria to jqgrid from query string

I tried code below to pass filter to url which invokes jqgrid. jqGrid still shows all rows, passed filter is not passed to url to retrieve data form server.
How to force jqGrid to filter by filter passed in query string ?
window.open( '/Grid?filters=' + encodeURIComponent(
'{"groupOp":"AND","rules":[{"field":"Name","op":"cn","data":"John"}' ));
You can parse window.location.href and get all parameters which you need. If the URL contains the parameter which you need you can decode it with respect of decodeURIComponent and use like you as need.
The following code can be used for tests. It demonstrate how to decode filters parameter.
if (window.location.href.indexOf('?') < 0) {
// the code will open the current HTML page with additional
// parameter "filters" and reopen the same page with the parameters
window.location = window.location.href + '?' +
$.param({
filters: JSON.stringify({
groupOp: "AND",
rules: [
{field: "Name", op: "cn", data: "John Smith"}
]
})
});
} else {
// decode URL parameters and place in the as properties in the
// object "parameters":
var namedParameters = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&'),
parameters = {},
nameAndValue,
i;
for (i = 0; i < namedParameters.length; i += 1) {
nameAndValue = namedParameters[i].split('=');
parameters[nameAndValue[0]] = decodeURIComponent(nameAndValue[1]);
if (nameAndValue[0] === "filters") {
// display the data from the "filters" parameter
var myFilters = $.parseJSON(decodeURIComponent(nameAndValue[1]));
alert(myFilters.rules[0].data);
}
}
}

Resources