synonym api Ajax call return - ajax

Have struggled with this call for a while now but i can't get it to work. dataToReturn still returns Error and not the called data. What am i doing wrong?
function get_translation(search) {
search = search.replace(/(<([^>]+)>)/ig, "").toLowerCase();
original = search;
google.language.translate( original , 'en', 'sv',
function(result) {
translated = result.translation;
$("#results").html('<li class="ui-li-has-icon ui-li ui-li-static ui-btn-up-c" role="option" tabindex="0">'+ translated + '</li>')
});
};
function get_synonyms(items) {
var dataToReturn = "Error";
$.ajax({
url: 'http://words.bighugelabs.com/api/1/xxx/' + items+ '/json',
type: 'GET',
dataType: 'jsonp',
async: false,
cache: false,
success: function(data) {
dataToReturn = data;
}
});
return dataToReturn;
}
$('#results').delegate("li", "tap", function(){
myDate = new Date();
displayDate = myDate.getDate() + "/" + myDate.getMonth()+1 + "/" + myDate.getFullYear();
id = myDate.getTime();
var wordObject = {'id' : id, 'date': displayDate, 'translated': translated, 'original': original, 'nmbr': "0", 'syn': get_synonyms('hello')};
save_terms(wordObject);
loopItems() ;
$("#results").html("");
$("#addField").val("");
// location.reload(true);
});

It's because the return dataToReturn line is being executed before the AJAX call is complete. When you call $.ajax, the browser says, "Okay, I'll just move on to the next thing while I'm waiting for that to get back to me."
The simplest way to fix this would be to change the success function to actually do whatever it is you're trying to do with dataToReturn. But if that's not really feasible, then more context would help come up with a better answer.

Related

Posting a pdf to Solr using Ajax

I am trying to push (Post) pdf files to Solr/Tika for text extraction and indexing using Ajax/js. I've gotten the following curl command to work:
curl 'http://localhost:8983/solr/techproducts/update/extract?literal.id=doc1&commit=true' -F "myfile=#/PathToFile/SomeDoc.pdf"
This command puts the desired pdf into the Solr Index, and I can retrieve it just fine. However, I need to be able to do this from a web browsers. After much googling, and a little experimentation I've got the following js code ALMOST working. It returns a 0 status code, and status of Success, but nothing gets committed to the index:
$("#solrPost").click(function(event) {
event.stopPropagation();
event.preventDefault();
/* Read a local pdf file as a blob */
let fileAsBlob = null;
let file = $('#upload_file')[0].files[0];
let myReader = new FileReader();
myReader.onloadend = function() {
fileAsBlob = myReader.result;
sendToSolr(fileAsBlob);
};
fileAsBlob = myReader.readAsArrayBuffer(file);
function sendToSolr(fileAsBlob) {
$.ajax({
url:"http://localhost:8983/solr/techproducts/update/extract?literal.id=doc2&commit=true",
type: 'POST',
data: fileAsBlob,
cache: false,
crossOrigin: true,
dataType: 'jsonp',
jsonp: 'json.wrf',
processData: false,
contentType: false,
success: function(data, status) {
console.log("Ajax.post successful, status: " + data.responseHeader.status + "\t status text: " + status);
console.log("debug");
},
error: function(data, status) {
console.log("Ajax.post error, status: " + data.status + "\t status text:" + data.statusText);
},
done: function(data, status) {
console.log("Ajax.post Done");
}
});
}
This is SO close to working, but I just can't figure out what's going wrong. All indications (From client side) are good, but nothing added to the index.
Note:
The fileReader is working, I see an Array of the same size as the source pdf.
Even though I specify POST, when I examine the network tab in the browser/debugger, it says GET.
I've hardcoded the literal.id=doc2 for simplicity, not a long term strategy...
I know there are similar posts, but none address the issue of extracting pdf's using Solr/Tika outside of the provided post script. Thanks in advance.
Well it took some searching but thanks to a post by "tonejac" I found the solution.
If you look at: [JQuery Ajax is sending GET instead of POST
The VERY last comment states that if you use dataType:jsonp that "POST" gets converted to "GET". I deleted the jsonp, installed a plugin to handle the CORS issue I was trying to avoid by using jsonp, and viola, it worked. For those interested, the working code is posted below. It's not fancy or robust but allows me to post or get documents (.pdf, .docx...) to Solr from a web app. I've only posted the js code, but the html is simple and provides an input of type "file", as well as inputs to set id for posting docs, or searching by id. There are two buttons, solrPost, and solrGet which call the listeners in the js. The connectSolr() function is called from the html onLoad.
function connectSolr() {
$("#solrPost").click(function(event) {
event.stopPropagation();
event.preventDefault();
/* Read a local pdf file as a blob */
let fileAsBlob = null;
let file = $('#upload_file')[0].files[0];
let myReader = new FileReader();
myReader.onloadend = function() {
fileAsBlob = myReader.result;
sendToSolr(fileAsBlob);
};
fileAsBlob = myReader.readAsArrayBuffer(file);
/* Get the unique Id for the doc and append to the extract url*/
let docId = $("#userSetId").val();
let extractUrl = "http://localhost:8983/solr/techproducts/update/extract/?commit=true&literal.id=" + docId;
/* Ajax call to Solr/Tika to extract text from pdf and index it */
function sendToSolr(fileAsBlob) {
$.ajax({
url: extractUrl,
type: 'POST',
data: fileAsBlob,
cache: false,
jsonp: 'json.wrf',
processData: false,
contentType: false,
echoParams: "all",
success: function(data, status) {
console.log("Ajax.post successful, status: " + data.responseHeader.status + "\t status text: " + status);
console.log("debug");
},
error: function(data, status) {
console.log("Ajax.post error, status: " + data.status + "\t status text:" + data.statusText);
},
done: function(data, status) {
console.log("Ajax.post Done");
},
});
}
});
$("#solrGet").click(function(event) {
event.stopPropagation();
event.preventDefault();
let docId = "id:" + $("#docId").val();
$.ajax({
url:"http://localhost:8983/solr/techproducts/select/",
type: "get",
dataType: "jsonp",
data: {
q: docId
//wt: "json",
//indent: "true"
},
jsonp: "json.wrf",
//"json.wrf": "?",
success: function(data, status) {
renderDoc(data, status);
},
error: function(data, status) {
console.log("Ajax.get error, Error: " + status);
},
done: function(data, status) {
console.log("Ajax.get Done");
}
});
console.log("Debug");
});
let renderDoc = function(theText, statusCode) {
let extractedText = theText.response.docs[0].content[0];
let extractedLinks = theText.response.docs[0].links;
let $textArea = $("#textArea");
$textArea.empty();
let sents = extractedText.split('\n')
sents.map(function(element, i) {
let newSpan = $("<span />");
$textArea.append(newSpan.html(element).append("<br/>"));
});
console.log("debug");
};
}

ajax call returning promis and resolve it by the calling function to its value

By now i read somewhere around 6 pages containing documentations and stackoverflow answers but I don't get the method.
My function is by now after reading all the stuff built like this:
async function getFToken(postId){
const response = await $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data:{
action:'get_f_token',
postId: postId,
},
success:function(response) {
}
});
return response;
}
and in my other function is like this:
function getFeedback(postId){
$(".show_company").hide();
$(".show_feedback").show();
$.ajax({
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data:{
action:'get_feedback',
postId: postId,
},
success:function(response) {
var postTitle = '';
for (i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
var test = getFToken(387);
alert(Promise.resolve(test));
};
$("#result").html(postTitle);
}
});
}
is there any chance, that this is a bigger issue because i call a async in another Ajax call trying to retrieve the value? I'm trying to get the string from the first ajax call and hand it to the second function in the ajax call to attach it to the posts i retrieve from WordPress
The alert is giving me [object Promise] but how do i get the value passed from the php script?
php-scrtipt:
//get fToken from specific feedbacks
add_action( 'wp_ajax_get_f_token', 'get_f_token' );
function get_f_token() {
if(isset($_POST['postId'])){
$postId = $_POST['postId'];
}
$fToken = get_post_meta($postId, 'fToken', true);
echo $fToken;
wp_die();
}
Don't use success callbacks when you can use async/await:
async function getFToken(postId) {
return $.ajax({
type: "POST",
url: ajax_object.ajax_url,
data: {
action: 'get_f_token',
postId: postId,
}
});
}
async function getFeedback(postId) {
$(".show_company").hide();
$(".show_feedback").show();
const response = await $.ajax({
// ^^^^^
type: "POST",
dataType: "text json",
url: ajax_object.ajax_url,
data: {
action: 'get_feedback',
postId: postId,
}
});
let postTitle = '';
for (const i in response) {
postTitle += "<h1>" + response[i].post_title + "</h1><br/><br/>" + response[i].ID ;
const test = await getFToken(387);
// ^^^^^
alert(test); // no Promise.resolve, you don't want to alert a promise
}
$("#result").html(postTitle);
}

jqgrid onclickSubmitLocal using ajax

I am using the example here as a starting point. Everything works fine, I can submit the data back to the server and get a response. However I don't know how to connect the callback from the ajax to the jqgrid onclickSubmitLocal. I don't want to use alerts because even if there is an error the row is updated. I would like some how if there is an error the modal edit dialog to show the error and prevent it from updating the row. On success I would like the user to get a message saying data was saved.
Here is the relevant code:
function submitData(rowData){
var dataToSend = JSON.stringify(rowData);
$.ajax({
url: '/save',
type: 'POST',
contentType: 'application/json; charset=utf-8',
data: dataToSend,
dataType: 'json',
success: function (result) {
alert(' successfully saved.');
},
error: function(xhr, status, error) {
alert('Error processing submit ' + xhr.responseText);
}
});
}
I called the previous function from
onclickSubmitLocal = function (options, postdata) {
var $this = $(this), p = $(this).jqGrid("getGridParam"),// p = this.p,
idname = p.prmNames.id,
id = this.id,
idInPostdata = id + "_id",
rowid = postdata[idInPostdata],
addMode = rowid === "_empty",
oldValueOfSortColumn,
newId,
idOfTreeParentNode;
... same as in example from link above
if (postdata[p.sortname] !== oldValueOfSortColumn) {
// if the data are changed in the column by which are currently sorted
// we need resort the grid
setTimeout(function () {
$this.trigger("reloadGrid", [{current: true}]);
}, 100);
}
// !!! the most important step: skip ajax request to the server
options.processing = true;
submitData([postdata]);
},

Restructuring nested ajax calls so variables work

My "value" variables below are not being inherited into the second call. What is the recommended way to reconstruct this so that it works?
First, I get all the data from our data table. Then, I need to get pending changes from a completely different database (change control). I need to display the second data if it exists.
function getData(appid) {
$.ajax({
url: 'services/getData',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data) {
var field1Value = data.field1;
var field2Value = data.field2;
var field3Value = data.field3;
//get pending changes
$.ajax({
url: 'services/getPendingChanges',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data2) {
if (data2.field1 <> '') { field1value = data2.field1 };
if (data2.field2 <> '') { field1value = data2.field2 };
if (data2.field2 <> '') { field1value = data2.field2 };
},
complete: function () {
//set data in UI regardless of whether it came from getData or getPendingChanges
$('#txtField1').html(field1value);
$('#txtField2').html(field2value);
$('#txtField3').html(field3value);
}
})
}
})
}
of course when I do this, all the "*value" variables are undefined.
Unsure whether this will help you at all (and it probably won't), but this is what I've learned in my time in Javascript. But the nature of anon classes in javascript are so that you can use them without worry of variable collisions. The easiest way is that you funnel up to a higher scope variable to use later. But that's generally bad practice... So you could throw a wrapper around all that...
I ended up hiding the fields then calling the second ajax from the complete of the first. I set the fields in the success of the first call and also in the success of the second call, if they exist. Then I unhide them in the complete of the second.
function getData(appid) {
$('#txtField1').hide();
$('#txtField2').hide();
$('#txtField3').hide();
$.ajax({
url: 'services/getData',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data) {
var field1Value = data.field1;
var field2Value = data.field2;
var field3Value = data.field3;
$('#txtField1').html(field1value);
$('#txtField2').html(field2value);
$('#txtField3').html(field3value);
},
complete: function () {
//get pending changes
$.ajax({
url: 'services/getPendingChanges',
type: 'GET',
data: { 'appid': appid },
dataType: 'json',
success: function (data2) {
if (data2.field1 <> '') {
field1value = data2.field1
$('#txtField1').html(field1value);
};
if (data2.field2 <> '') {
field2value = data2.field2
$('#txtField2').html(field2value);
};
if (data2.field3 <> '') {
field3value = data2.field3
$('#txtField3').html(field3value);
};
},
complete: function () {
$('#txtField1').show();
$('#txtField2').show();
$('#txtField3').show();
}
})
}
})
}
Ultimately instead of hiding them I would swap them out with a loading indicator. Also, I realize the BEST thing to do would be have a single web service that did all the logic in the background and just returned the appropriate data.

CFWheels Pagination using AJAX

I've searched the entire Internet, all of it, and cannot find an answer to this.
I'm using the ColdFusion CFWheels Framework to query a database. The query is done via AJAX like this:
var id = $("#ship-id").val();
$.ajax({
type: "POST",
url: "/my-controller/my-method?format=json",
data: {shipId: id},
dataType: "json",
success: function(response) {
var resultHtml = '';
$.each(response, function(i, value) {
resultHtml += '<tr><td>' + value.FIRSTNAME + ' ' + value.LASTNAME + '</td></tr>';
});
$("#my-table").html(resultHtml);
}
});
I need to paginate that result set. In CFWheels you normally do that by setting the handle, page, perPage and order values in the query like this:
var order = model("order").findAll(
select="id, firstname, lastname, email",
where="orderid IN (#ValueList(orders.id)#)",
handle="ordersQuery",
page=params.page,
perPage=5,
order="lastname"
);
Then you just put this line in your view:
<cfoutput>#paginationLinks(handle="ordersQuery")#</cfoutput>
But... how in the heck can you get pagination to work with an AJAX call?
I think that something along these lines might be your answer (notice I removed the url and added those params to data ...
$.ajax({
type: "POST",
data: {
shipId: id,
controller: myController,
action: myAction,
page: params.page,
},
dataType: "json",
success: function(response) {
var resultHtml = '';
$.each(response, function(i, value) {
resultHtml += '<tr><td>' + value.FIRSTNAME + ' ' + value.LASTNAME + '</td></tr>';
});
$("#my-table").html(resultHtml);
}
});

Resources