I have a serialized string comming from the controller to a view:
Controller:
var serialize = new JavaScriptSerializer();
return Json(new
{
data = serialize.Serialize(obj)
}, JsonRequestBehavior.AllowGet);
Json string:
[{"indiceName":"Caracter","indiciId":24,"indiceId":1,"tamanhoIndice":10,"mask":null,"indiceObr":1},
{"indiceName":"Numérico","indiciId":25,"indiceId":2,"tamanhoIndice":10,"mask":null,"indiceObr":0},
{"indiceName":"AlfaNumérico","indiciId":26,"indiceId":3,"tamanhoIndice":10,"mask":null,"indiceObr":0}]
As far as I know, modern browser should be able to parse that string with a simple
Json.parse()
View:
success: function (data)
{
$('.dinamic').remove();
console.log(data);
var obj2 = JSON.parse(data);
console.log(obj2);
}
I am able to see that string in the first console.log, but I get nothing from the second.
Is there any thing else I should be looking at because all the post I have read people only do it as simple as it is with a single JSON.parse.
I am using latest version of google chrome ,firefox and IE so it should work.
Although your success function is not shown in context of the other AJAX options being given, I would guess you are passing a dataType option of "json", or are using $.getJSON or something similar.
If that is the case, jQuery has already parsed the JSON for you by the time it passes it into success so you do not need to (and cannot) parse it again. You can simply use your data structure (data[0]. indiceName and etc).
(The below code is running live at http://jaaulde.com/test_bed/GuilhermeLongo/ )
Consider the following PHP (stored in json.php):
<?php
exit('[{"indiceName":"Caracter","indiciId":24,"indiceId":1,"tamanhoIndice":10,"mask":null,"indiceObr":1},{"indiceName":"Numérico","indiciId":25,"indiceId":2,"tamanhoIndice":10,"mask":null,"indiceObr":0},{"indiceName":"AlfaNumérico","indiciId":26,"indiceId":3,"tamanhoIndice":10,"mask":null,"indiceObr":0}]');
And the following JS:
<script src="http://code.jquery.com/jquery.min.js"></script>
<script>
$.ajax({
url: 'json.php',
type: 'get',
dataType: 'json',
success: function (data) {
console.log(data[0]);
console.log(data[0].indiceName);
},
error: function () {
throw new Error('AJAX request error occurred.');
}
});
</script>
It results in the following outputted log info:
GET http://jaaulde.com/test_bed/GuilhermeLongo/json.php
200 OK
99ms
jquery.min.js (line 3)
Object
{indiceName="Caracter", indiciId=24, indiceId=1, more...}/test_...eLongo/
(line 8)
Caracter
Related
Ajax request is executing, but it returns not curent_day variable but null.
Js:
$.ajax({
url: 'planing/next-day',
data: {new_curent_day: $('.owl-item.center .slide_day').text()},
dataType: 'json',
type: 'POST',
success: function(curent_day) {
alert(curent_day);
},
error: function(xhr, status, error) {
alert(xhr.responseText + '|\n' + status + '|\n' +error);
}
});
Controller:
public function actionNextDay() {
if (Yii::$app->request->isAjax){
$this->planing_model->curent_day = Yii::$app->request->post('new_curent_day');
return Json::encode($this->planing_model->curent_day);
}
}
May be the problem is your are sending the POST data as JSON so your not able get it through
Yii::$app->request->post('new_curent_day');
Try this they have updated JSON parser set and to get the JSON value through yii.
Error in accessing post json data in yii2
Use the Javascript console and debugger in your browser to see what $('.owl-item.center .slide_day') contains. Make your API endpoint log what it gets in the post variables.
The typos in variable names make me worry that you might refer to the wrong thing. planing has two n's, curent has two r's. This code looks consistent at least but if I came across this code I would suspect current and curent got mixed up.
I've searched around for this error and none of the solutions appear to help me with what I am getting. I am doing an ajax request, and I am trying to retrieve the json output released by the server. I can print out the json that i am trying to capture (via console.log()) not process it in the jQuery.parsejson(). I keep getting a "Uncaught SyntaxError: Unexpected token o" error. Please can someone advise?
my code:
// Make ajax request
$.ajax({
url: 'http://localhost/multipleFileUpload_adam/webservice/delete_pdf.php',
data: {delete_array: jsonString},
dataType: 'json',
type: 'POST',
success: function(data){
console.log(data);
var x = jQuery.parseJSON(data);
},
console.log(data) gives the following ( am trying to retrieve the 'success_deleted' array:
Object {success_delete: Array[2], unsuccess_delete: Array[0], input array: Object}
if I remove the line of code :
var x = jQuery.parseJSON(data);
Then I am able to get the console.log(data) to work. if i add it i get the error mentioned above.
This line:
dataType: 'json',
tells jQuery to ignore the content-type returned by the server and always parse the response as if it was JSON.
Then:
success: function(data){
The JavaScript value (which is an object) that you get from parsing the JSON is passed into data.
This line:
jQuery.parseJSON(data);
Takes the value of data (an object)
Converts it into a string (which will be "[object Object]")
Tries to parse that string as JSON (which it isn't).
Then I am able to get the console.log(data) to work. if i add it i get the error mentioned above.
Yes. That is the expected behaviour. Don't do that. Just work with the already parsed data in data.
there is a parse error because data is already an object so it is expecting json and getting Object. 'O' is the unexpected character. Try without the parseJSON function.
I'm making a jQuery AJAX call to my Rails app (all run on localhost) which is responding with Javascript. The javascript is running because I'm getting the alert. But, I would like to read the my_var variable in the js.erb file. However, when I try to look at the data parameter of the success function it sees the data as a string. So doing data.my_var is undefined.
js.erb file
var my_var = "hi";
alert('this ran');
javascript
$.ajax({
url: "/a/validate?a_id=" + "<%= params[:id] %>",
context: this,
dataType: "script",
data:
{
json_a: JSON.stringify(this.a),
model_to_validate: model,
target_class: target_class,
current_class: current_class
},
success: function (data, textStatus, jqXHR) {
if(!this.orderFormViewed) {
this.orderFormViewed = data.order_block_opened;
}
},
error: function (data) {
console.log("error in ajax validate call");
debugger;
}
})
That's because that's exactly what you told it to do with dataType: "script" - look at the dataType options below. The script is run in it's own context and so you won't see that variable (I believe). You're going to need to communicate differently if you want that set. Or if you just need data send json.
https://api.jquery.com/jQuery.ajax/
"script": Evaluates the response as JavaScript and returns it as plain text. Disables caching by appending a query string parameter, "_=[TIMESTAMP]", to the URL unless the cache option is set to true. Note: This will turn POSTs into GETs for remote-domain requests.
try to change your dataType to json if you only need to get an object and be sure your server return a json.
A jQuery function receives a string from a database using GET, after that I would like to inject that string into HTML in place of a div. Pretty standard stuff so it seems.
However I am not quite managing it.
Here is what I have going on:
<h1>Whatever</h1>
<div id="replace_me">
</div>
<a id="click_me" href="#">Click Me</a>
<script>
//AJAX
var brand_id = 8
var dataX = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$(function(){
$("#click_me").click(function(){
$.ajax({
type: 'GET',
url: '/ajax_request/',
data: dataX,
datatype: "json",
success: function(data) {
alert(data);
$("#replace_me").load(data);
},
error: function() {
alert("Nope...");
}
});
});
});
</script>
When the alert is set off I receive my string which shows everything is working fine, but how can I input that string I just received into the div "replace_me" without having to load from another url?
You have an error in your success function. Check documentation on jQuery load(). Instead, you should do
success: function(data) {
//alert(data);
$("#replace_me").html(data);
},
or, slightly better style
success: function(data) {
//alert(data);
$("#replace_me").empty().append($(data));
},
Also note, that you specified "json" in your datatype option. As a consequence, if your server responds in proper JSON, your data will be a JavaScript object, as jQuery will parse the JSON format for you. If you really want to see the object, you will need to use, e.g. JSON.stringify():
$("#replace_me").empty().append($(JSON.stringify(data)));
If your server does not produce valid JSON, your success method will not be called in most cases.
load() is a convenience method to do the two steps of calling the ajax url, then putting the data into the element all in a single function. Instead of calling .ajax(), just call .load()
i.e.
var brand_id = 8
var data = {'brand': brand_id, 'csrfmiddlewaretoken': ""};
$("#replace_me").load('/ajax_request/', data);
Earlier today I posted another post where #Darin Dimitrov helped me great, however once again I'm stucked...
My javascript calls the AddWebsite ActionResult which does it job as it should, however the error function in the $.ajax() is always firing since
return PartialView(ListPartialView, MapUserToViewModel);
isn't valid JSON.
I've come across examples where people use something like
RenderPartialViewToString(partialview, model);
and throws it into a JSON object... but it's just too "hackish" if you ask me.. isn't there an easier way to accomplish this?
... And the code:
// DashboardController.cs
[HttpPost]
public ActionResult AddWebsite(CreateWebsiteViewModel website)
{
if (!ModelState.IsValid)
{
throw new HttpException(400, "Client-side validation failed.");
}
if (string.IsNullOrWhiteSpace(website.URL))
{
throw new ArgumentNullException("URL", "The URL cannot be empty nor contain only whitespaces.");
}
using (_session.BeginTransaction())
{
_session.Query(new AddWebsite(_contextProvider.GetUserSession.UserId, website.URL));
_session.Transaction.Commit();
}
return PartialView(ListPartialView, MapUserToViewModel);
}
// MyJs.js
$("#testform").live('submit', function () {
var test = { URL: $("#URL").val() };
$.ajax({
url: "/Dashboard/AddWebsite",
type: "POST",
data: JSON.stringify(test),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("TRIG");
$("#content").html(data);
},
error: function () {
alert("Error");
}
});
return false;
});
Thanks in advance!
In your particular instance I think the problem is with your javascript code. You are specifying the dataType (which is what the function expects to parse in the response) as json. Based on the Action you posted you should have html as the dataType and it should solve your problem. There's nothing wrong with doing that (you don't have to use JSON for everything).
Simple data
Why are you setting dataType and contentType in the first place? Since your object test is very simple you can just provide it as is and it will be consumed by Asp.net MVC without any problems and you will return your partial view.
Complex data
If your object would be more complex then you could use a different jQuery plugin that will make it possible to send complex JSON objects without strigification.