Sending json from Javascript to Javascript - javascript

I have a js inside a jsp from where I want to send a json in another js.
In jsp the console.log(html_out); prints the json right.
$.ajax({
//ajax code
},
async: true
})
.done(function(html_out) {
console.log(html_out);
drawTable(html_out);
})
Output for console.log(html_out):
{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }
But, in js the json doesn't put the data right inside the table i want to put them. The console.log(rowData); displays :
{
t
i
t
l
e
:
"
h
...
...
Here is my code in the js that i want to print my json:
function drawTable(data){
for (var i=0; i<data.length; i++){
drawRow(data[i]);
}
}
function drawRow(rowData) {
console.log(rowData);
var row = $("<tr />")
$("#farmacyDataTable").append(row);
row.append($("<td>" + rowData.title + "</td>"));
row.append($("<td>" + rowData.name + "</td>"));
}

As mentioned by dfsq, you have to parse the JSON string into a JavaScript object, right now you are iterating over the string
$.ajax({
//... ajax code
async: true, // Not needed, it default to async: true, async:false is deprecated
// If you add the line below, you don't need to parse the response
// dataType: 'json'
})
.done(function(html_out)
drawTable(JSON.parse(html_out));
})
If you correctly set the MIME type for the response (on the server), you will not need to call JSON.stringify
http://api.jquery.com/jquery.ajax/
dataType: The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string). The available types (and the result passed as the first argument to your success callback) are:

var parsed = JSON.parse(html_out);
drawTable(parsed);
Please take a look at the JSON.parse MDN page for browser compatibility.

I made some corrections to your code, you can play with it here: https://jsfiddle.net/mzf4axc0/
var jsonData=[{ title: "hello1", name: "nam1" },{ title: "hello2", name: "nam2" }];
function drawTable(data){
for (var i=0; i<data.length; i++){
drawRow(data[i]);
}
}
function drawRow(rowData) {
console.log(rowData);
var row = $("<tr /><td>" + rowData.title + "</td><td>" + rowData.name + "</td>" + "</tr>");
$("#farmacyDataTable").append(row);
}
$(document).ready(drawTable(jsonData));

Related

\r\n characters in CSV file not treated as line breaks

Apologies for what is surely a bonehead question...
I am trying to create a CSV file that looks like this:
Header1,Header2,Header3,
"Value1","Value2","Value3"
Instead, I'm getting a CSV file that looks like this:
Header1,Header2,Header3,\r\n"Value1","Value2","Value3"
How do I get my CRLF characters to actually produce line breaks in my output?
What I'm doing is making an ajax call to a WebMethod that generates a datatable from a stored proc. That datatable is then parsed out to a CSV like so:
if (!createHeaders)//I deal with the headers elsewhere in the code
{
foreach(DataColumn col in table.Columns){
result += col.ColumnName + ",";
};
result += Environment.NewLine;
}
for (int rowNum = 0; rowNum < table.Rows.Count; rowNum++)
{
for (int colNum = 0; colNum < table.Columns.Count; colNum++)
{
result += "\"" + (table.Rows[rowNum][colNum]).ToString();
result += "\",";
};
result += Environment.NewLine;
};
return result;
}
That string is then passed back to the success function of the ajax query, where it undergoes a few more transformations...
function getExportFile(sType) {
var alertType = null
$.ajax({
type: "POST",
url: "./Services/DataLookups.asmx/getExcelExport",
data: JSON.stringify({ sType: sType }),
processData: false,
contentType: "application/json; charset=utf-8",
dataType: "text",
success: function (response) {
response = replaceAll(response,"\\\"", "\"")
response = response.replace("{\"d\":\"", "")
response = response.replace("\"}", "")
download(sType + ".csv",response)
}
});
function download(filename, text) {
var element = document.createElement('a');
element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
element.setAttribute('download', filename);
element.style.display = 'none';
document.body.appendChild(element);
element.click()
document.body.removeChild(element);
}
function escapeRegExp(str) {
return str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, "\\$1");
}
function replaceAll(str, find, replace) {
return str.replace(new RegExp(escapeRegExp(find), 'g'), replace);
}
In my debugging before the string is passed back to javascript, if I just type ?response, I get the incorrect, all-on-one-line response. However, when I type ?resonse,nq the linebreaks are recognized, and everything looks the way it should.
Also, I'm sure there is PLENTY that I'm doing wrong/stupidly here. Pointing out those instances is also appreciated.
Your header should have data:Application/octet-stream, as MIME-type instead of data:text/plain;charset=utf-8,, the reason being that as per HTTP specifications, when the content type is unknown, the recipient should treat it as type application/octet-stream.
Since you are already using the encodeURIComponent(), that seems to be the only issue remaining.
#AryKay's answer surely helped, but there was one additional issue. The string returned by the Ajax call had the\r\ns escaped into literals. Ran a
Response = response.replace (/\\r\\n/g, "\r\n")
Before passing to encodeURIComponent and it ran like a charm.

Force function to show result when they received with jquery.get method

this function gets results with $.get method from an asp ashx XML file :
$.get("http://www.example.com/example.ashx",
{ From: txtFrom, To: txtTo, Date: txtTime },
function (data) {
var arrFrom = [], arrTo = [], arrPrice = [];
$(data).find("F").each(function (index, item) {
arrFrom[index] = [];
arrTo[index] = [];
arrPrice[index] = [];
$(item).find("From").each(function (i, fromIndex) {
arrFrom[index].push($(fromIndex).text());
});
$(item).find("To").each(function (i, toIndex) {
arrTo[index].push($(toIndex).text());
});
$(item).find("Price").each(function (i, priceIndex) {
arrPrice[index].push($(priceIndex).text());
});
});
/**********************************************************/
var htmlResult = "<table style=\"background-color:red;\">";
for (i = 0; i < arrFrom.length; i++) {
htmlResult += "<tr><td>" + arrFrom[i] + "</td>" +
"<td>" + arrTo[i] + "</td>" +
"<td>" + arrPrice[i] + "</td></tr>"
};
htmlResult += "</table>";
$('#divSearchResults').html(htmlResult);
/**********************************************************/
}, "text");
but ashx needs some time (unpredictable) to response.
I used a function to recall this each 5seconds, but it is not affordable.
how can I make htmlResult be created right when the response is received?
Your sample code is correct, in the sense that the anonymous function that you've defined fires as soon as your backend responds. If your data is empty, it could mean that something happens to the data while you're processing it in your javascript, your backend returned an empty dataset, or your backend timed out. To check whether the problem is with your backend or your data processing, try this:
$.get("http://www.example.com/example.ashx",
{ From: txtFrom, To: txtTo, Date: txtTime },
function (data) {
console.log(data);
//Or in case you don't have a developer console use alert:
alert(data);
}, "text");
You should now be able to verify that you are indeed getting data. If that's the case, then something is happening to the data when you're parsing it, and you should debug that code instead, perhaps with a static dataset. You could also make your life a lot easier by sending json encoded data instead of plaintext. I don't know how you would do that with your backend but I'm sure Google will help. On the javascript side of things you could then change the last line to:
}, "json");
Then, instead of find()ing things, you would have a neat json object to work with.

Twitter API - no encoding

I'm currently working on a project for university. we are trying to use the twitter api but we are having some trouble with the query. I want to search a complete string, therefore I need to put my string in quote sings.( like "I'm seraching for this whole sting")
the problem is that the command I use to get the array from twitter somehow encodes the whole string but I need the quote sings to not be encoded. I hope you guys understand my problem. in addition i'll post my js code.
JS CODE: first I tryed a json command but it didnt work. afterwards I tryed ajax but I ran into the same problem. I don't get a response when I use quote signs in my query.
$( document ).ready(function()
{
console.log("ready");
// div mit id unique1 - bei klick mache onClick1
$('a#unique1').bind('click', onClick1);
});
function onClick1(elem)
{
var inputString = $("#SearchInput").val();
var EncodedString = encodeURI(inputString);
console.log('test' + inputString);
var endNode = 'search/tweets.json?q=hate%20' + EncodedString + '&result_type=mixed&count=200';
/*
$.getJSON('twitter/twitter-proxy.php?url='+encodeURIComponent(endNode),
*/
$.ajax({
type: "GET",
url: 'twitter/twitter-proxy.php?url='+encodeURIComponent(endNode),
data: " ",
success: function(twitterResponse){
var respStr = "start";
console.log(twitterResponse);
console.log(twitterResponse.statuses);
for(var i = 0; i < twitterResponse.statuses.length; i++)
{
$('.container .apiCall ol').append('<li>'+ twitterResponse.statuses[i].created_at + '</br>' + twitterResponse.statuses[i].text.toLowerCase() + '</li>');
respStr = respStr + twitterResponse.statuses[i].created_at + twitterResponse.statuses[i].text.toLowerCase();
}
}
});
/*
function(twitterResponse)
{
var respStr = "start";
console.log(twitterResponse);
console.log(twitterResponse.statuses);
for(var i = 0; i < twitterResponse.statuses.length; i++)
{
$('.container .apiCall ol').append('<li>'+ twitterResponse.statuses[i].created_at + '</br>' + twitterResponse.statuses[i].text.toLowerCase() + '</li>');
respStr = respStr + twitterResponse.statuses[i].created_at + twitterResponse.statuses[i].text.toLowerCase();
}
*/
/*
// respSgtr = " ";
// write tweets to file
$.post("writer.php", { fileString:respStr},
function(response)
{
//alert("Data Loaded: " + data);
});
});*/
}
Your approach is flawed.
jQuery does all the parameter encoding for you. Don't interfere, just pass an object which contains keys and values. Do not build URLs from individual bits of string.
Important security consideration: Don't build a server-side proxy script that accepts any arbitrary URL. Doing this is plain stupid.
Instead change your PHP script to accept a set of operation verbs, like "search", which are hard-wired to the correct URL on the server side.
I recommend using $.get() and $.post() over $.ajax(), for the benefit of cleaner code.
Further, use $.each() rather than a regular for loop. The resulting code will be cleaner and easier to read.
Avoid building HTML from bits of string. Especially if the bits of string come from a completely untrustworthy source, like Twitter. Use jQuery's capabilities and the DOM to build HTML safely. (read about XSS vulnerabilities if you're not sure why I bring this up)
Suggested solution (appendText() jQuery plugin taken from here):
$.fn.appendText = function(text) {
return this.each(function() {
var textNode = document.createTextNode(text);
$(this).append(textNode);
});
};
$(function () {
$('a#unique1').on('click', function (event) {
$.get('twitter/twitter-proxy.php', {
operation: 'search',
params: {
q: 'hate ' + $("#SearchInput").val(),
result_type: 'mixed',
count: 200
}
}).done(function (twitterResponse) {
$.each(twitterResponse.statuses, function (index, status) {
$("<li>")
.appendText(status.created_at)
.append("<br>")
.appendText(status.text.toLowerCase())
.appendTo(".container .apiCall ol");
});
});
});
});

How to pass cakephp formhelper input values to ajax via jquery?

I am still new to cakephp, and my attempt is to retrieve the FormHelper's value and pass it via $.ajax() call in jquery. However, by cakephp convention, the name of each field generated by FormHelper will be in the format of data[Model][field]. Now, I want to submit $_POST data in form of cakephp array format. However, I couldn't find a way to do so, because I couldn't find a way to turn name and value attribute into a passable array format.
My attempt was to turn everything into string and try to create a json array. However, I failed to do so, and this method doesn't seem convincing to me too.
function submitEdit(sendurl, formid){
var dataset = [];
$('form#'+ formid + ' > input,select').each(function(){
dataset.push($(this).attr('name') + ':' + $(this).val());
});
alert(dataset);
$.ajax({
type: 'POST',
data: '{' + dataset + ']',
url: sendurl,
success: function(content){
$('.setting-preview.username').append('<pre>' + content + '</pre>');
}
});
}
Therefore, how do I pass this as data[Model][field] array to the sendurl controller?
Something like
$.ajax({
type: 'POST',
data: {
Model: {
foo: $('#ModelFoo').val(),
bar: $('#ModelBar').val()
}
},
url: sendurl,
success: function(content){
$('.setting-preview.username').append('<pre>' + content + '</pre>');
}
});

$.ajax json method does not hit the web method

When this function is hit , it does not call my function in code behind? Why could it be doing this? How can I fix this error.
$(document).ready(function() {
$('[id$=btn_Update]').click(function() {
var reten = $('[id$=txt_Reten]').val();
var i=0;
var selectValues = "";
var ProdID = new Array();
$("#lst_ProdId option").each(function() {
selectValues = selectValues + $(this).text() + ",";
ProdID[i] = $(this).text();
i++;
});
for(var j=0; j < ProdID.length;j++)
{
// alert(ProdID[j]);
}
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
$.ajax({
type: "POST",
url: "/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod",
data: params,
contentType: "application/json; charset=utf-8",
datatype: "json",
success: function(result) {
alert("sucess");
},
error:function(e) {
alert(e.statusText);
// if(errorThrown != null)
// alert(textStatus+ ":"+errorThrown);
// else
// alert("fail");
}
});
return false;
});
return false;
});
This is my webmethod in code behind:
[WebMethod]
public static bool UpdateRetenPeriod(string[] ProdID,string RetenP)
{
for (int i = 0; i < ProdID.Length; i++)
{
update(ProdID[i],RetenP);
}
return true;
}
You're passing your parameters as a string instead of as an object literal:
var params = "{'ProdID':'" + ProdID + "','RetenP':'" + reten + "'}";
should (almost certainly) be:
var params = {'ProdID': ProdID,'RetenP': reten};
Also, how do you know that the ajax request is not making it to the server? Have you tried tracing the HTTP requests with something like TamperData (for Firefox) or Firebug (also Firefox)?
Does it call the error method?
You need to return JSON. Not a boolean. Perhaps something like {success: true}.
Then:
success: function(data) {
if(data.success) {
...
}
else {
...
}
}
jQuery expects JSON and will throw an error if it doesn't receive well-formed JSON. Also, what is the exact response you're getting back? You can use something like Firebug to figure this out.
One more thing. Can you verify that you can successfully hit that URL? Are you able to successfully point your browser to http://your.url.here/ProductPricing/Products/RetenPeriod.aspx/UpdateRetenPeriod?
Also look at Pointy's solution. Your request is unlikely to succeed since you aren't passing in an actual object literal.
Do you have a ScriptManager defined in the markup with EnablePageMethods set to true?
Also, I believe your params line should be:
var params = "{ProdID:'" + ProdID + "', RetenP:'" + reten + "'}";
I have several functions in my own apps that do it this way. You want the value of params to look like this: "{ProdID:'1,2', RetenP:'undefined'}"
Can you place a breakpoint at alert(e.statusText); to see what the error message is?
Have u got error message.. please, try to get the error message
I think, u can use this by replacing error block
error:
function(XMLHttpRequest, textStatus, errorThrown){
alert( "Error Occured!" + errorThrown.toString());
}
I think, problems occurred in code behind method.. if in [web method] has any problem, then ajax doesn't call the method..

Categories