Search code examples
jqueryajaxvb.netiis-7.5

convert VB.NET to jQuery


I'm trying to use web-based API. All I received from my client is this code:

Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
    Dim client = New Net.WebClient
    client.Credentials = New Net.NetworkCredential(System.Configuration.ConfigurationManager.AppSettings("apiUsername"), _
                                                    System.Configuration.ConfigurationManager.AppSettings("apiPassword"), _
                                                    System.Configuration.ConfigurationManager.AppSettings("apiDomain"))


    client.Headers(Net.HttpRequestHeader.ContentType) = "application/json"
    Dim eventParam As New PlumbingLibrary.StreamGameParam With {.EnterpriseId = txtAuthorEID.Text,
                                                                 .HeaderText = TxtText.Text,
                                                                 .ImageUrl = txtURL.Text,
                                                                 .Title = txtPhotoURL.Text,
                                                                 .Description = txtAlbumURL.Text}

    Dim stream As New IO.MemoryStream()
    Dim serializer As New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(PlumbingLibrary.StreamGameParam))
    serializer.WriteObject(stream, eventParam)

    Dim data As Byte() = client.UploadData(PlubingAPI_URL, "POST", stream.ToArray())


    stream = New IO.MemoryStream(data)
    serializer = New System.Runtime.Serialization.Json.DataContractJsonSerializer(GetType(PlumbingLibrary.Activity))
    Dim returnActivity = TryCast(serializer.ReadObject(stream), PlumbingLibrary.Activity)

    End Sub

This is part of working VB desktop application that I'm supposed to use as a example. Project I'm working on is solely web based though. All written in javascript/jquery.

I tried this:

 var username = "API-ID",
    password = "API-PASS",
    url = "API-URL";


 function make_basic_auth(user, password) {
  var tok = user + ':' + password;
  var hash = Base64.encode(tok);
  return "Basic " + hash;
}

var auth = make_basic_auth(username,password);

$.support.cors = true;

  $.ajax
      ({
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        async: false,
        crossDomain: true,
        data: JSON.stringify({EnterpriseId: "the.id",
                              HeaderText: " ",
                              ImageUrl: " ",
                              Title: " ",
                              Description: " "
        }),
        beforeSend : function(req) {
            req.setRequestHeader('Authorization', auth);
        },
        success: function (){
            console.log('Success');
            $("body").append("success");
        },
        error: function (xhr, err) {
            console.log("ERROR");
            console.log(xhr.statusText);
        }
    });

I also tried all other ajax + cors variations.

e.g.:

xhr = new XMLHttpRequest();
      xhr.open('POST', url, true);

      console.log(xhr);
      xhr.setRequestHeader('X-PINGOTHER', 'pingpong');
      xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhr.setRequestHeader('Authorization', auth);

but I'm getting 401 unautorized and No 'Access-Control-Allow-Origin' header. The login information I have work with the desktop app. I can also login directly thru http login in browser to the API url.

Does anyone can help?


Solution

  • It can get a bit tricky with cross-domain. If you are receiving data back from the client in json format (and it looks like you do), try to tell your script you are receiving jsonp data by adding this line in your request: dataType: "jsonp"

    $.ajax
      ({
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        async: false,
        crossDomain: true,
        dataType: "jsonp",
        data: JSON.stringify({EnterpriseId: "the.id",
                              HeaderText: " ",
                              ImageUrl: " ",
                              Title: " ",
                              Description: " "
        }),
        beforeSend : function(req) {
            req.setRequestHeader('Authorization', auth);
        },
        success: function (){
            console.log('Success');
            $("body").append("success");
        },
        error: function (xhr, err) {
            console.log("ERROR");
            console.log(xhr.statusText);
        }
    });