How to print array list data using ajax? - javascript

I am new to AJAX and JSON. I have an ArrayList which contains another ArrayList and I converted the whole array in to JSON object:
#Produces(MediaType.APPLICATION_JSON)
public String getRecords(#QueryParam("mobile_no") String mobilenumber) {
UserActivityDelegate delegate = new UserActivityDelegate();
List<AssessmentDTO> list = delegate.getLastFiveAssessment(mobilenumber
.trim());
if (list.isEmpty())
return "Sorry....You have not attended any assessment";
else {
System.out.println(list);
return (new Gson()).toJson(list);
}
Now I want to know how can I retrieve or iterate the response object in JSP using ajax??

In Ajax response you receive a response string you can convert that either to javascript list or json and iterate over them.
Like below:
jQuery.ajax({
type: 'POST',
url: your_url_string,
data: 1=1 //params,
async: false,
success: function(response,textStatus){
json= JSON.parse(response);
},
error:function(XMLHttpRequest,textStatus,errorThrown){}
});
then json object is what you need to take care of.

Related

Passing data from javascript to PHP via POST not working

Im trying to send an array, populated using javascript on client-side, to a php file in the backend.
MAIN.JS
var list = iterateItems();
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "string",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
TICKET.PHP
<?php
var_dump(json_decode($_POST['list']));
?>
And executing this, I'm getting this result:
Notice: Undefined index: list in D:\127.0.0.1/prog1/final/class/ticket.php on line 2
NULL
Im not understanding why im getting an undefined index.
I tried googling this, but most responses seem to point in the direction of using some kind of HTTPS method, which is what I'm trying to achieve via POST.
Any help will be greatly appreciated. Thank you.
The 'list' undefined issue might be due to the structure of the JSON array you pass.
Try the below code and check if it works. If not let's check further :)
var list = {'list': iterateItems()};
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", list)
.done(function(list){});
});
function _ajax(url,data) {
var ajax = $.ajax({
type : "POST",
datatype : "json",
url : url,
data : data
})
return ajax;
}
function iterateItems() {
// array is an array populated in this function, returned to be sent to ticket.php
return JSON.stringify( array );
};
Your PHP Code:
<?php
var_dump(json_decode($_POST['list']));
PHP can't parse JSON parameters automatically. $_POST will only be filled in from a URL-encoded string or a FormData object.
$.ajax will URL-encode an array automatically for you.
_ajax("https://127.0.0.1/prog1/final/class/ticket.php", array)
.done(function(list) {});
function _ajax(url, data) {
var ajax = $.ajax({
type: "POST",
dataType: "string",
url: url,
data: {list: data}
})
return ajax;
}
In PHP you then don't need to call json_decode(). The value of $_POST['list'] will be the array.

Trying to make an Ajax call to a web form method and getting an internal server error. I have tried almost all solutions to similar questions

The function getClientData() gets called from one of the anchor tags in a grid's column. The anchor tag has a couple of Data-Tags which are passed to the code behind method. I have to perform some DB operation through these parameters but before that I wanted to make sure if this prototype would work.
This is how the anchor tag looks:
Show
This is my Javascript method:
function getClientData() {
//var dataValue = { "keyData": this.event.target.getAttribute("data-kt"), "valueData": this.event.target.getAttribute("data-kv")};
$.ajax({
type: "GET",
url: "Clients.aspx/GetClientData",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ keyData: this.event.target.getAttribute("data-kt"), valueData: this.event.target.getAttribute("data-kv")}),
dataType: 'json',
error: function (error) {
alert(error.statusText);
},
success: function (result) {
alert("Success: " + result );
}
});
}
I put a break point here and it never gets triggered. This is my web method in the code behind file:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string keyData, string valueData)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}
This is the URL that gets created for the POST request "http://localhost:60825/Clients.aspx/GetClientData?{%22keyData%22:%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22,%22valueData%22:%221p7q9%22}". Please let me know if I am doing something wrong.
I am not sure how you configured routing but based on your API method (code behind) your data should be formatted in following manner:
Method 1:
http://localhost:60825/Clients.aspx/GetClientData?keyData=Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy&valueData=1p7q9
As you can see, instead passing stringified JSON object I am sending data in format of query string where keyData and valueData has corresponding values.
Method 2:
If you prefer to send stringified JSON you can modify your Payload in URL like this:
http://localhost:60825/Clients.aspx/GetClientData?data=%7BkeyData%22%3A%22Cpuqsrtsotmfegrhsi-jikdbCvuwsxtcodmeelrmI-Dn-ovpcqSresctrfegthKiejy%22%2C%22valueData%22%3A%221p7q9%22%7D
Here I am sending stringified JSON as data parameter in query string. For that purpose your code behing method needs to be like this:
[WebMethod]
[ScriptMethod(UseHttpGet = false)]
public string GetClientData(string data)
{
string result = string.Empty;
if (!string.IsNullOrEmpty(keyData) && !string.IsNullOrEmpty(valueData))
{
result = "Decrypted String!";
}
return result;
}

I mess up JSON object, arrays and strings

So i´m, trying send data from php to js.
PHP
$balkTypes[] = $stmt->fetchAll();
echo json_encode($balkTypes);
JS
balkTypesData = {}; //Outside Ajaxcall
success: function(result){
balkTypesData = result;
Console.log(balkTypesData);
}
Console
[[{"id":"3","typ":"Bas 200*600","hojd":"200","bredd":"600","rec":"","viktM":"135"},{"id":"2","typ":"Bas 240*600","hojd":"240","bredd":"600","rec":"","viktM":"160"},{"id":"5","typ":"Isol\u00e4tt 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"4","typ":"Kontur 240*600","hojd":"240","bredd":"600","rec":"","viktM":"105"},{"id":"6","typ":"Passbit","hojd":"0","bredd":"0","rec":"","viktM":"0"}]]
Now, i´d like to search my Json object?!
I´d like to find "viktM" for "typ:Bas 200*600"
//Get balkType weight/m
var searchField = "typ";
var searchVal = "Bas 200*600";
for (var i=0 ; i < balkTypesData.length ; i++){
if (balkTypesData[i][searchField] == searchVal) {
weigth = balkTypesData[i]['viktM'];
console.log(weigth);
}
}
First of all, it seams that i cannot use .lengton "balkTypsData". it gives me 410 hits. Must be all characters?
Second, i cannot find how to access part of my object.
If i use: console.log(balkTypesData[i][searchField]);
I get: "Undefined"
I have also tried to remove the "[i].
So what am i missing?
Be gentle i´m still learning.
Take a look at $.parseJSON() (jQuery) or JSON.parse() (vanilla):
With jQuery
success: function(result){
balkTypesData = $.parseJSON(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
Without jQuery
success: function(result){
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
console.log(balkTypesData[i][searchField]);
}
When you receive the data from your AJAX request it's not JSON, just a string.
The length result that you're getting is the length of the string, not the amount of elements within the array.
Furthermore you're setting $balkTypes[] which means that you're trying to add 1 entry in the array of $balkTypes however $stmt->fetchAll(); also returns an array so you now have a nested array which is not needed.
In your PHP file change
$balkTypes[] = $stmt->fetchAll()
to
$balkTypes = $stmt->fetchAll()
this will make sure that when you fetch your data it will be an array containing all objects instead of an array containing the array of objects.
Then in your JS, instead of trying to directly read from the string, use JSON.parse() to convert the json string into a collection of JS objects/integers/arrays/strings/booleans
e.g.
success: function(result) {
balkTypesData = JSON.parse(result);
console.log(balkTypesData);
}
EDIT
As pointed out by Armen you could also set the dataType: 'json' in the AJAX request, when the AJAX request returns it will automatically do the JSON.parse() so you can just directly console.log(result); to see the output.
Within the console.log you should now see the nested structure instead of just the string.
From here on your loop which checks the values seems correct and I would not change it unless it tells you that something is wrong.
Docs: JSON.parse();
Set in your jQuery $.ajax request additional attribute dataType: 'json'
$.ajax({
type: "POST",
dataType: "json",
url: url,
data: { params },
success: function( response )
{
// Your data will be already json no need to parse it
console.log(response);
}
});
You are encoding a JSON on the PHP side. You are not decoding it on the JS side.
You should look at JSON.parse()

Json serialization: how to send c# data to javascript script. Error: Invalid character

I'm trying to send data from Entity Framework database to js script on my webpage. This is my MVC Controller:
public ActionResult Index()
{
var wordsToShow = db.Words.Where(w => w.OwnerName == User.Identity.Name); // && DateTime.Compare(w.NextReview, DateTime.Now) <= 0
ViewBag.wordsToShow = HttpUtility.HtmlDecode(new JavaScriptSerializer().Serialize(wordsToShow));
var test = ViewBag.wordsToShow;
return View();
}
And in index.cshtml I've put this code:
<script>
var wordsJson = "#ViewBag.wordsToShow.ToString()";
var wordsAsObject = JSON.parse(wordsJson);
</script>
The problem is, javascript says:
Invalid character
In the line where I'm parsing json to javascript object. The reason is: json string doesn't look like it should. This is part of what's inside "wordsJson" variable in web browser:
What can I do to make it work?
You're going about in an overly roundabout way. JSON is called "JavaScript Object Notation" for a reason. There's no need to put it in a string and re-parse it. You can just use the JSON as JavaScript.
ASP.NET MVC has a helper for serializing values as JSON, so you can just use that and assign it to a variable in your JavaScript:
<script>
var wordsAsObject = #Html.Raw(Json.Encode(ViewBag.wordsToShow));
</script>
This would eliminate the need to do the JSON serialization within your Action.
I suspect that the reason you're encountering this issue is that by default, values inserted into a view with # are automatically HTML encoded. You can use Html.Raw() to prevent this, as I've done above, but as I said, there's no reason to put it into a string first and parse it.
I always create Method that return JsonResult/string
like:
public string GetData()
{
//your logic here
string json_sales = JsonConvert.SerializeObject(<<your data>>);
return json_sales;
}
and in JavaScript I just do AJAX request:
$.ajax({
url: 'PUT_YOUR_URL_HERE_To_METHOD_GetData',
dataType: "json",
type: "GET",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify({ Make: maka.value }),
async: true, // Or false
cache: false,
success: function (data) {
//do something
}
},
error: function (xhr) {
alert('error');
}
})

Ajax call to Asp.net Web Method using Jquery

I am using a jquery method, to send information (namely only member identification #) from client side to the server side.
The server side has the traditional Web Method implemented so as to capture data sent and execute SQL queries based on it.
Web-service-method-using-jQuery
However until now I have been returning a single string from the server side back to the client side after the SQL query.
Wondering what would be the best way to return a complicated series of strings... member Identification number, start date, end date, type of member... depending on the type of the member, there can be multiple start dates and end dates.
Should I be looking into XML ?
What about returning even a datatable
$.ajax({
type: "POST",
url: "YourPage.aspx/doSomething",
data: "{'id':'1'}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
var returnedstring = data.d;
var jsondata = $.parseJSON(data.d);//if you want your data in json
}
});
aspx:
[WebMethod]
public static string doSomething(int id)
{
....
DataTable dt = new DataTable();
dt = anothermethodReturningdt(id)
return JsonConvert.SerializeObject(dt);
}
You can use json.net for serializing .Net objects
Edit
you can also do this
[WebMethod]
public static string doSomething(int id)
{
Product product = new Product();
product.Name = "Apple";
product.Expiry = new DateTime(2008, 12, 28);
product.Price = 3.99M;
product.Sizes = new string[] { "Small", "Medium", "Large" };
return JsonConvert.SerializeObject(product);
}
The point is you can serialize any type of object, arrays, collections etc and then pass it back to the calling script.

Categories

Resources