Ajax response and Jquery parse.JSON error - javascript

I'm consuming a Rest API. Post call for a login. Got a 200 and a lot of things said API returns. I want to console.log that data (just to confirm things, and see what info I will want to preserve). So I tried:
$.ajax({
url: 'http://www.mensagemassinada.com.br/QSWebAPI/API/Login',
type: 'POST',
data: JSON.stringify(tudo),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
complete: function(data) {
var cap = data.responseJSON
console.log(cap);
console.log(data);
},
});
event.preventDefault();
})
I can get the info I want (in data.responseJSON). In the plain "data" console.log I get all other info from the server. I want to acess individual itens inside said responseJSON (in the log I can see that responseJSON is a array). How can I acess individual values inside this array? I believe I would use parseJson, but got a error, regarding JSON structure. This is the array content printscreen (with private data edited):
From what I could find the Json format should be different. But I just want to confirm if the error is my fault, or if I need to ask for some modifications from the back end guy.
thanks in advance.

You can access the data by targeting the array with the id 0
console.log(cap[0].Empr_Nome);

Related

Using ajax to pass pass values to controller from view in MVC

I have the following in my Razor view file:
<button onClick="getFavouriteBooks()">Display Favourites</button>
<script>
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '#Url.Action("Favourites", "Home")',
data: ids,
dataType: "javascript"
});
}
</script>
And in my Home Controller, this action:
public async Task<ViewResult> Favourites(string[] ids)
{
// var bookList = code that retrieves list of all books
var favouriteBooks = bookList.Any(book => ids.Contains(book.Id));
return View("Index", favouriteBooks);
}
When user clicks 'Display Favourites' I get a 500 error for localhost/Home/Favourites. Can anyone help me see where I've gone wrong here?
Update: bookIds is an array of string Ids.
Update data with added contentType in ajax call as below and check again
function getFavouriteBooks() {
var ids = JSON.parse(localStorage.getItem("bookIds"));
$.ajax({
type: "POST",
url: '#Url.Action("Favourites", "Home")',
// jQuery refers below mentioned contentType to serialize data in JSON format
// Without this, serialization will be url encoded string
contentType: "application/json; charset=utf-8",
// Assuming ids as a array of strings
// data to be an object that holds Action methods parameters as it's properties
// Stringify object before assigning to data
data: JSON.stringify({
ids: ids
}),
dataType: "javascript"
});
}
So I think there is a couple of things going on here.
I am assuming it’s a “get” request not a “post” request. Since you want to display the books. If you want to “get” all that match an id the easiest way would be to get the total response and loop through it. If it is just for a small project if it’s serious you want to want to change your SQL to find where ID.
But assuming you just want assistance with the JavaScript.
First of all if you put your javascript in line like that you need to also handle the response in line which isn't going to be syntactically very friendly. After all we are not writing php.
The second point about async functions is that you need a response which will happen asynchronously so need to await. Also need to handle the promise
I have simplified what I think is the solution here to use fetch instead of ajax to avoid all the jquery and Ajax setup with code pen but the logic should be there for you to follow up.
https://codepen.io/sijbc/pen/qBRrgBG?editors=1111
fetch('https://api.github.com/users')
.then(res => res.json())//response type
.then(data => console.log(data))
Also found this article which would be worth checking out
https://medium.com/front-end-weekly/ajax-async-callback-promise-e98f8074ebd7

Extract object from JS script loaded with synchronous jQuery ajax call

I am trying to get use an object from a script loaded synchronously using Ajax via jQuery.
From this script I am trying to load an object which looks like this from a script called map_dropdowns.js which returns the object options:
{curr_cat: "RELATIONSHIP"
curr_subcat: " Population in households"
curr_total: "Total"}
My code for the script with the ajax is here:
<script>
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "script",
async: false,
success: function(data){
console.log(data);
}
});
console.log(options); //returns `Object{}` in the console, and only shows values when expanded
options["curr_cat"]; //returns undefined
console.log(Object.keys(options)); //returns an empty array []
</script>
In the original script, the keys and values within options can be accessed perfectly fine. console.log in Chrome shows its contents fully without needing to be expanded (Object {curr_cat: "RELATIONSHIP", curr_subcat: " Population in households", curr_total: "Total"}), and Object.keys() works just fine.
After it is loaded onto the page with the Ajax function, however, trying to access the values using the keys comes up undefined, Object.keys turns up an empty array [], and the key:value pairs are only shown in the console when I click on the object, with it otherwise showing only Object {}.
I am pretty sure that I need to do something in the success function of the Ajax, but I am not sure what after a lot of trial and error.
Thanks!
Loading JS code via AJAX is always a little hit and miss. It's usually a much better idea to load the data either as HTML, XML or JSON, and then deal with it as required once the AJAX request completes.
In your case, as you're attempting to load an object, JSON would be the most appropriate. If you change your map_dropdowns.js file to return data in this format:
'{"curr_cat":"RELATIONSHIP","curr_subcat":"Population in households","curr_total":"Total"}'
You can then make your async request to get this information from this file:
$.ajax({
type: "GET",
url: "../scripts/map_dropdowns.js",
dataType: "json",
success: function(data){
console.log(data.curr_cat); // = 'RELATIONSHIP'
console.log(data.curr_subcat); // = 'Population in households'
console.log(data.curr_total); // = 'Total'
}
});

Posting JSON string to PHP page

Okay, I'm having some suicidal issues posting a JSON string to a PHP page. I have literally been through the top ten results on Google and plenty of SO questions related to my problem, but still can't work out what I'm doing wrong.
I have multiple forms on a page and want to collect all form fields, turn them into a JSON string and post them to a PHP page, where a script iterates each item and updates the relevant database tables.
This is my jQuery/JS script to collect the data from all the forms:
var photo_annotations = {};
$('form').each(function(i) {
var id = $(this).attr('id');
photo_annotations[id] = {
caption: $('#'+id+'_caption').val(),
keywords: $('#'+id+'_keywords').val(),
credit: $('#'+id+'_credit').val(),
credit_url: $('#'+id+'_credit_url').val()
};
});
If I console.log my photo_annotations object, this is what is produced, based on a two form example:
({11:{caption:"Caption for first photo.", keywords:"Keyword1,
Keyword2, Keyword3", credit:"Joe Bloggs",
credit_url:"www.a-domain.com"}, 12:{caption:"Caption for Lady Gaga.",
keywords:"Keyword3, Keyword4", credit:"John Doe",
credit_url:"www.another-domain.com"}})
I then need to POST this as a string/JSON to a PHP page, so I've done this:
$.ajax({
type: 'POST',
dataType: 'html',
url: 'ajax/save-annotations.php',
data: { data: JSON.stringify(photo_annotations) },
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data) {
$('#form_results').html(data);
} else {
alert("No data");
}
}
});
And on my PHP page, I've got this:
<?php
//print_r($_POST['data']);
$decoded = json_decode($_POST['data'],true);
print_r($decoded);
?>
Now, this isn't the only thing I've tried. I've tried to remove all the JSON settings from the AJAX script, in a bid to just send a pure string. I've tried removing contentType and JSON.stringify but still won't go. My PHP page just can't get the data that I'm sending.
Please help push me in the right direction. I've got to the point where I can't remember all the variations I've tried and this little script is now on day 2!
MANAGED TO FIX IT
I rewrote my AJAX function and it worked. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
Try:
$.ajax({
// ...
data: { data: JSON.stringify(photo_annotations) },
// ...
});
If you just set the "data" property to a string, then jQuery thinks you want to use it as the actual query string, and that clearly won't work when it's a blob of JSON. When you pass jQuery an object, as above, then it'll do the appropriate URL-encoding of the property names and values (your JSON blob) and create the query string for you. You should get a single "data" parameter at the server, and it's value will be the JSON string.
Try urldecode or rawurldecode as follows:
<?php
$decoded = json_decode(urldecode($_POST['data']), true);
print_r($decoded);
?>
I rewrote my AJAX function and it now works. I have no idea what was going wrong but decided to test my AJAX function with a very basic data string test=hello world and found that no POST data could be read from the PHP page, even though Firebug says that the page did in fact receive post data matching what I sent. Very strange. Anyway, this is the revised AJAX script:
var the_obj = JSON.stringify(photo_annotations);
var post_data = "annotations="+the_obj;
$.ajax({
url: 'ajax/save-annotations',
type: 'POST',
data: post_data,
dataType: 'html',
success: function(data) {
$('#form_results').html(data);
}
});
The only thing I can think of is that the order of AJAX settings needed to be in a particular order. This is my old AJAX script which does not send POST data successfully - well it does send, but cannot be read!!
var the_obj = JSON.stringify(photo_annotations);
var data_str = "annotations="+the_obj;
$.ajax({
type: 'POST',
dataType: 'html',
data: data_str,
url: 'ajax/save-annotations.php',
success: function(data) {
$('#form_results').html(data);
}
});
in your ajax call try resetting the dataType to json
dataType: "json",
You wouldn't have to use the JSON.stringify() either. On your php script you won't have to decode [json_decode()] the data from the $_POST variable. The data will be easy readable by your php script.

As create json file with data in JavaScript, and send that file for JSONP other domain

I need your help with a big doubt.
Question: As I can create JSON file (with data) from JS code?
The reason is which I need use JSONP, and I wanna take that data from other domain (i.e. http://www.example.com/data/clients.json?callback=?), but this data are storage in a DB (WebSQL) and I need which that data is written in the json file (i.e. clients.json)
Please I need your help because three days ago I try do this, but I don't find yet the answer.
P.S.: Sorry for my english, not is my native language.
EDIT
Sorry my question is confused. I try again but for steps.
I need to write a JSON file with data or records from a DB (WebSQL). Actually my functions are working well (add record, update record, delete), but I need to put that data in a json file because, I'll use the next code for get the data from other domain.
(function($) {
var url = 'http://www.example.com/scripts/clients.json?callback=?';
$.ajax({
type: 'GET',
url: url,
async: false,
jsonpCallback: 'jsonCallback',
contentType: "application/json",
dataType: 'jsonp',
success: function(json) {
console.dir(json.sites);
},
error: function(e) {
console.log(e.message);
}
});
})(jQuery);

jQuery.post is not sending data to the specified URL

I have a mobile application and I have a lot of data that I am putting in to a JSON object to store in localStorage. I need to get this data to PHP to process it. I have chosen to use jQuery.ajax to send the data as a JSON object to PHP. However, when I run the function, it gives a success message, but does not go to the url specified. I have a lot of PHP experience but this is my first JS intensive project.
Here is my JS code:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
ATRdataJSON is a JSON object that has several JSON objects nested inside.
The URL may not be pointing where you think it's pointing. Try:
function sendToPHP() {
jQuery.ajax({
type: "POST",
url: "/email.php",
data: { "json" : ATRdataJSON},
success: function(data){
console.log("Data Sent!");
},
});
};
i'm afraid you cannot send the json object without stringifying it, it may be sent but as a string [object] try to check it first then you may make sure of the url is absolute to make sure it goes to the right controller.

Categories