Posting a pdf to Solr using Ajax - 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");
};
}

Related

merge ajaxform with ajax to upload image

I try to create upload photos in my nodejs site.
I used this code to choose file and upload the image:
var fileData = null;
function loadFile() {
var preview = document.querySelector('file');
var file = document.querySelector('input[type=file]').files[0];
var reader = new FileReader();
reader.onloadend = function () {
fileData = file;
}
if (file) {
reader.readAsDataURL(file);
}
}
function uploadFile() {
data = new FormData();
data.append('file', fileData);
$.ajax({
url: "/post_pdf/",
type: "POST",
data: data,
enctype: 'multipart/form-data',
processData: false,
contentType: false,
success: function(data) {
document.getElementById("result").innerHTML = 'Result: Upload successful';
},
error: function(e) {
document.getElementById("result").innerHTML = 'Result: Error occurred: ' + e.message;
}
});
}
With loadfile funcion i choose my image, and with Uploadfile function i upload the image with ajax.
if i use it alone its work perfect and upload the image to the location.
but when i try to add this code to my code, it make alot of errors.
in my code i send to back end all the forms in the pug file:
$('#account-form').ajaxForm({
error : function(e){
if (e.responseText == 'title-empty'){
av.showInvalidTitle();
}
},
success : function(responseText, status, xhr, $form){
if (status == 'success')
{
$('.modal-alert').modal('show');
console.log(responseText)
}}
});
i try to merge the ajaxform with the ajax but when i merege the formdata or i send in ajaxform the data of the file is send error.
how can i merge the codes?
thanks for helping.
Try to submit form it will submit form with your image.
let form = $("#form_id");
$.ajax({
url : $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
success:function(data){
},
error: function (xhr, status, e) {
}
});
#Yogesh Patel
when i use this code:
$('#account-form-btn2').on('click', function(e) {
let form = $("#account-form");
$.ajax({
url: $(form).attr("action"),
type: "POST",
dataType: "json",
processData: false,
contentType: false,
cache: false,
data: new FormData(form[0]),
error: function (e) {
if (e.responseText == 'title-empty') {
av.showInvalidTitle();
}
},
success: function (responseText, status, xhr, $form) {
if (status == 'success') {
$('.modal-alert').modal('show');
}
}
});
});
for some reason it sends the values to "routes" three times.
and it doesn't catch the erorrs or success.
and it sends me to a white window with the value of the callback.
if needed, i can send the function that gets the values and returns them (app.post).

File upload using jquery/ajax for REST API

I was trying to upload file to a remote server using REST api by ajax/jquery with the following script, but it returns 400 error with a Bad request. I have tested the end point with curl, which is giving correct response and file is being uploaded.
$(document).ready(function () {
$("#btnSubmit").click(function (event) {
//stop submit the form, we will post it manually.
event.preventDefault();
fire_ajax_submit();
});
});
function fire_ajax_submit() {
// Get form
var form = $('#fileUploadForm')[0];
alert(form.files[0]);
var data = new FormData(form);
data.append("CustomField", "This is some extra data, testing");
$("#btnSubmit").prop("disabled", true);
$.ajax({
type: "POST",
enctype: 'multipart/form-data',
url: "http://10.13.20.166:5332/fileUploadtoFolder",
data: data,
processData: false,
contentType: false,
cache: false,
timeout: 600000,
success: function (data) {
$("#result").text(data);
console.log("SUCCESS : ", data);
$("#btnSubmit").prop("disabled", false);
},
error: function (e) {
$("#result").text(e.responseText);
console.log("ERROR : ", e);
$("#btnSubmit").prop("disabled", false);
}
});
}
Change your code 👇
var data = new FormData(form);
Use this code 👇
// Create an FormData object
var data = new FormData(document.getElementById("fileUploadForm"));
Try again

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]);
},

display values returned by json

I have simple question to display data on html page. Following code displays array of json data on screen. but, I want to display it by each element such as "url", "img_url" and so on.
could you please let me know who to do it ?
ajax code
var dataString = 'url=' + pathname + '&img_name=' + img_name + "&tag=" + tag;
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
complete: function (xhr, status) {
if (status === 'error' || !xhr.responseText) {
//handleError();
alert("error");
} else {
var data = xhr.responseText;
$('#tt').html("<div id='message'></div>");
$('#message').html(data);
}
}
});
json return
{"cid":"14","url":"http:\/\/localhost\/","img_url":"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg","img_name":"mat_173317134c.jpg","html":"<div id=\"hotspot-19\" class=\"hs-wrap hs-loading\">\r\n<img src=\"http:\/\/static.naver.net\/www\/up\/2013\/0305\/mat_173330634c.jpg\">\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"95\" data-y=\"64\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nasdf\r\n<\/div>\r\n<div class=\"hs-spot-object\" data-type=\"spot\" data-x=\"168\" data-y=\"53\" data-width=\"30\" data-height=\"30\" data-popup-position=\"left\" data-visible=\"visible\" data-tooltip-width=\"200\" data-tooltip-auto-width=\"true\">\r\nrere\r\n<\/div>\r\n<\/div>\r\n","jscript":""}
$.ajax({
type: "POST",
url: "image_finder.php",
data: dataString,
dataType: 'json',
success: function (data) {
for(var item in data){
console.info(item);//print key
console.info(data[item]);//print value
}
}
});
I hope this is what you need.

synonym api Ajax call return

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.

Resources