I am using elasticsearch 1.2.1 and I want to do a search from javascript with several fields, for instance, by title and content.
My code is:
var data = { q: 'title: test};
$.ajax({
data: data,
url: http://localhost:9200/_search,
type: 'GET',
success: function (data) {
$.each(data.hits.hits, function(position,hit) {
$("#<portlet:namespace/>search-pattern").append( '<li>' + hit._source.title + '</li>' );
});
}
});
But in addition to search for a title also want to look for the content field.
What should be the value for the attribute data in order to search not only by the field 'title' but also by the field 'content'?
Someone can help me?
Thanks in advance
Try to use Request Body Search, specify the conditions using Query DSL
Related
I'm trying to save google's API search results in a Mysql database in localhost.
My problem
I'm using a for loop to show every possible result from book research, such as "Harry Potter".
I do this with AJAX and then I cycle the results.
The main problem is that if I want to save one of the results, what is saved is just the last one because every variable is overwritten during every cycle.
Here is the code, saveBook.php is just a .php file where I do an insert into query.
$.ajax({
url:"https://www.googleapis.com/books/v1/volumes?q=" + search,
dataType: "json",
type: 'GET',
success: function(data){
for(i=0; i < data.items.length; i++)
{
title = $( '<p> ' + data.items[i].volumeInfo.title + '</p>');
author = $('<p> ' + data.items[i].volumeInfo.authors + '</p>');
img = $('<img><a href=' + data.items[i].volumeInfo.infoLink +
'><br></br><button>Read More</button></a>' );
url= data.items[i].volumeInfo.imageLinks.thumbnail;
save = $('<br><button onclick="save()">Save</button></br>
</br>');
img.attr('src',url);
title.appendTo("#result");
author.appendTo("#result");
img.appendTo("#result");
save.appendTo("#result");
}
},
});
}
}
function save(){
$.ajax({
type:'POST',
data: {
url: url,
title: title,
author: author,
},
url: "saveBook.php",
success: function(data){
alert("Success!");
location.replace("home.php");
}
})}
Another problem is:
how should I use this JSON
data: {
url: url,
title: title,
author: author,
},
to actually return a string with title and author, because url is correctly saved.
I've had some time to think over your project. While I'm not sure of all of your project requirements, a fundamental pursuit should be to minimize the calls to the api. For this reason, let your users search via a standard (non-ajax) search input/form and load the api results into the html with php, then use your ajax call to allow multiple save calls from a single load of search results (if that makes sense for your project). Basically, I suppose I am discouraging the auto-reload after saving a single item; otherwise you can avoid ajax again.
Also, as far as I know authors is an array, so you'll need to join/implode the values into a single string.
foreach (json_decode($apijson, true) as $item) {
echo '<div class="book">';
// your other elements in the row
echo "<button onclick=\"save('" ,
htmlspecialchars($item['id'], ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars($item['volumeInfo']['title'], ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars(implode(', ', $item['volumeInfo']['authors']), ENT_QUOTES, 'UTF-8') , "','" ,
htmlspecialchars($item['volumeInfo']['imageLinks']['thumbnail'], ENT_QUOTES, 'UTF-8') , "');\">Save</button>";
echo '</div>';
}
Then these parameters can be directly fed to your ajax function.
Be sure to validate and use sensible data sanitizing techniques and use a prepared statement when you INSERT.
You can return a success message from your ajax, and then hide() the saved row/book.
You can return a vague (not exact) error message if the insert did not make an "affected row".
Problem solved thanks to #mickmackusa. I have declared the variable "save" as a global array and, then, I have passed every string with a proper escape. Now it's working fine! Thank you very much.
save[i] = $('<button onclick="save((\'' + data.items[i].volumeInfo.authors + '\'),(\'' + data.items[i].volumeInfo.title + '\'),(\'' + data.items[i].volumeInfo.infoLink + '\'))">Save</button><br><br>')
My client has a jobs board whose API data I'm pulling via Ajax. I can parse the "jobs" data but cannot seem to pull any thing else. For instance, this works to pull the names of job listings to a select box:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
$.each(json.jobs, function(i, value) {
$('#myselect').append($('<option>').text(value.title).attr('value', value.title));
});
}
});
But when I change "json.jobs" to anything else like "json.offices" or "json.locations" nothing is pulled. How do I go about accurately targeting these data strings to cull together for a complete careers page? Appreciate any guidance whatsoever thanks.
This is the JSON if you need to take a look:
https://api.greenhouse.io/v1/boards/roivantsciences/jobs/
try pull location.name for all jobs $.each(json.jobs, function(i, value) { $('#myselect').append($('<option>').text(value.location.name).attr('value', value.location.name)); });
Ive done a small test:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
console.log(json)
}
});
What I got back from console is that your json object only has 'jobs' as the top attribute in it.
You have to go through it like this to get locations:
$.each(json.jobs, function(i, value) {
console.log(value.location);
});
then you have the location object inside this you got the attribute 'name'
so u can get the names with value.location.name
I am desperately trying to submit multiple POST variables via AJAX, but just cant get manage to get the formatting right... Problem is that I have both a hardcoded / written action=problem_lookup variable and a dynamic field input as $(this).val and just cant manage to get both into one data string...
this works well:
data: 'problem=' + $(this).val(),
This does not:
data: { action: 'problem_lookup' , problem: $("problem").val() },
data: { action: 'problem_lookup' , problem: $(this).val() },
data: { action: problem_lookup, problem: $(this).val() },
I tried numerous formats from other threads and looked at the official jquery manual, but cant seem to get this figured out. Any help is appreciated.
EDIT:
full script below, tried the solutions posted so far but no success. $("problem") is a <select> field (with Select2 running) hence shouldnt cause me so much frustration, especially since the original approach with data: 'problem=' + $(this).val(), works fine.
$(function () {
$('#problem').change(function () { // on change in field "problem"
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
$.ajax({ // launch AJAX connection
type: 'POST', // via protocol POST
url: 'ajax.php',
//data: 'problem=' + $(this).val(), // send $_POST string
//data:"{'action':'"+action+"','problem':'"+$(this).val()+"'}",
//data:"{'action':'problem_lookup','problem':'"+$(this).val()+"'}",
//data: { action: 'problem_lookup' , problem: $("problem").val() },
//data : data_string,
data: $.param(data),
dataType: 'json', // encode with JSON
success: function (data)
{
// do something
},
});
});
});
An issue is in the
$("problem")
Jquery call.
If.problem is a css class try with
$(".problem")
if problem is a css id try with
$("#problem")
For posting arrays of object you can build data as an object containing arrays, changing a little bit your structure. Something like this
Var obj={};
obj.postData=[];
obj.postData.push(/*your first object here*/);
...
obj.postData.push(/*your n-th object here*/);
$.ajax({
.....
data:obj;
......
});
Try the FormData() FormData.
var data = new FormData();
data.append('action', value);
...
You need to specify your data variable first like this:
var data = {
action: 'problem_lookup',
problem: $("problem").val()
}
In AJAX serialize your data using $.param,
data: $.param(data),
Note: Twice check if $("problem").val() is correct. If problem is a class, you need to specify like this $(".problem").val() or if it is ID, $("#problem").val()
I have two pages customer.aspx and customer_detail.aspc, each with their corresponding code behind files. The objective is being able to send a particular table cells's value from customer to customer_detail. For example, the following javascript renders the table dynamically onto customer.aspx based on the BindTable method in customer.aspx.cs file.
customer.aspx:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "customer.aspx/BindCustomer",
data: "{}",
dataType: "json",
success: function(data) {
for (var i = 0; i < data.d.length; i++) {
$("#customer_table").append("<tr><td>"+'<a id = "anchor" href="customer_individual.aspx">' + data.d[i].customer_name +'</a>'+ "</td><td>" + data.d[i].customer_id +"</td><td>" + data.d[i].total_value + "</td><td>" + data.d[i].created_date + "</td></tr>");
}
},
error: function(result) {
alert("Error");
}
});
});
The BindCustomer function above is a WebMethod written in customer.aspx.cs, which returns a customer array object, customer[], which is bound to the customer_table. Notice that, in the above I have a href within the first td element of the table, which redirects the page to the customer_detail.aspx.
The objective is to be able to send say a customer_name value upon clicking the link to the customer_detail.aspx.cs, so that I can query the customer object which I store separately, with the name and populate the page accordingly. What would be the best method to accomplish this? Any suggestions as to how to proceed will be greatly helpful!
The easiest way is to format a link to customer_detail.aspx with the data you want to pass in the querystring like this (it looks very similar to what you're already doing.)
Link
When customer_detail.aspx loads, you retrieve the value from the querystring.
In your Page_Load event in customer_detail.aspx
var customerName = Request["customerName"];
You could be more particular and say Request.Querystring["customerName"] but on this page you probably don't care whether the value was passed in the querystring or a form field. Request["customerName"] covers both.
I'm trying to check if a user exists in my database and then change the values of my input fields to match that user's information. I have the following code but it doesn't seem to work.
<button onclick="checkAvailability()">Check Availability</button>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function checkAvailability()
{
$(function()
{
$.ajax(
{
type: 'POST',
url: 'test.php',
data: "name=" + $("#name").val(),
dataType: 'json',
success: function(row)
{
$('#name').val(row[0]);
$('#address1').val(row[1]);
$('#phone1').val(row[2]);
alert('success');
}
});
});
}
</script>
The alert goes off but none of the values are changed. I checked the response using Firebug and the response is a JSON object with the user's information. I'm not sure where the error is. Thank you for any input.
If you have a json object you must use: $("#name").val(row.name);
In case you are getting a json then it might look like this
var json = [{"name": "sample"},{"phone":"sample"},{"address":"sample"}];
When you are doing row[0].
what you get is an object["name":"sample"]
So you must make the following change
success: function(row)
{
$('#name').val(row.name);
$('#address1').val(row.address);
$('#phone1').val(row.phone);
alert('success');
}
Also make sure you have input types with id's name, address1 and phone1