I'm trying to append a some HTML to a code in jquery, but chrome keeps throwing "unexpected string" at the append function, here's the code :
for (var i =0 ;i<resultArray.length;i++){
$.ajax({url:"getExpenseInfo.php",type:"POST",data : {
'expenseId' : resultArray[i]["expenseId"]
},success:function(expense){
expense = $.parseJSON(expense);
$("#mainDiv").append("<div class=\"row\">".expense["expenseName"]."</div>");
}});
}
I guess you're mixing up php and js syntax, string concatenation works with + in js and not ..
$("#mainDiv").append("<div class=\"row\">" + expense["expenseName"] + "</div>");
Your string concatenation in your append function is a little off. Try something like this:
for (var i =0 ;i<resultArray.length;i++){
$.ajax({url:"getExpenseInfo.php",type:"POST",data : {
'expenseId' : resultArray[i]["expenseId"]
},success:function(expense){
expense = $.parseJSON(expense);
$("#mainDiv").append("<div class=\"row\">"+expense[expenseName]+"</div>");
}});
}
Related
i could not make it as function.Please help.When i modified as function and add button,it not work.
i'm newbie in javascript.i would like study by the simple script.But for the below script when i try to add "function xxx()" it not working with input button.
I try to solve by my own with google...failed.
<script>
var myStr = "xxx yyy zzz";
var strArray = myStr.split(" ");
// Display array values on page
for(var i = 0; i < strArray.length; i++){
document.write("<p>" + strArray[i] + "</p>");
}
</script>
Break your code into blocks if you ever are stuck on something. So first you are trying to break a string into an array so that's your first block. Then your second block would be to write it to the page. So we have our code basically written out in our heads.
---Break string
---Display broken string
So to make a function we need to write a function first
myFunction = function(){
};
But to get the function to be modular we need to be able to pass in variables
So we'll add two variables one being the string to pass through and one being the location to inject the looped broken text.
myFunction = function(str, location){
};
Now we have to do something with these variables.
myFunction = function(str, location){
///test if str is a string
if(typeof(str) == "string")
{
var l = str.split(" "); /// here we're spliting the string into an array by every space
if(l.length >= 1) ///test if there's atleast one item
for(i=0;i<l.length;i++) ///simple for loop
location.innerHTML += "This is a part of str " + l[i] + "<br>" ///you can do anything here you want to do.
}
};
Now as you can see it's modular at it's lowest point, this can be as complex as you want it. here is a test you can try out and mess around with. https://jsfiddle.net/s8pytzm3/1/
Line break in javascipt string console
console.log("Foo" + "\n" + "Bar");
Line break in javascript object console
console.log({ value : "Foo\nBar" });
Is it possible to add linebreaks in javascript objects.
The answer is no: when you print an object to the console log, strings will be written as javascript objects (similar but not identical to what you'd get if you explicitly converted them into JSON, like console.log(JSON.stringify(object))).
If you want for some reason to print your strings with line breaks, you'd have to implement the object-to-string conversion yourself; perhaps with something like this:
function customString(object) {
let string = '{\n';
Object.keys(object).forEach(key => {
string += ' "' + key + '": "' + object[key] + '"\n';
});
string += '}';
return string;
}
console.log(customString({ value: "Foo\nBar" }));
(It sounds like you have an idea in mind of exactly how you want this output to look, so adjust the function above until it works as expected.)
You can make JSON pretty with automatic line breaks using:
console.log(JSON.stringify({ test: { key: { inner: 'val' } }}, null , 2))
Where 2 is the number of spaces/indent for each level.
You can use ES6:
console.log(`hello
world`)
will produce:
hello
world
I think its originally creating a line break, but due to the object, it's not showing directly. Try to assign it in variable and access that in the console.
Code:
var v = {val:"test\ntest"};
console.log(v.val);
Output:
test
test
I am getting issues to convert unicode and render in a nice HTML code.
Here is the information i have as an input in my Json file
`"CLIENT:\r\n-Client1: Project1\u00c2\u00a0\r\n- Client2: etc..."`
I would like this to render as below in
CLIENT:
- client1: Project 1
- Client2: etc...
It currently renders like this :
`CLIENT: - Client1: Project1Â - Client2: etc...`
I looked everywhere but could not find a function that could handle all unicodes to decode in nice html code.
Thanks in advance!
Maybe you can take a look at this:
How do I replace all line breaks in a string with tags?
You do this:
str = str.replace(/(?:\r\n|\r|\n)/g, '<br />');
before insert into the html.
If you are using javascript, you can use this fragment
<script>
var c = decodeURIComponent(escape(`"CLIENT:\r\n-Client1: Project1\u00c2\u00a0\r\n- Client2: etc..."`));
c = c.replace(/(?:\r\n|\r|\n)/g, '');
c = c.replace(':-', ': - ');
document.write(c);
</script>
Ok I managed to make this work with the below function:
function strFormat(str) {
var c= decodeURIComponent(escape(str));
c= c.replace(/(?:\r\n|\r|\n)/g, '<br />');
c= c.replace(':-', ': - ');
return c;
}
Let me know if there are any cleaner way to do this?
I have a page with the following html that appears numerous times with different phone numbers:
<div class="crm-content crm-contact_phone primary">
<span>5555551212</span>
</div>
The phone number itself is displayed using a smarty variable in the form {$phone.i.phone}, where i is the array key in an array of phone numbers.
I want to be able to change the format of these phone numbers using js.
So for just one phone number, I was using the following in my smarty .tpl file:
{literal}
cj(function($){
var phoneNumber = {/literal}{$phone.1.phone}{literal};
var phoneNumberFormatted = '(' + phoneNumber.substr(0,3) + ') ' + phoneNumber.substr(3,3) + '-' + phoneNumber.substr(6);
$(".crm-contact_phone span").text(phoneNumberFormatted);
});
{/literal}
So I figure, I need to do something along the lines of:
$('.crm-contact_phone span').each(function(i, obj) {
var phoneNumber = '' + {/literal}{$phone.1.phone}{literal};
}
but I have no idea how to replace the 1 inside the smarty variable, with the javascript index i.
Any ideas? Thanks.
Try this
$('.crm-contact_phone span').each(function(i, obj) {
var phoneNumber = '' + {/literal}{$phone[i].phone}{literal};
}
Use the bracket Notation and replace it with i .
I took a different approach in the end, saving the entire smarty array to a js array using the following:
var phoneNumbers = {/literal}{$phone|#json_encode}{literal};
I could then just access the phone number by using pure js:
var phoneNumber = phoneNumbers[i]['phone'];
Can anyone shed any light as to why my JSON is coming out below, with the extra backslashes. I am using ASP.net MVC to serialise a datatable, when I debug in Visual studio it all looks ok but when I look with firebug with adds the extra characters?
Any ideas anyone?
JSON
[{\"uid\":\"516219026\",\"pic\":\"http://profile.ak.net/\",\"first_name\":\"Daniel\",\"last_name\":\"James\",\"fql_query_response_Id\":0,\"LIFEID\":null}
JAVASCRIPT
function GetFBFriends() {
FB.Connect.requireSession(function() {
$.ajax({
url: "/Facebook/GetFaceBookFriends",
type: 'POST',
data: null,
dataType: 'json',
success: function(result) {
data = "<table>";
alert(result.length);
for (i = 0; i < result.length; i++) {
data += "<tr><td><td><img src=" + result[i].pic + " alt=" + result[i].first_name + " /></td><input type='checkbox' value='" + result[i].uid + "' name='friends[]' id = 'friend" + result[i].uid + "' /></td><td>" + result[i].first_name + " " + result[i].last_name + "</td></tr>";
}
data += "</table>";;
}
});
})
};
Public Function GetFaceBookFriends() As JsonResult
Dim fbFriends As New DataTable
Try
fbFriends = FacebookModel.GetFriendsAndMatchToLife()
Return Json(JsonConvert.SerializeObject(fbFriends))
Catch ex As Exception
Finally
fbFriends.Dispose()
fbFriends = Nothing
End Try
End Function
That's Firebug showing the string containing JSON in it's string representation. Think of it as JSON-encoding a string containing JSON. Or rather, if your were to put the JSON in a string literal in your Javascript, it would look like that.
Your string does not actually contain those backslashes. They are just escapes for the double-quotes.
Looks like Firebug is adding escape characters. What if you enclosed your entire JSON in single quotes? That may correct the problem. Edit Can you provide the code that encodes your JSON?
I solved this question, I was returning JSON data which was then being changed into JSON by jquery as well, so I simply returned a string and jquery handled it correctly.
I would suggest doing injecting the following into the first line for the success function.
console.dir({'result':result});
This will show you what you are getting back, as opposed to just viewing the result from the network call.
The Firebug display is simply escaping the string, so you can copy/paste the entire result into the console for inspection/interrogation directly...
var temp = {pasted-string-here}
//var temp = "[{\"uid\":\"516219026\",\"pic\":\"http://profile.ak.net/\", ... }]"
var val = JSON.parse(temp);
console.debug({"val":val});