My jquery and ajax call is not responding and showing unexpected error in console - ajax

I don't know why my code is giving error while making the ajax call and not responding or working at all. I ran this on an html file. I took this function - getParameterByName() from another stackoverflow answer.tweet-container tag is down the code below outside this script and an empty division.I tried some jquery also.
<script>
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
$(document).ready(function(){
console.log("working");
var query = getParameterByName("q")
// console.log("query");
var tweetList = [];
function parseTweets(){
if (tweetList == 0){
$("#tweet-container").text("No tweets currently found.")
} else {
//tweets are existing, so parse and display them
$.each(parseTweets, function(key, value){
//console.log(key)
// console.log(value.user)
// console.log(value.content)
var tweetKey = value.key;
var tweetUser = value.user;
var tweetContent = value.content;
$("#tweet-container").append(
"<div class=\"media\"><div class=\"media-body\">" + tweetContent + "</br> via " + tweetUser.username + " | " + View + "</div></div><hr/>"
)
})
}
}
$.ajax({
url:"/api/tweet/",
data:{
"q": query
},
method: "GET",
success:function(data){
//console.log(data)
tweetList = data
parseTweets()
},
error:
function(data){
console.log("error")
console.log(data)
}
})
});
</script>
strong text

Fix the quotes to resolve your syntax error:
$("#tweet-container").append("<div class=\"media\"><div class=\"media-body\">" + tweetContent + " </br> via " + tweetUser.username + " | " + "View</div></div><hr/>")

Related

How do I send a base64 image to Microsoft-ocr api?

I'm trying to use Microsoft Azure OCR API service to extract some text from an image.
The image I have for sending to the API service has a "data:image/png; base64, " structure and therefore I can't send it with content-type "application/json".
I tried sending it with content-type "multipart/form-data" or "application/octet-stream", but it also fails...
// this "url" gives me the "data:data:image/png;base64, " code
var sourceImageUrl = document.getElementById("myImage").src;
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(jqXHR){
jqXHR.setRequestHeader("Content-Type","multipart/form-data");
jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: [sourceImageUrl]
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ?
"Error. " : errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
I am bit confused about how I should be sending the image or if I should do some transformations.
Which content-type should I be using to do a proper request?
Should I change the encoding of the image source? How?
Thank you all!
I finally got it working by adding a makeBlob function that returns a blob out of a base64 code. I also set the content-type to "application/octet-stream".
Final code looks like this:
function makeblob(b64Data, contentType, sliceSize) {
contentType = contentType || '';
sliceSize = sliceSize || 512;
var byteCharacters = atob(b64Data);
var byteArrays = [];
for (var offset = 0; offset < byteCharacters.length; offset += sliceSize) {
var slice = byteCharacters.slice(offset, offset + sliceSize);
var byteNumbers = new Array(slice.length);
for (var i = 0; i < slice.length; i++) {
byteNumbers[i] = slice.charCodeAt(i);
}
var byteArray = new Uint8Array(byteNumbers);
byteArrays.push(byteArray);
}
var blob = new Blob(byteArrays, { type: contentType });
return blob;
}
function recognizeText() {
imageToSend = image.src;
binDataImage = imageToSend.replace("data:image/png;base64,","");
// Perform the REST API call.
$.ajax({
url: uriBase + "?" + $.param(params),
// Request headers.
beforeSend: function(jqXHR){
jqXHR.setRequestHeader("Content-Type","application/octet-stream");
jqXHR.setRequestHeader("Ocp-Apim-Subscription-Key", subscriptionKey);
},
type: "POST",
// Request body.
data: makeblob(binDataImage, 'image/jpeg'),
cache: false,
processData: false
})
.done(function(data) {
// Show formatted JSON on webpage.
$("#responseTextArea").val(JSON.stringify(data, null, 2));
})
.fail(function(jqXHR, textStatus, errorThrown) {
// Display error message.
var errorString = (errorThrown === "") ?
"Error. " : errorThrown + " (" + jqXHR.status + "): ";
errorString += (jqXHR.responseText === "") ? "" :
(jQuery.parseJSON(jqXHR.responseText).message) ?
jQuery.parseJSON(jqXHR.responseText).message :
jQuery.parseJSON(jqXHR.responseText).error.message;
alert(errorString);
});
};

Execute multiple http request - Parse Cloud Code

i have an array of stores, where the address and some other things are stored.
Now I want to iterate through this array and geocode the lat / lng coords and save them to the database.
With the code below I get double or triple entries of the same store. Do I miss something with the scope here?
Thanks!
var promises = [];
data.forEach(function (element, index)
{
var addressString = element.plz + " " + element.stadt + "," + element.adresse;
var url = encodeURI("https://maps.googleapis.com/maps/api/geocode/json?address=" +
addressString);
var promise = Parse.Cloud.httpRequest({
method: "GET",
url:url
}).then(function (http) //SUCCESS
{
var geocodedObject = new Parse.Object("GeocodedStores");
geocodedObject.set("storeID", element.id);
geocodedObject.set("Latitude", http.data.results[0].geometry.location.lat);
geocodedObject.set("Longitude", http.data.results[0].geometry.location.lng);
return geocodedObject.save(null, {
useMasterKey: true
});
},
function (http, error)
{
response.error(error);
});
promises.push(promise);
});
return Parse.Promise.when(promises);
Finally found a working solution. It looked like it was a problem with the scope. I put the code in a seperate function and added this returned promise to an array.
var fn = function(element, geocodedObject)
{
var addressString = element.plz + " " + element.stadt + "," + element.adresse;
var url = encodeURI("https://maps.googleapis.com/maps/api/geocode/json?address=" +
addressString);
Parse.Cloud.httpRequest({
method: "GET",
url: url
}).then(function(http)
{
geocodedObject.set("storeID", element.id);
geocodedObject.set("Latitude", http.data.results[0].geometry.location.lat);
geocodedObject.set("Longitude", http.data.results[0].geometry.location.lng);
geocodedObject.set("address", addressString);
return geocodedObject.save(null, {
useMasterKey: true
});
});
}
var promises = [];
for (var k = 0;k<data.length;k++)
{
var geocodedObject = new Parse.Object("GeocodedStores");
promises.push(fn(data[k], geocodedObject));
}
Parse.Promise.when(promises).then(function () {
response.success("DONE");
});

why save event is not working in cloud code?

Find my code below which working very fine. but only problem facing by me is that save event is not working for me.Also you can see my log file in the picture. In each method i tried success and error function which working fine as you can see in picture. I tried this code alot but still... it is not working for me.
It always shows error message.
Code :
Parse.Cloud.afterSave("HouserDetailed", function(request, response)
{
var obj = request.object.id;
//console.log(obj);
// code !
var houserdetailed = new Parse.Object("HouserDetailed");
var query = new Parse.Query("HouserDetailed");
query.equalTo("objectId", obj);
query.first({
success: function(results) {
//alert("updates objectId " +request.object.id + " " + "input" + " "+ request.object.bet_title );
var bet_title = results.get("bet_title");
var match_id = results.get("match_id");
var level_coin = results.get("level_coin");
if(bet_title !== "false")
{
console.log("bet_title :- "+bet_title+", match_id:- "+match_id+", level_coin:- "+level_coin);
// nested query
var better = new Parse.Object("Better");
var query1 = new Parse.Query("Better");
query1.equalTo("match_id", match_id);
query1.first({
success: function(result){
var bet_title_better = result.get("bet_title");
var user_id = result.get("user_id");
var bet_OnNoOfticket = result.get("bet_OnNoOfticket");
var bet_price = result.get("bet_price");
var money_got = bet_OnNoOfticket * bet_price;
console.log("bet_title_better :-"+bet_title_better);
if(bet_title !== bet_title_better)
{
console.log("Condition does not match!");
}
else
{
console.log("Condition match!" + "money got :- "+money_got);
// checking for existing user in parse DB
var wallet = new Parse.Object("Wallet");
var query2 = new Parse.Query("Wallet");
query2.equalTo("user_id", user_id);
query2.first({
success: function(result)
{
console.log("User found");
var wallet_coins_number = result.get("wallet_coins_number");
var objectId = result.get("objectId");
total_amount = +wallet_coins_number + +money_got;
console.log("Total amount got :- " + total_amount );
// saving amount in wallet
var Wallet = Parse.Object.extend("Wallet");
var wallet = new Wallet();
wallet.set("user_id", user_id);
wallet.set("wallet_coins_number", total_amount);
wallet.save(null, {
success: function(wallet){
console.log("amount saved in wallet!");
},
error: function(wallet)
{
console.log("amount not saved in wallet!");
}
});
},
error: function(error)
{
console.log("User not found");
}
});
}
},error: function(error)
{
}
});
}
// nested query end
},
error: function(error) {
console.log("Error: " + error.code + " " + error.message);
}
});
// code !
});][1]][1]
I don't see any log, probably it would tell you what is wrong. But you are attempting to save existing ParseObject with dirty objectId, which is bad idea. You are not allowed to change objectId of existing object. Try to remove wallet.set("objectId", objectId) from your code.
You should not use result.get("objectId") either, use result.id instead.

Parsing JSON with AJAX - show random item of the JSON and update after an amount of time

I'm able to parse JSON with ajax, but at the moment it shows all the names out of the JSON.
I want only one name viewed and after an amount of time I want another one viewed and so on..
Ajax code:
$(document).ready(function(){
parseJson();
});
function parseJson(){
$.ajax({
url : 'data/members.json',
dataType : 'json',
success : function(data) {
succes(data);
},
error: function(){
window.alert("error");
}
});
};
function succes(dataObj){
var counter = 1;
$.each(dataObj.Members.Member, function(indexData, valueData){
var htmlString = "";
htmlString += '<article class="memberInfo" data-object="' + counter + '">';
htmlString += "<div class=''><p>" + valueData.Firstname + ' ' + valueData.Surname + "</p></div>";
htmlString += "</article>";
$("#members").append(htmlString);
counter++;
});
}
Rather than use .append you can use .html and set a staggering timeout so that it cycles through the names that get displayed:
var timer = 0;
$.each(...
setTimeout(function () {
var htmlString = "";
/* snip */
$("#members").html(htmlString);
}, timer + (indexData * 2000));
});

Javascript JSON results throws text is null error

I am using ajax to pull photos from instagram. Below is the ajax call:
$.ajax({
type: "GET",
dataType: "jsonp",
cache: false,
url: "https://api.instagram.com/v1/media/search?lat=" + lat +"&lng=" + lng + "&distance=" + distance + "&access_token=" + accessToken + "",
success: function(data) {
for (var i = 0; i < 6; i++) {
$("#instagram").append("<li><a class='group' title='' href='" + data.data[i].images.standard_resolution.url +"'><img src='" + data.data[i].images.thumbnail.url +"' /></a>");
}
}
});
This works well due to the fact that the anchors title attribute is left blank. I was using title='" + data.data[i].caption.text + "' to pull the instagram caption as the anchor title. For the most part, this works, but I often get the following error: "Uncaught TypeError: Cannot read property 'text' of null"
I am assuming this is happening from one of two reasons:
A) no caption at all
B) a caption with characters that will not work as a title.
Does anyone know why this is happening, and also how I can fix this? I tried the following but it throws the same error:
if(data.data[i].caption.text != null) {
var title = data.data[i].caption.text;
} else {
var title = "";
}
Any ideas?
If there is no caption attached, Instagram does not return that field. Just add another null check.
if (data.data[i].caption !=null) {
if(data.data[i].caption.text != null) {
var title = data.data[i].caption.text;
}
} else {
var title = "";
}
for (x in data.data) {
var title_text = '';
if (data.data[x].caption != null) {
if (data.data[x].caption.text != null) {
title_text = data.data[x].caption.text;
}
} else {
title_text = "";
}
$("#instagram").append("<a target="_blank" href="' + data.data[x].link + '">" + title_text);
}

Resources