0

I want to convert Jquery Ajax to Pure JavaScript Ajax, i hope someone can help me,

jQuery

$.ajax({
            type: "GET",
            contentType: "application/json; charset=utf-8",
            url: accessURL,
            dataType: 'jsonp',
            success: function (data) {        
                var dataLen = data.results.length;
                // console.log("api returned " + dataLen + " total results");

                 $.each(data.results, function (i, val) {
                     var venueObj = val.venue;
                     //console.log(venueObj);

                    if ( ( venueObj && venueObj.lat != 0) ) {

                        meetupName.push(val.name);
                        meetupDescript.push(val.description);
                        meetupUrl.push(val.event_url);

                        //meetupLat = [];
                        meetupLat.push(venueObj['lat']);
                        //meetupLong = [];
                        meetupLon.push(venueObj['lon']);

                        //address
                        meetupAddress.push(
                            venueObj['address_1'] + "</h3><h3>" +
                            venueObj['city']
                        );

                    } else {
                        return;
                    }

                });

                //console.log(data.results);

                //console.log(meetupLon);
                meetupLon = _.without(meetupLon, 0);
                //console.log(meetupLon);
                meetupLat = _.without(meetupLat, 0);
                //console.log(meetupLat);

                //console.log(meetupAddress);


                for (i=0; i < meetupLat.length; i++) {
                    //set the markers.    
                    myLatlng = new google.maps.LatLng(meetupLat[i], meetupLon[i]);

                    allMarkers = new google.maps.Marker({
                        position: myLatlng,
                        map: map,
                        title: "Meetup",
                        html:
                                '<div class="markerPop">' +
                                    "<h2>"+ meetupName[i] +"</h2>" +
                                    "<h3>"+ meetupAddress[i] +"</h3>" +
                                    "<p>"+ meetupDescript[i] +"</p>" +
                                    "<a href='"+ meetupUrl[i] +"'>"+ meetupUrl[i] +"</p>" +

                                '</div>'
                    });

                    allLatlng.push(myLatlng); 
                    //console.log(allLatlng);

                    google.maps.event.addListener(allMarkers, 'click', function () {
                        infowindow.setContent(this.html);
                        infowindow.open(map, this);
                    });

                    //  Make an array of the LatLng's of the markers you want to show
                    //  Create a new viewpoint bound
                    var bounds = new google.maps.LatLngBounds ();
                    //  Go through each...
                    for (var i = 0, LtLgLen = allLatlng.length; i < LtLgLen; i++) {
                      //  And increase the bounds to take this point
                      bounds.extend (allLatlng[i]);
                    }
                    //  Fit these bounds to the map
                    map.fitBounds (bounds); //Finished !(a)


                } //end for loop


            }
        }); //end ajax request

i saw little code here. http://youmightnotneedjquery.com/ this is the code

Pure Javascript

var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);

request.onload = function() {
  if (request.status >= 200 && request.status < 400) {
    // Success!
    var resp = request.responseText;
  } else {
    // We reached our target server, but it returned an error

  }
};

request.onerror = function() {
  // There was a connection error of some sort
};

request.send();

how can i set the contentType and dataType

mmativ
  • 1,414
  • 14
  • 25

2 Answers2

3

Try:

function jsonp(url, callback) {
    var callbackName = 'jsonp_callback_' + Math.round(100000 * Math.random());
    window[callbackName] = function(data) {
        delete window[callbackName];
        document.body.removeChild(script);
        callback(data);
    };

    var script = document.createElement('script');
    script.src = url + (url.indexOf('?') >= 0 ? '&' : '?') + 'callback=' + callbackName;
    document.body.appendChild(script);
}

jsonp('https://api.meetup.com/2/open_events.json?zip=12233&page=30&category=34&time=,1w&key=1719487a4a3c39b3e241e181837529', function(data) {
   alert(data.meta.description);
});

https://jsfiddle.net/tgL5v0yo/

note:

JSONP does not use XMLHttpRequests. The reason JSONP is used is to overcome cross-origin restrictions of XHRs.

madalinivascu
  • 32,064
  • 4
  • 39
  • 55
  • how about the data type? sorry i am not good at pure `javascript`. – mmativ Mar 30 '16 at 08:12
  • `Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.` i still cant get request. – mmativ Mar 30 '16 at 08:45
  • please can u include it to my `script` idk where to put, i am so confuse, sorry – mmativ Mar 30 '16 at 09:05
  • i think this is working but i got error `{"details":"API requests must be key-signed, oauth-signed, or accompanied by a key: http:\/\/www.meetup.com\/meetup_api\/docs\/#authentication","code":"not_authorized","problem":"You are not authorized to make that request"}` – mmativ Mar 30 '16 at 09:17
  • seems to be a problem with the variables ,try it now – madalinivascu Mar 30 '16 at 09:26
  • same, `XMLHttpRequest cannot load https://api.meetup.com/2/open_events.json. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.` – mmativ Mar 30 '16 at 09:31
  • still the control origin blocking me `XMLHttpRequest cannot load https://api.meetup.com/2/open_events.json?zip=12233&page=30&category=34&time=,1%E2%80%8C%E2%80%8Bw&key=1719487a4a3c39b3e241e181837529&callback=func. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.` – mmativ Mar 30 '16 at 09:48
  • please join here http://chat.stackoverflow.com/rooms/107713/ajax-request – mmativ Mar 30 '16 at 10:04
1

Problem is here:

request.onload

try replacing with

request.onreadystatechange

for to continue with request.onload see this onreadystatechange

For more info Using XMLHttpRequest

UPDATE 1

var request = new XMLHttpRequest();
request.withCredentials = true;
request.open('GET', '/my/url', true);
Community
  • 1
  • 1
itzmukeshy7
  • 2,669
  • 1
  • 21
  • 29
  • i got error `Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.` – mmativ Mar 30 '16 at 08:25
  • For this error see this [getting-request-doesnt-pass-access-control-check-no-access-control-allow-orig](http://stackoverflow.com/questions/33820142/getting-request-doesnt-pass-access-control-check-no-access-control-allow-orig) – itzmukeshy7 Mar 30 '16 at 08:27
  • thats a php, so i think i cant use that. – mmativ Mar 30 '16 at 08:29
  • What url you are trying to access using this pure JavaScript method? – itzmukeshy7 Mar 30 '16 at 08:30
  • `https://api.meetup.com/2/open_events.json?zip=12233&page=30&category=34&time=,1w&key=1719487a4a3c39b3e241e181837529` – mmativ Mar 30 '16 at 08:33
  • This is because you are making `crossDomain` ajax request; – itzmukeshy7 Mar 30 '16 at 08:52
  • yes, but in ajax, work flawless. – mmativ Mar 30 '16 at 08:53
  • this is the ajax request i want to make pure javascript, `https://github.com/adrienshen/TechMeetups/blob/master/js/meetup.js` – mmativ Mar 30 '16 at 08:57
  • check this one, `http://dota2nation.com/project/meetup/market.html` this is the sample of working ajax request using `$.ajax` use in the zip code `10002` – mmativ Mar 30 '16 at 09:01
  • Try **UPDATE 1** from answer; – itzmukeshy7 Mar 30 '16 at 09:17