Multiple JSON objects via AJAX

I have result returned using AJAX like this:

{"FileName":"example.jpg",
"Statuses":null,
"ProductMatchedByCode":{"ProductID":"00000000-0000-0000-0000-000000000000",
"ProductDetailID":"00000000-0000-0000-0000-0",
"Code":"",
"Title":"",
"ProductImages":[{"Path:"\\v4\\images\example.jpg",
"Date":null,
"OriginalFileName":"example.jpg",
"FileSize":null}],
"IsSuccesfull":false,
"StatusCode":200,
"StatusMessage":""},
"IsSuccessful":true,
"StatusCode":200,
"StatusMessage":'example.jpg' Uploaded Successful"
}
{"FileName":"example2.jpg",
"Statuses":null,
"ProductMatchedByCode":{"ProductID":"00000000-0000-0000-0000-000000000000",
"ProductDetailID":"00000000-0000-0000-0000-0",
"Code":"",
"Title":"",
"ProductImages":[{"Path:"\\v4\\images\example2.jpg","Date":null,"OriginalFileName":"example2.jpg",
"FileSize":null}],
"IsSuccesfull":false,
"StatusCode":200,
"StatusMessage":""},
"IsSuccessful":true,
"StatusCode":200,
"StatusMessage":'example2.jpg' Uploaded Successful"
}

But Status Message was undefined, also I think I used the wrong way for result.length it doesn’t give real objects length, it gives me something bigger ex.525.Any idea how can I fix it? Any suggestions will be appreciated. Thanks

My code:

$.ajax({
  url: self.webserviceUploadImageUrl,
  type: 'POST',
  processData: false,
  contentType: false,
  cache: false,
  data: formData,
  success: function(result) {
   for (var i = 0; i < result.length; i++) {
   var statusmsg = JSON.stringify(result[i]).StatusMessage;
   }
    var url = location.protocol + '//' + location.host + location.pathname;
    
    if (url.indexOf('?') > -1) {
      url += '&message=' + statusmsg;
    } else {
      url += '?message=' + statusmsg;
    }
    window.location.href = url;
  },
  error: function() {
    self.statusMessage("Error uploading");
  }
});

Do you have the actual JSON return (that is not valid json, perhaps it’s two JSONs) or can you give a sample url and body we can use to hit the endpoint?

For one thing here, why are you stringifying this? It is already an object. If you stringify it it becomes a JSON encoded string. It isn’t going to have the property StatusMessage - not matter what that object is, that property will always come back undefined. What does:

var statusmsg = result[i].StatusMessage;

give you?

I try to use JSON.parse but always give me an error like this one :Uncaught SyntaxError: Unexpected token { in JSON at position 570
at JSON.parse ()
at Object.success (jquery.magico.shop.js:11834)
at n (jquery-1.7.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.7.1.min.js:2)
at w (jquery-1.7.1.min.js:4)
at XMLHttpRequest.d (jquery-1.7.1.min.js:4)


This is an original return of result

Is that the response you are getting? Is that result?

I guess my issue would be that (unless you know something specific about this data response), it is most likely the entire response that is JSON, not the individual elements in the array.

What about:

function(JSONResult) {
   const result = JSON.parse(JSONResult);
   for (var i = 0; i < result.length; i++) {
     var statusmsg = result[i].StatusMessage;
   }
   // ...

This will parse the result, not the individual elements in the array (If we’re even getting those.)

I try this and there again an error
Uncaught SyntaxError: Unexpected token { in JSON at position 570
at JSON.parse ()
at Object.success (jquery.magico.shop.js:11848)
at n (jquery-1.7.1.min.js:2)
at Object.fireWith [as resolveWith] (jquery-1.7.1.min.js:2)
at w (jquery-1.7.1.min.js:4)
at XMLHttpRequest.d (jquery-1.7.1.min.js:4)

Is the endpoint you are hitting public? This would be a lot easier to help you.

What is the type that you are getting as the result, like:

function(result) {
  console.log(typeof result);
  console.log(result);

Can you cut and paste the result, not take a picture of it?

string
jquery.magico.shop.js:11849 {“FileName”:“123image.jpg”,“Statuses”:null,“ProductMatchedByCode”:{“ProductID”:“00000000-0000-0000-0000-000000000000”,“ProductDetailID”:“00000000-0000-0000-0000-000000000000”,“Code”:"",“Title”:"",“ProductImages”:[{“Path”:"\v4\c5fcaa67-0ba8-421d-8223-7fb1b08b70a2\images\product_originals\123image.jpg",“Date”:null,“ID”:“ccfbff65-9532-47c7-9b68-41e409842307”,“OriginalFileName”:“123image.jpg”,“FileSize”:null}],“IsSuccessful”:false,“StatusCode”:200,“StatusMessage”:""},“IsSuccessful”:true,“StatusCode”:200,“StatusMessage”:"‘123image.jpg’ has already been uploaded."}{“FileName”:“a.jpg”,“Statuses”:null,“ProductMatchedByCode”:{“ProductID”:“00000000-0000-0000-0000-000000000000”,“ProductDetailID”:“00000000-0000-0000-0000-000000000000”,“Code”:"",“Title”:"",“ProductImages”:[{“Path”:"\v4\c5fcaa67-0ba8-421d-8223-7fb1b08b70a2\images\product_originals\a.jpg",“Date”:null,“ID”:“55dfbfa4-fbef-4bc4-ab24-50fae27da0a8”,“OriginalFileName”:“a.jpg”,“FileSize”:null}],“IsSuccessful”:false,“StatusCode”:200,“StatusMessage”:""},“IsSuccessful”:true,“StatusCode”:200,“StatusMessage”:"‘a.jpg’ has already been uploaded."}

OK, when I format that, I get:

{
    "FileName":"123image.jpg",
    "Statuses":null,
    "ProductMatchedByCode":{
        "ProductID":"00000000-0000-0000-0000-000000000000",
        "ProductDetailID":"00000000-0000-0000-0000-000000000000",
        "Code":"",
        "Title":"",
        "ProductImages":[
            {
                "Path":"\v4\c5fcaa67-0ba8-421d-8223-7fb1b08b70a2\images\product_originals\123image.jpg",
                "Date":null,
                "ID":"ccfbff65-9532-47c7-9b68-41e409842307",
                "OriginalFileName":"123image.jpg",
                "FileSize":null
            }
        ],
        "IsSuccessful":false,
        "StatusCode":200,
        "StatusMessage":""
    },
    "IsSuccessful":true,
    "StatusCode":200,
    "StatusMessage":"‘123image.jpg’ has already been uploaded."
}
{
    "FileName":"a.jpg",
    "Statuses":null,
    "ProductMatchedByCode":{
        "ProductID":"00000000-0000-0000-0000-000000000000",
        "ProductDetailID":"00000000-0000-0000-0000-000000000000",
        "Code":"",
        "Title":"",
        "ProductImages":[
            {
                "Path":"\v4\c5fcaa67-0ba8-421d-8223-7fb1b08b70a2\images\product_originals\a.jpg",
                "Date":null,"ID":"55dfbfa4-fbef-4bc4-ab24-50fae27da0a8",
                "OriginalFileName":"a.jpg",
                "FileSize":null
            }
        ],
        "IsSuccessful":false,
        "StatusCode":200,
        "StatusMessage":""
    },
    "IsSuccessful":true,
    "StatusCode":200,
    "StatusMessage":"‘a.jpg’ has already been uploaded."
}

This is not valid JSON. Notice the lack of a comma after the first object - about halfway down.

// ...
    "StatusMessage":"‘123image.jpg’ has already been uploaded."
}
{
    "FileName":"a.jpg",
// ...

What is the endpoint you are hitting?

This is the code from where result come

HttpFileCollection files = Request.Files;

for (int i = 0; i < files.Count; i++) {
  HttpPostedFile file = files[i];



  string fileExtension = GetFileExtension(file.FileName);
  if (IsImageFile(fileExtension)) {
    bool dbSuccessful = false;
    string statusMessage = "Error inserting image into database";
    string targetFilePath = WebsiteCommon.GetVersion4OriginalProductImageFilePath(file.FileName);
    if (!File.Exists(targetFilePath)) {
      file.SaveAs(targetFilePath);
    }


    Product.Image images = WebsiteCommon.Product();
    FileViewModel imageFile = null;

    images.LoadImage(file.FileName);

    string urlFormat = @ "\v4\{0}\images\product_originals\{1}";

    if (images.HasRows()) {
      imageFile = new FileViewModel() {
        ID = images.ImageID, Path = String.Format(urlFormat, WebsiteCommon.ShopID.ToString(), images.OriginalFileName), OriginalFileName = images.OriginalFileName
      };

      statusMessage = String.Format("'{0}' has already been uploaded.", file.FileName);
      dbSuccessful = true;
      images.Unload();
    } else {
      images.Unload();
      System.Drawing.Image img = System.Drawing.Image.FromFile(targetFilePath);
      string fileNameMinusExtension = file.FileName.Substring(0, file.FileName.LastIndexOf("."));
      dbSuccessful = images.InsertImage(Guid.Empty, Guid.Empty, Product.Image.ImageGroup_OriginalProductImages, "", 0, "." + fileExtension,
        file.FileName, img.Width, img.Height, null, fileNameMinusExtension);
      statusMessage = String.Format("'{0}' uploaded successfully.", file.FileName);

      images.LoadImage(file.FileName);
      imageFile = new FileViewModel() {
        ID = images.ImageID, Path = String.Format(urlFormat, WebsiteCommon.ShopID.ToString(), images.OriginalFileName), OriginalFileName = images.OriginalFileName
      };
      images.Unload();
    }

    string productCode = GetProductCode(file.FileName);
    Product.ProductDetail product = WebsiteCommon.InitialiseProductDetails();
    classes.Responses.ProductSummaryResponse productMatch = null;
    if (product.LoadProductDetailsFromCode(productCode, WebsiteCommon.CatalogueID, true, true)) {
      productMatch = new classes.Responses.ProductSummaryResponse() {
        Code = productCode, IsSuccessful = true, ProductDetailID = product.ProductDetailID.ToString(), ProductID = Guid.Empty.ToString(), Title = product.Title, ProductImages = new List < FileViewModel > () {
          imageFile
        }
      };
    } else {
      productMatch = new classes.Responses.ProductSummaryResponse() {
        Code = "", IsSuccessful = false, ProductDetailID = Guid.Empty.ToString(), ProductID = Guid.Empty.ToString(), Title = "", ProductImages = new List < FileViewModel > () {
          imageFile
        }
      };
    }

    UploadFileResponse response = new UploadFileResponse {
      FileName = file.FileName,
        StatusMessage = statusMessage,
        Statuses = null,
        IsSuccessful = dbSuccessful,
        ProductMatchedByCode = productMatch
    };

    Response.Write(JsonConvert.SerializeObject(response, Formatting.None));
  } else {
    Response.Write("ERROR: Cant upload this type of file: " + file.FileName);
  }

}

WebsiteCommon.WebServices_Close();

Response.End();
}
}

private string GetProductCode(string fileName) {
  string name = fileName.IndexOf('.') > 0 ? fileName.Substring(0, fileName.LastIndexOf('.')) : fileName;

  if (name.Length > 4 && char.IsDigit(name[name.Length - 1]) && name.Contains("_")) {
    int index = name.Length - 1;
    while (index > 0 && char.IsDigit(name[index])) {
      index--;
    }
    if (index > 0 && name[index] == '_') {
      index--;
      while (index > 0 && char.IsDigit(name[index])) {
        index--;
      }
      if (index > 0 && name[index] == '-') {
        // remove char before size
        name = name.Substring(0, index);
      }
    }
  }

  if (name.Length > 2 && char.IsDigit(name[name.Length - 1]) && name.Contains("_")) {
    int index = name.Length - 1;
    while (index > 0 && char.IsDigit(name[index])) {
      index--;
    }
    if (index > 0 && name[index] == '_') {
      name = name.Substring(0, index);
    }
  }
  return name;

}
}
}
if (images.HasRows()) {
  imageFile = new FileViewModel() {
    ID = images.ImageID, Path = String.Format(urlFormat, WebsiteCommon.ShopID.ToString(), images.OriginalFileName), OriginalFileName = images.OriginalFileName
  };

  statusMessage = String.Format("'{0}' has already been uploaded.", file.FileName);
  dbSuccessful = true;
  images.Unload();
} else {
  images.Unload();
  System.Drawing.Image img = System.Drawing.Image.FromFile(targetFilePath);
  string fileNameMinusExtension = file.FileName.Substring(0, file.FileName.LastIndexOf("."));
  dbSuccessful = images.InsertImage(Guid.Empty, Guid.Empty, Product.Image.ImageGroup_OriginalProductImages, "", 0, "." + fileExtension,
    file.FileName, img.Width, img.Height, null, fileNameMinusExtension);
  statusMessage = String.Format("'{0}' uploaded successfully.", file.FileName);

  images.LoadImage(file.FileName);
  imageFile = new FileViewModel() {
    ID = images.ImageID, Path = String.Format(urlFormat, WebsiteCommon.ShopID.ToString(), images.OriginalFileName), OriginalFileName = images.OriginalFileName
  };
  images.Unload();
}

string productCode = GetProductCode(file.FileName);
Product.ProductDetail product = WebsiteCommon.InitialiseProductDetails();
classes.Responses.ProductSummaryResponse productMatch = null;
if (product.LoadProductDetailsFromCode(productCode, WebsiteCommon.CatalogueID, true, true)) {
  productMatch = new classes.Responses.ProductSummaryResponse() {
    Code = productCode, IsSuccessful = true, ProductDetailID = product.ProductDetailID.ToString(), ProductID = Guid.Empty.ToString(), Title = product.Title, ProductImages = new List < FileViewModel > () {
      imageFile
    }
  };
} else {
  productMatch = new classes.Responses.ProductSummaryResponse() {
    Code = "", IsSuccessful = false, ProductDetailID = Guid.Empty.ToString(), ProductID = Guid.Empty.ToString(), Title = "", ProductImages = new List < FileViewModel > () {
      imageFile
    }
  };
}

UploadFileResponse response = new UploadFileResponse {
  FileName = file.FileName,
    StatusMessage = statusMessage,
    Statuses = null,
    IsSuccessful = dbSuccessful,
    ProductMatchedByCode = productMatch
};

Response.Write(JsonConvert.SerializeObject(response, Formatting.None));
}
else {
  Response.Write("ERROR: Cant upload this type of file: " + file.FileName);
}
}

WebsiteCommon.WebServices_Close();

Response.End();
}
}


private string GetProductCode(string fileName) {

  string name = fileName.IndexOf('.') > 0 ? fileName.Substring(0, fileName.LastIndexOf('.')) : fileName;

  if (name.Length > 4 && char.IsDigit(name[name.Length - 1]) && name.Contains("_")) {
    int index = name.Length - 1;
    while (index > 0 && char.IsDigit(name[index])) {
      index--;
    }
    if (index > 0 && name[index] == '_') {
      index--;
      while (index > 0 && char.IsDigit(name[index])) {
        index--;
      }
      if (index > 0 && name[index] == '-') {
        // remove char before size
        name = name.Substring(0, index);
      }
    }
  }

  if (name.Length > 2 && char.IsDigit(name[name.Length - 1]) && name.Contains("_")) {
    int index = name.Length - 1;
    while (index > 0 && char.IsDigit(name[index])) {
      index--;
    }
    if (index > 0 && name[index] == '_') {
      name = name.Substring(0, index);
    }
  }
  return name;

}
}
}

I’ve edited your post for readability. When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).

What is that? C#? Sorry, I don’t do that. Perhaps someone else can. All I know is that is not valid JSON you were showing.

I would want to go into that server code and figure out exactly what it is sending back and if/why that isn’t valid JSON.

Looking at it again, it almost looks like two valid JSON responses stuck together. I don’t know why it would do that.

Maybe someone here does C# (or whatever it is) and can give better advice.

1 Like