I am receiving a JSON string from an ajax call and would like to convert a value to a predefined variable:
var predefined = "hello world";
var foo = {"msg":"predefined"}; // JSON string
I want to echo out the standard string accessing it with
alert(foo.msg)
EDIT: to make the answer more clear here is my call:
var success_msg = "Your email is send successfully!";
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status == "success") {
msg.text(data.msg).addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
})
ajax-share-email.php responds:
{"status":"success", "msg":"success_msg"}
var strings = {"predefined":"hello world"};
alert(strings[foo.msg]);
or e.g.
var messages = {};
messages.success_msg = "Your email is send successfully!";
// ...
msg.text(messages[data.msg]).addClass("email-msg-success");
How about this -- just use the message inline on success and don't even bother to make it part of the JSON. On an error, do include the entire message and use it directly. Also, I'd have your server return something like:
{ "status": true }
or
{ "status": false, "msg": "The mail server is down." }
Then you can just evaluate it as a boolean without comparing it to a string value.
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status) {
msg.text('Your email has been sent successfully!').addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
});
If, and only if, you start reusing your messages for multiple functions, then refactor to a message dictionary and reference it from there. Note your messages object would likely need to be a global variable, or at least in the outer scope of all the functions that use it.
var messages = {};
messages.mail_success = 'Your email has been sent successfully!';
messages.post_success = 'Your data has been updated!';
$.ajax({
url: "ajax-share-email.php",
type: "POST",
dataType: "json",
data: {},
success: function(data) {
if (data.status) {
msg.text(messages.mail_success).addClass("email-msg-success");
} else {
msg.text(data.msg).addClass("email-msg-error");
}
}
});
var predefined = "hello world";
var foo = {"msg":predefined}; // JSON string
alert(foo.msg)
?
IFF I understand what you are asking, I think I have all of the pieces here.
You have a variable predefined and you want to be able to return that in your json and have the resulting parsed object contain the value in predefined
JSON.parse will not work for you (at least not in Chrome), but eval will.
var predefined = "Hi! I'm predefined";
// ...
var json = '{"foo": predefined}'; // notice no quotes
var response = eval("(" + json + ")");
alert(response.foo);
var out = eval(foo.msg); // out is now "hello world"
Note: do not use eval() if you are not sure what the content of foo.msg is.
or
var out = foo.msg=="predefined" ? predefined : foo.msg;
Related
I'm executing an ajax call to a external api (this cannot be modified) to upload an store a file into a folder. This request must return a path (ex. "C:\Doctos\File.pdf" but after a console.log is returning something like this:
#document < string xmlns="http://tempuri.org/">"C:\Doctos\File.pdf"
So my question is, what can I do to get only the text that I want without any change in the api (because I'm not able to do it).
Here is the ajax call that I'm using.
PD. This ajax call is using the provided structure for the dev team that developed the api so things like dataType also cannot be modified
var data = new FormData();
var files = $('#fileUpload').get(0).files;
if (files.length > 0) {
data.append("UploadedFile", files[0]);
}
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
var res = data;
//Returns above example
console.log(res);
//Returns something like <p>[object XMLDocument]</p>
$('#MyInput').attr('src', res);
}
});
I would use regular expressions to get the desired string from received data. Put this after success line.
var regex = />\"(.*)\"/;
var matched = regex.exec(data);
var result = matched[1];
console.log(result);
The regex matches the last quoted string in your example.
You can get the data in the xml with jQuery
$.ajax({
type: 'POST',
url: 'api/v1/moreurl/UploadFile',
contentType: false,
processData: false,
data: data,
success: function (data) {
// Get the contents of the xml
var file = $(data).find('string').text();
$('#MyInput').attr('src', file);
}
});
I have the following controller:
public function getPrice()
{
$id = $this->input->post('q');
$data['price'] = $this->emodel->get_peUniformPrice($id);
echo json_encode($data);
}
which outputs this:
"{\"price\":[{\"Price\":\"250\"}]}"
How can I make it like 250? My jQuery:
function showPrice(size) {
$.ajax({
type: "POST",
url: "<?php echo site_url('enrollment/getPrice/');?>",
data: {
q: size
},
success: function(data) {
$("#txtpeUniform").val(data);
},
});
}
I can see that you are using jQuery.. if you want to turn the json object into a javascript object you could do something like
var convertedObject = $.parseJSON($data);
alert(convertedObject.Price);
what this effectively does is converts your Json string into a javascript object which you can reference the properties out of and the get the value from these properties.. let me give you another example
var jsonString = {'Firstname':'Thiren','Lastname':'Govender'};
var jObject = $.parseJSON(jsonString);
console.log(jObject.Firstname) // this will output Thiren.
console.log(jObject.Lastname) // this will output Govender.
modify your code
function showPrice(size) {
$.ajax({
type: "POST",
url: "<?php echo site_url('enrollment/getPrice/');?>",
data: {
q: size
},
success: function(data) {
console.log(data); // make sure this is returning something..
$("#txtpeUniform").val(data);
},
});
}
I hope this helps you..
Regards
The $.ajax method will automatically deserialise the string to an object for you, so you simply need to access the required property. Assuming that you only ever want to retrieve the first price returned in the price array, you can access it directly by index. Try this:
success: function(data) {
$("#txtpeUniform").val(data.price[0].Price); // = 250
},
HI how to post a form and return data it will be a array as like this
{
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
}
My code is this
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
var formValidate = $('#add-menu-list').parsley().validate();
validateFront();
// console.log(formValidate);
var menuName = $('input[data-api-attr=menuItemName]').val();
var validUntil = $('input[data-api-attr=validUntil]').val();
var menuStatus = $('input[data-api-attr=status]').val();
var menuNote = $('textarea[data-api-attr=notes]').val();
var menuDesc = $('textarea[data-api-attr=menuItemDesc]').val();
var dataString = {
menuItemName: menuName,
validUntil : validUntil,
status : menuStatus,
notes : menuNote,
menuItemDesc : menuDesc
};
if(formValidate == true){
alert('success');
console.log(menuName + validUntil + menuStatus + menuNote + menuDesc);
var url = "xyz.html"; // the script where you handle the form input.
$.ajax({
type: "POST",
// url: url,
dataType: "json",
data: $(dataString).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response
}
});
}else{
alert('Validation fail ');
}
});
Since "data" is a server response i guess that your server return a json object. In this case you have to somehow inform the jquery's ajax that you expect a json response from server or you have to translate the "data" to a json object by your self.
It is best to follow the first option so you don t have to deal with the translation your self you can easily do that by giving an extra parameter tou your ajax reuest : dataType: 'json', this will do the trick!
Now that you have a proper response object from your request you can either stringify it with var string_resp=JSON.stringify(data); and then alert it alert(string_resp) or you can access its elements like that : alert(data.status) which will alert your object's status field etc.
so your code will be :
$.ajax({
type: "POST",
url: url,
dataType: 'json',
data: $(menuName).serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // will alert an object
alert(data.status); // will alert object's status field in this case 1
alert(JSON.stringify(data)) // will alert the object as a string
}
});
you are sending only one value in serialize, serialize() should be on form element not on field element, like :
$('#add-menu-list .btn[data-attr=submit-btn]').on('click', function(){
...
$.ajax({
...
data:$("#form").serialize();
...
success: function(data)
{
alert(data.notes); // show response
....
}
var myObj = {
"notes":'some notes',
"validUntil": '12/12/2015',
"status": 1,
"menuItemName": "HR Section",
"menuItemDesc": "gggg"
};
myObj.toString = function()
{
var str = '';
for (var property in myObj)
{
if (myObj.hasOwnProperty(property) && (property != "toString") )
{
str += (property + ': ' + myObj[property] + "\n");
// do stuff
}
}
return str;
}
alert(myObj);
I've been stuck at this error for a few days and still couldn't figure out what is wrong. Would be great if someone could just point me to the right direction of solving this issue.
Update:
I realise that error is gone when I commented "addMessages(xml)" in the updateMsg() function. How do I make it work then?
Error:
http://i.imgur.com/91HGTpl.png
Code:
$(document).ready(function () {
var msg = $("#msg");
var log = $("#log");
var timestamp = 0;
$("#name").focus();
$("#login").click(function() {
var name = $("#name").val();
if (!name) {
alert("Please enter a name!");
return false;
}
var username = new RegExp('^[0-9a-zA-Z]+$');
if (!username.test(name)){
alert("Invalid user name! \n Please do not use the following characters \n `~!##$^&*()=|{}':;',\\[\\].<>/?~##");
return false;
}
$.ajax({
url: 'login.php',
type: 'POST',
dataType: 'json',
data: {name: name},
success: function() {
$(".login").hide();
}
})
return false;
});
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()},
})
msg.val("");
return false
});
window.setInterval(function () {
updateMsg();
}, 300);
function updateMsg() {
$.post('server.php', {datasize: '1024'}, function(xml) {
addMessages(xml);
});
}
function addMessages(xml) {
var json = eval('('+xml+')');
$.each(json, function(i, v) {
tt = parseInt(v.time);
if (tt > timestamp) {
console.log(v.message);
appendLog($("<div/>").text('[' + v.username + ']' + v.message));
timestamp = tt
}
});
}
function appendLog(msg) {
var d = log[0]
var doScroll = d.scrollTop == d.scrollHeight - d.clientHeight;
msg.appendTo(log)
if (doScroll) {
d.scrollTop = d.scrollHeight - d.clientHeight;
}
}
});
It might help to read up on eval a bit. It looks like it doesn't do what you think it does.
eval() is a dangerous function, which executes the code it's passed with the privileges of the caller.
Also
There are safer (and faster!) alternatives to eval() for common use-cases.
It looks like what you're trying to do is get data from the server in the form of JSON. You'll need to make sure that your server returns something that is valid JSON, which you can verify here. Most server-side programming languages have a library that will turn an object into JSON to make that a piece of cake. Here's an example for php.
On the client-side, you'll need to change var json = eval('(' + xml + ')'); to var json = JSON.parse(xml); This will give you the javascript version of your php/perl/python/etc object. If it's an array, you can then iterate through it with a for loop, Array.prototype.forEach, or a variety of functions from different libraries, such as $.each or _.each.
SyntaxError: expected expression, got ')' usually cause by something like
exeFunction(a,b,)
See if your form submit function ajax causing such error
$("#form").submit(function() {
if (!msg.val()) {
return false;
}
$.ajax({
url: 'add_message.php',
type: 'POST',
dataType: 'json',
data: {message: msg.val()}, <-------
})
msg.val("");
return false
});
If you are triggering the java script on click or trigger any click. sometimes missing of 0 gives the above error.
delete
would JSON.stringify({datasize: '1024'}) do the trick? just a guess
Hello Fellow Developers,
I have a SSN textbox that onblur calls a function which does an ajax request to a Web Method to decide if an employee has been previously hired.
The Web Method returns a TermedEmployee Object to the success callback, but I'm unsure how to parse the object.
$('#<%=FormView1.FindControl("SSNField").ClientID%>').blur(hideValue);
hideValue = function (ev) {
var $this = $(this);
$this.data('value', $this.val());
$('#<%=FormView1.FindControl("hiddenSSN").ClientID%>').val($this.val());
var data2Send = '{"SSN": ' + $this.val() + ' }';
$.ajax({
type: "POST",
url: "AuthforHire.aspx/EmployeeisRehire",
data: data2Send,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result) {
var obj = JSON.stringify(result.d);
if (obj.IsTermed) {
$('#%=RadWindowRehire.ContentContainer.FindControl("TextBoxTermID").ClientID%>').val(arg.d);
var wndWidth = 900;
var wndHeight = 500;
var wnd = window.radopen(null, "RadWindowRehire");
}
},
error: function (xhr) {
alert('Form update failed. '); //error occurred
}
});
Below is a minified version of my webMethod, which works correctly
[System.Web.Services.WebMethod]
public static TermedEmployee EmployeeisRehire(string SSN)
{
TermedEmployee termedEmp = new TermedEmployee();
// Db call to get necessary data.
termedEmp.Name = dr["name"];
termedEmp.TermDate = Convert.ToDateTime(dr["TermDate"].ToString());
......
}
So How Can I extract Name, TermDate,StartDate, ReasonforTerm, etc from the object returned to the callback function?
Thank you in advance!
The first line in your success callback is:
var obj = JSON.stringify(result.d);
Which is trying to serialize what ASP.Net will already have serialized for you.
Change this to:
var obj = result.d;
And you will then have access to obj.Name, obj.TermDate and all the other properties by name.