Javascript to jQuery Conversion for an xml ajax call - javascript

I have the following script
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", "/getSelectedProductData?offerCollectionRef=" + offerCollectionRef + "&brandRef=" + brandRef + "&priceRef=" + priceRef + "&defaultSmallImage=" + defaultSmallImage + "&offerCode=" + offerCode + "&index=" + index, false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
I know how to write a $.ajax in jQuery. But I am stuck at how to send data.
My questions are
The return is XML and so the dataType: xml. am I correct?
How should I pass the data to the url?
Please elaborate on these things.
Disclaimer: The thing is that I couldn't test it myself and so this question.

1 The return is XML and so the dataType: xml. am I correct?
You actually don;t need to specify it if the server sets proper Content-Type header to text/xml. jQuery will automatically consider the result as XML
2 How should I pass the data to the url?
You could use the data hash:
$.ajax({
url: '/getSelectedProductData',
type: 'GET',
dataType: 'xml', // not necessary if the server sets the Content-Type: text/xml response header
data: {
offerCollectionRef: offerCollectionRef,
brandRef: brandRef,
priceRef: priceRef,
defaultSmallImage: defaultSmallImage,
offerCode: offerCode,
index: index
},
success: function(xml) {
// ...
}
});
Also you seem to be sending a synchronous request by setting the async parameter to false. To emulate the same with jQuery you could add the async: false option. This being said, you probably shouldn't be doing it. SJAX (sync javascript) will block the browser during the request and ruin the user experience.

Yep.
You can use the data property when passing settings to $.ajax(). It can be an object (it will be converted to a query string) or a query string. Please check the jQuery Manual for further details.
Excerpt from the manual:
data (Object, String) Data to be sent to the server. It is
converted to a query string, if not already a string. It's appended to
the url for GET-requests. See processData option to prevent this
automatic processing. Object must be Key/Value pairs. If value is an
Array, jQuery serializes multiple values with same key based on the
value of the traditional setting (described below).
So from your example, url shall be '/getSelectedProductData', and data could be everything after ?. Or you can organize them into an object like { 'offerCollectionRef': offerCollectionRef, ... }, it is a bit more readable.

Related

Response data is not in valid format in Ajax

I have a text file with the character set as "Shift_JIS" and the file contains Japanese characters. And then I do ajax request to that file as shown below.
$.ajax({
url: "demo.txt",
success: function(result){
alert(result);
}}
);
But the data that is shown in alert is not valid Japanese character. Instead it shows some junk data. Even though I tried to set the response header character set and I do many of the solution that is already before in stackoverflow, But it didn't work. Can any one help me to solve this ?
Note: Browser is Internet Explorer
You said you tried to change the charset, have you tried changing the contentType to plain text ? :
$.ajax({
/*...*/
contentType: "text/plain; charset=Shift_JIS"
/*...*/
})
You cannot read a Shift_JIS file into a string object directly in JavaScript. You have to once store the content of the file into a binary object and then decode it into UTF-16 (the internal representation of JavaScript string) with TextDecoder.
Unfortunately, jQuery's $.ajax() cannot handle the response body as binary (dataType: 'binary') out of the box. So you have to use additional module like
jQuery BinaryTransport, or use XMLHttpRequest like this:
// ref. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data
var oReq = new XMLHttpRequest();
oReq.open("GET", "demo.txt", true);
oReq.responseType = "arraybuffer"; // handle response body as binary
oReq.onload = function (oEvent) {
if (oReq.response) {
var sjisDecoder = new TextDecoder('shift-jis');
alert(sjisDecoder.decode(oReq.response)) // Note: not oReq.responseText
}
};
oReq.send(null);

Cannot carry out Ajax request from wikipedia

I want to use wikipedia API in my project to grab images of people, but fail. I use this url:https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100
When i console browser says the following
Refused to execute script from 'https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albe…Callback&callback=jQuery22409288979864744966_1470068280411&_=1470068280412' because its MIME type ('text/html') is not executable, and strict MIME type checking is enabled.
My code
var general = {
// The URL to the quote API
url: 'http://api.forismatic.com/api/1.0/',
// What to display as the author name if s/he's unknown
unknownAuthor: 'Uknown',
// Base URL for the tweet links generation
tweetURL: 'http://twitter.com/home?status=',
wikiURL:'https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert Einstein&pithumbsize=100&callback=wikiCallback'
};
var wikirequest = function() {
$.ajax({
url:general.wikiURL,
dataType: 'jsonp',
success: function(wikData) {
console.log(wikData);
//var image = wikiData.
displayQuote(image);
} // end of success
});
}// wikirequest
wikirequest();
Pen
Has anyone met the same issue?
You are trying to load the data using JSONP, but you are making a request to a URL that returns an HTML document. JSONP requests have to be answered with JavaScript programs (since that is a fundamental feature of how they work … and also why they are dangerous and should be avoided in favour of plain JSON and CORS).
To make it return JSONP you need to provided two additional query string parameters:
format=json
callback=YourCallbackName
… where YourCallbackName is the name of the function that should be executed and passed the data you are fetching as an argument. Most Ajax libraries will generate that name (and the function itself) dynamically when you specify callback=?.
https://en.wikipedia.org/w/api.php?action=query&prop=pageimages&titles=Albert%20Einstein&pithumbsize=100&format=json
You are missing the &format=json on the URL - The page was displaying the data with the html header and you would have been attempting to decode this. The above answer is actually better.

JSON returned from ASP.NET not usable in JS

I'm returning a DataSet converted to JSON via a jQuery AJAX call, all is well! The request I receive back is:
{"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]}
Looks valid to me, also ran it through JSLint validator, again, all is well! Now, whenever I try to access any of this data, I simply receive undefined from the following:
var dataObject = data.d //data.d is the response from the server and what is logged above
console.log(dataObject.Table) //undefined
console.log(dataObject["Table"]) //undefined
Now, if I run JSON.parse(dataObject), I can then access it alright. This is a problem right now however, since the site this will reside on sticks IE into IE7 mode, and JSON is always undefined according to IE (I know, IE7, it's out of my hands tho).
So my question is why can I not use the returned JSON as is? why must I run it through JSON.parse before using it? More info is available on request (AJAX call, DataSet converter, etc)
AJAX Call, per request:
$.ajax({
type: "POST",
url: "DBManager.asmx/GetAdminList",
contentType: 'application/json',
data: '{"strEmail": "' + strFilter + '" }',
dataType: "json",
success: function (data) {
console.log(data.d); //valid JSON response.
}
});
If you returning back a string you have to somehow parse it into an object. E.g.
var data = '{"Table":[[2,"BlackBerry Tour","2013-09-10","2013-09-13","Project"],null]}';
var dataJ
eval('dataJ = ' + data )
alert(dataJ.Table)
http://jsfiddle.net/uvvAm/
If you're using jQuery you can use
var dataJ = $.parseJSON(data);
This is preferable, since eval is open to all kinds of attacks.
var dataObject = eval('(' + data + ')');
alert(dataObject.Table);
Try this thing may help you.

Rendering mongodb database results from POST request in .ajax jquery wrapper in node js

I am creating a basic piece of functionality to allow users to send their location to a server which then queries a database and returns locations near to them. I am using the below jQuery .ajax wrapper to POST data to the server. This takes the form of a latlon point which is then used as the basis for a geosearch in MongoDB using nodejs and express on the backend. The results of the search are then intended to be returned to the client and rendered by the createMapListings function.
The /find page is initially rendered through a GET request to the database via mongodb separate from the below code. However subsequent to initial rendering, I then want to return results dependent on the location provided.
The POST method works fine and the location is posted to the server, with the search results being returned as I can print contents out through the console log.
However, I then want to render the results on the client-side. As mentioned, the results of the search render in the console, but when I attempt to pass through to the client, I can render the data itself (in the form of an array of objects) in the #output div, but the createMapListings function does not seem to catch the data.
In fact, the below function appears to be called but prints out over a thousand rows with the data that should be caught described as 'undefined'. I have tried to use res.render and res.redirect, but in the first case, the view renders in the div (which I suppose is expected) and the redirect fails.
The createMapListings function works fine when a simple GET request is made to the server, for example, for all objects in a collection, using ejs template. However, I think the issue here may be a combination of a POST request and then wanting to pass the results back to the AJAX request using the complete callback.
I apologise if the below code is somewhat obtuse. I’m definitely what you would call a beginner. I appreciate the above functionality may not possible so if there is a better way, I would of course be open to it (res.direct perhaps).
Here is the relevant client side script:
$(document).ready(function(){
$("#geolocate").click(function(){
navigator.geolocation.getCurrentPosition(geolocate, function(){
});
});
});
function geolocate(pos){
var latlonpt = [];
var x = pos.coords.latitude;
var y = pos.coords.longitude;
latlonpt.push(x);
latlonpt.push(y);
var obj = {
userlocation: latitudelongitudept
};
$.ajax({
url: "/find",
type: "POST",
contentType: "application/json",
processData: false,
data: JSON.stringify(obj),
complete: function (data) {
$('#output').html(data.responseText);
$('#infooutput').children().remove();
createMapListings(data.responseText);
}
});
};
function createMapListings(maps) {
for (var i = 0; i < maps.length; i++) {
var url = maps[i]._id;
var fullurl = "<a href='/show?id=" + url + "'>Route</a></div>";
var title = "<div>" + maps[i].title + " - " + fullurl +"";
$('#infooutput').append(title);
};
};
</script>
Here is the relevant route used in a basic express app to handle the post request made by the above .ajax wrapper.
exports.findbylocation = function(req, res) {
console.log(req.body.userlocation);
var userlocation = req.body.userlocation;
Map.ensureIndexes;
Map.find({loc :{ $near : userlocation }}, function(err, maps) {
if (err) {
console.log(err)
}
else {
var jmaps = JSON.stringify(maps);
console.log(jmaps);
res.send(jmaps);
}
});
};
By convention, the data variable name in an $.ajax callback signature refers to the parsed HTTP response body. Since your callback is on complete, we're actually passed the XMLHttpRequest used, by convention called xhr. You rightly grab the responseText property, but this needs parsing to be useful. So long as we take care over our Content-Type's and don't explicitly disable processData, jQuery will do the encoding/unencoding for us - we just deal with objects. This is a good thing, since the transport format isn't usually of any particular importance to the application logic. If we use res.json(maps) in place of res.send(jmaps), we can write our call more simply:
$.ajax({
url: '/find',
type: 'POST',
data: obj,
success: function(data) {},
error: function(xhr, text, err) {}
});
Here data is a Javascript object already parsed and ready to use. We also use a default application/x-www-form-urlencoded request rather than explicitly setting a contentType. This is the same as far as express is concerned: it will just be parsed by urlencoded instead of json.
Assuming you solved your client-sie problem.
As you are using express there is no need for JSON.stringfy,
you can use res.json(maps).

Ajax - 500 Internal Server Error

I am trying to learn AJAX for this project at work. I have a site that loads medications that a patient is taking.
I call this AJAX function up recursively so that it will append a new table containing a single medication and 7 days worth of history. I am having issues getting the code to execute in FF and IE. Works perfectly fine in chrome. I had alerts displaying the xmlhttp.status and this is what I got:
xmlhttp.status==500 (internal server
error).
I commented out all of my recursion so it is narrowed down to this tid bit of code. ( x keeps track of the number of meds so i know when to stop)
function LoadMeds()
if ( x == MaxMedCount )
{
document.getElementById("the_day").value = parseInt(document.getElementById("the_day").value)+7;
}
if ( x == (MaxMedCount - 1) )
{
document.getElementById("x").value = x + 1;
show();
}
else
{
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
try
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var div = document.createElement('div');
div.innerHTML= xmlhttp.responseText;
document.getElementById('MedTable').appendChild(div);
document.getElementById("the_med_").value = the_med_;
}
}
catch(e)
{
alert("Error");
}
}
xmlhttp.open("GET","URL with variables passed",true);
xmlhttp.send();
document.getElementById("x").value = x + 1;
}
if more code is needed just let me know.
The 500 (internal server error) means something went wrong on the server's side. It could be several things, but I would start by verifying that the URL and parameters are correct. Also, make sure that whatever handles the request is expecting the request as a GET and not a POST.
One useful way to learn more about what's going on is to use a tool like Fiddler which will let you watch all HTTP requests and responses so you can see exactly what you're sending and the server is responding with.
If you don't have a compelling reason to write your own Ajax code, you would be far better off using a library that handles the Ajax interactions for you. jQuery is one option.
I think your return string data is very long. so the JSON format has been corrupted.
You should change the max size for JSON data in this way :
Open the Web.Config file and paste these lines into the configuration section
<system.web.extensions>
<scripting>
<webServices>
<jsonSerialization maxJsonLength="50000000"/>
</webServices>
</scripting>
</system.web.extensions>
This may be an incorrect parameter to your SOAP call; look at the format of the parameter(s) in the 'data:' json section - this is the payload you are passing over - parameter and data wrapped in JSON format.
Google Chrome's debugging toolbar has some good tools to verify parameters and look at error messages - for example, start with the Console tab and click on the URL which errors or click on the network tab. You will want to view the message's headers, response etc...
Uncomment the following line : [System.Web.Script.Services.ScriptService]
Service will start working fine.
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
To allow this Web Service to be called from script, using ASP.NET
AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
Had the very same problem, then I remembered that for security reasons ASP doesn't expose the entire error or stack trace when accessing your site/service remotely, same as not being able to test a .asmx web service remotely, so I remoted into the sever and monitored my dev tools, and only then did I get the notorious message "Could not load file or assembly 'Newtonsoft.Json, Version=3.5.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed' or one of its dep...".
So log on the server and debug from there.
One must use behavior: JsonRequestBehavior.AllowGet in Post Json Return in C#
I fixed an error like this changing the places of the routes in routes.php, for example i had something like this:
Route::resource('Mensajes', 'MensajeriaController');
Route::get('Mensajes/modificar', 'MensajeriaController#modificarEstado');
and then I put it like this:
Route::get('Mensajes/modificar', 'MensajeriaController#modificarEstado');
Route::resource('Mensajes', 'MensajeriaController');
I had the same error. It turns out that the cause was that the back end method was expecting different json data. In my Ajax call i had something like this:
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"url":"test"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
});
Now in my WebMethod, inside my C# backend code i had declared my endpoint like this:
public static string PostAjax(AjaxSettings settings)
Where AjaxSettings was declared:
public class AjaxSettings
{
public string url { get; set; }
}
The problem then was that the mapping between my ajax call and my back-end endpoint was not the same. As soon as i changed my ajax call to the following, it all worked well!
var data ='{"url":"test"}';
$.ajax({
async: false,
type: "POST",
url: "http://13.82.13.196/api.aspx/PostAjax",
data: '{"settings":'+data+'}',
contentType: "application/json; charset=utf-8",
dataType: "json"
});
I had to change the data variable inside the Ajax call in order to match the method signature exactly.

Categories

Resources