I'm not getting response from my jsonp - javascript

i have this test json url
This is the link
jQuery.support.cors = true;
window.Getdata = function() {
var request = $.ajax({
type: "POST",
data: "{}",
dataType: 'json',
url: "/gh/gist/response.json/4001105/",
mimeType: "application/json; cherset=utf-8",
success: krywaarde,
failure: givealert
});
function krywaarde(result) {
alert("Name = "+result.fighters[0].name);
alert("Nickname = "+result.fighters[0].nickname);
// this changes the text
document.getElementById("routing").innerHTML = result.fighters[0].name;
}
function givealert(error) {
alert('failed!!' + error);
}
}
$(document).ready(function() {
window.Getdata();
});
​
i have edited my whole questions code
the problem i have now is, it works on JSFiddle, but not in my mobile app.
the onlu changes between the 2 is, the ons on Js Fiddle is called on page load, and my real mobile app the function is called on buttonclick!
here is the jsfiddle :
little jsfiddle
the html where i am calling the function is
<a type=button id="processnames" onclick="window.Getdata();" style="color: White; font-size:large;">test json

This line:
kryrequest(https://raw.github.com/appcelerator/Documentation-Examples/master/HTTPClient/data/json.txt?callback=awe)
… looks like it is trying to pass a string literal to the function. String literals must be surrounded by quote marks.
(this section refers to an earlier version of the question)
Additionally, that URI returns a JSON text, not a JSONP script, so it still won't work if you do fix that.
What's more, even if that response did contain JSON-P, it will wouldn't work because the object has a fighters property, but not a name property. The value of fighters is an array (of objects which have names), but those names are strings, not arrays.
(this section refers to an earlier version of the question)

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

jquery ajax call is forcing XML element names in the response to lowercase

I have the following code:
var frm = $('#login');
frm.submit(function (ev) {
var postData = $(this).serializeArray();
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
datatype: "xml",
data: postData,
success: function (data, textStatus, jqXHR) {
var saml = $("saml2\\:Assertion", (new XMLSerializer()).serializeToString(data));
var $assertion = $('<div/>').text(saml[0].outerHTML);
$('<pre/>').appendTo('#body').text(vkbeautify.xml($assertion.text()));
},
error: function (jqXHR, textStatus, errorThrown) {
alert('login failed - '.concat(jqXHR.responseText));
}
});
The service I'm invoking is returning an XML document with element names in CamelCase. The document begins:
<ns3:RequestSecurityTokenResponse xmlns:ns1="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd" xmlns:ns10="http://www.w3.org/2000/09/xmldsig#" xmlns:ns2="http://www.w3.org/2005/08/addressing" xmlns:ns3="http://docs.oasis-open.org/ws-sx/ws-trust/200512/" xmlns:ns4="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd" xmlns:ns5="http://docs.oasis-open.org/ws-sx/ws-trust/200802" xmlns:ns6="http://schemas.xmlsoap.org/ws/2004/08/addressing" xmlns:ns7="http://schemas.xmlsoap.org/ws/2004/09/policy" xmlns:ns8="http://schemas.xmlsoap.org/ws/2005/02/sc" xmlns:ns9="http://schemas.xmlsoap.org/ws/2006/02/addressingidentity">
<ns3:RequestedSecurityToken>
The problem I'm having is that when I inspect the returned data object in the debugger (with a breakpoint before the line beginning 'var saml' is executed, I can see that the element names are all lowercase, e.g. the top-level element is now ns3:requestsecuritytokenresponse.
I can see that the message on the wire is uppercase.
Any ideas how to prevent Ajax from forcing the element names to lowercase?
Thanks.
I think the problem might be that JQuery interprets the data as HTML instead of XML. Since you're not setting the dataType attribute correctly, it will, according to the documentation, try to make an intelligent guess.
Try changing to:
dataType: "xml"
^
After that, if you're still seeing the same behavior, it might be just your debugger that's not displaying things correctly. Try displaying the serialized XML with an alert() call and check whether the problem persists.
Note, that in the line where you create the saml variable, you're forcing everything to HTML, so I would expect element names to be lower-cased after that line, but not before.

Jquery response load

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);

jQuery AJAX and JSON Performance Query

I am storing some JSON data in a text file to query using jQuery Ajax in my page. Currently, my text file contains around 10 facets of data (which could contain an additional 30 facets of data). The JSON data contains a questions and answers to those questions.
In my JavaScript files, I have setup different functions to get specific bits of data.
For example:
function GetAnswer(questionName) {
var correctAnswer = null;
jQuery.ajax({
type: "GET",
url: "../content/questions.txt",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
async: false,
success: function (result) {
$.each(result, function (i, q) {
if (q.questionID == questionName) {
correctAnswer = q.correctAnswer;
return false;
}
});
},
error: function () { },
complete: function () { }
});
return correctAnswer ;
}
As you can see from my code-snippet, I am looping through my JSON to get the data I need. I have other functions coded in a similar fashion to get the question type, question name etc.
What I am finding is that I am calling these functions one after another to get the data I need. I think the way I am querying my JSON data is not good from a performance point-of-view since I am looping through the whole of my JSON dataset until I find a match.
Is there a better way to query my JSON data?
NOTE: I am having to use a text file to store questions due to restrictions of the technology I am using (SCORM 1.2).
Looping through your JSON object is relatively quick. What is slow (comparatively) is loading in that text file each time (though it may be cached).
Either way, I would suggest loading in the JSON either the first time the user initiates a question/answer situation, or just load it in on page load (you can do it asynchronously) and store it for later use.
Example of the latter:
jQuery(document).ready(function(){
var questions = '';
jQuery.ajax({
type: "GET",
url: "../content/questions.txt",
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "",
async: false,
success: function (result) {
questions = result;
},
error: function () { },
complete: function () { }
});
function GetAnswer(questionName) {
var correctAnswer = null;
$.each(questions, function (i, q) {
if (q.questionID == questionName) {
correctAnswer = q.correctAnswer;
return false;
}
});
return correctAnswer ;
}
});
The problem is that you have async set to false. This is bad. This halts the browser while it waits for your requests, and will cause the performance to feel very laggy.
Why not change the structure of your Q&A object to include an id for each question, and make the id an attribute in the object? Then you could pass the id to GetAnswer() and just have it go directly to the right question by referencing the correct attribute? The object could look like this:
{"myQuiz" :
"Q1" :
{ "q" : "What color was George Washington's white horse?",
"a" : "White"
},
"Q2" :
{ "q" : "In what city would you find the Leaning Tower of Pisa?",
"a" : "Pisa"
}
}
If this is assigned to result, and an id of Q2 was passed to GetAnswer(id), you could easily return result.myQuiz[id].a;
As an alternative, if the order of the questions is consistent, you could use an object that contains an array of q and a pairs, and refer to them by index rather than id.
Why not move the logic to a server-side script like PHP that can take in POST parameters and perform the queries against the JSON set and return only the record(s) you wish to receive. Or, if you are intent on keeping this in all js, you could simply store the JSON (as long as it is non-sensitive data) in a local variable and query against it locally.
You could make somekind of mechanism on the server to load data. Then you could send parameters like QuestionName and filter data. This will lower payload sent on the wire.

Problems with variable scope (JavaScript)

I have the following JavaScript (I'm using jQuery):
function language(language)
{
var text = new Object();
$.ajax({
type: "GET",
url: "includes/xml/languages/" + language + ".xml",
dataType: "xml",
success: function(xml){
$(xml).find('text').each(function(){
text[$(this).attr('id')] = $(this).text();
});
}
});
return true;
}
I have an XML file which is then being read by the class. The XML file has declarations like this:
<text id="must_be_string">Must be a string.</text>
<text id="must_be_number">Must be a number.</text>
<text id="must_be_integer">Must be an integer.</text>
The XML file is being read correctly, but the problem I'm having is that the text variables don't seem to be working properly.
From putting some alert stop-points in to try to debug, I've discovered that this is what's happening:
Inside success: function(xml){, the var text can be properly accessed. However, the assignment inside that function to assign a new phrase to text doesn't add it correctly. Inside the success:, I can alert(text['must_be_string']) and get "Must be a string," but when I leave the Ajax call, it always shows "undefined."
In case I'm not being clear:
var text = new Object();
$.ajax({
type: "GET",
url: "includes/xml/languages/" + language + ".xml",
dataType: "xml",
success: function(xml){
alert(text); // Shows [object Object]
$(xml).find('text').each(function(){
text[$(this).attr('id')] = $(this).text();
});
alert(text['must_be_string']); // Shows "Must be a string."
}
});
alert(text['must_be_string']); // Shows undefined -- this is my problem
I would really, really appreciate any help on this. Please explain because I would really like to understand what's going on.
The success method of the ajax call is an asynchronous call. When you call $.ajax the method will instantly return and attempt to execute the alert(text['must_be_string']);, which won't be set until after the success of the ajax call is made, some point in the future.
Hope this helps.
Variable 'text' lives in the scope of the 'language' function.
I'm not sure how jQuery manages scopes, but I think the success function is a new function that is not inside 'language's scope.
'language' ends when reaching return and the ajax query is sent. However, the response comes afterwards (async).
Try declaring 'text' object as global, outside 'language'

Categories