I have build some inputs to let the user search the database. The search is using ajax request.
The problem that I have is because when I get the response from the server I also get the search inputs. I don't want that.
Take a look to my code:.
<script>
$(document).on('change', '.auto-select', function(e){
e.preventDefault();
var tags = $('#auto-tag-script').serialize();
var contracts = $('#auto-contract-script').serialize();
var educations = $('#auto-education-script').serialize();
var towns = $('#auto-town-script').serialize();
runAjax(tags, contracts, educations, towns);
});
function runAjax(tags, contracts, educations, towns) {
$.ajax({
url: 'http://localhost/jobs/public/anazitisi-ergasias?' + tags + '&' + contracts + '&' + educations + '&' + towns
}).done(function(data){
$('div.show-html-from-ajax').html(data);
});
}
</script>
With the above code the inputs appears again in my page.
Is there any way to escape this form inputs.
You can hide it 2 ways...before you insert it (best way) or after you insert it
$.ajax({
url: '...'
}).done(function(data){
// create jQuery object from response
var $html = $(data);
//hide within that object
$html.find('.search-form-for-hide').hide();
// insert the object
$('div.show-html-from-ajax').html($html);
/******* OR ***************/
// the html is in the DOM now, can do whatever might be needed to it
$('.search-form-for-hide').hide();
});
For many plugins you would need to insert first and then call the plugin
With jQuery, you can implicitly convert a DOM object or html string to a jQuery object by using $(data) or jQuery(data) (See this doc). Then use $(data).find('.search-form-for-hide').hide() to find the element and hide it.
Related
I am using Google Books API PHP and would like to change search key word when user types it in order to return immediate title tips. How to implement so that q=what user types right now?
<script src="https://www.googleapis.com/books/v1/volumes?q=harry+potter&callback=handleResponse"></script>
To do this efficiently, remove &callback=handleResponse so the actual response you get back is JSON.
In your javascript set a variable as so:
var request = 'https://www.googleapis.com/books/v1/volumes';
Have a form (containing textarea and submit) handler with something like this:
$('#form').onsubmit(function(e){
e.preventDefault();
var keywords = $('#myTextAreaInputInsideTheForm').val();
$.getJSON(request + '?q=' + keywords, function(data){
//do stuff with the json response
console.log(data);
});
});
Or if you require the XMLHTTPrequest to be called everytime something changes within the textarea
$('#myTextArea').on('keyup', function(){
var keywords = $(this).val();
$.getJSON(request + '?q=' + keywords, function(data){
//do stuff with the json response
console.log(data);
});
});
EDIT: I'm assuming you're using textarea, but <input type="text"/> works as well.
EDIT2: DEMO The demo may not work because google now returns a 403 forbidden. You must not call URL too many times or google will bloc your request. I recommend calling it every couple of letters written. Good luck.
var request = 'https://www.googleapis.com/books/v1/volumes';
$('#myTextArea').on('keyup', function(){
var keywords = $(this).val();
if(keywords.length > 0 && keywords.length % 5 == 0){
$.getJSON(request + '?q=' + keywords, function(data){
//do stuff with the json response
console.log(data);
});
}
});
Using keyup is better than change.
I'm trying to set up a function using jquery/php where a user selects a checkbox in a row with a specific ID (the id matches the primary key of the row data in my database), stores each row ID into an array, and then upon clicking the "compare selected rows" button passes it to a new page where a table of results is displayed with only those selected rows.
each input looks like this
<input type='checkbox' id='$id' class='compareRow'></input>
I am pretty novice at jquery and was planning to use a variation of a previous script I had put together to display dynamic row data in a modal. I am not sure if this code is relevant at all but it also passes the row id to another php page in order to query the database. Mind you this has only been used for single queries in the past where this new function would need some sort of foreach statement at the query level in order to process the array of IDs, im sure.
Heres the script I've been trying to tweak
$(function(){
$('.compareRow').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'query.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
success : function(r)
{
other code?
});
}
});
});
});
I know that there is much more needed here but this is just what I have so far, any help would be greatly appreciated.
Update, so I've created the page and have the following:
in my compareSelected.php I have the following code:
if(isset($_POST['post_id'])){
$compare_received = $_POST['post_id'];
}
print_r($compare_receive);
It returns undefined index.
I also modified the code to change to that page after like so:
$('.compareRowButton').click(function(){
var ids = [];
//loop to all checked checkboxes
$('.compareRow:checked').each(function(){
//store all id to ids
ids.push($(this).attr('id'));
});
$.ajax({
type : 'post',
url : 'compareSelected.php', //query
data : {post_id:ids}, // passing id via ajax
success : function(r)
{
window.location = 'compareSelected.php';
}
});
});
Not sure why it won't pick up the array values.
If you're set on your current implementation, you could maintain a reference to the data returned by each ajax call in the rows array. Later, you could implement a button that fires a function to append the row data to your table. Of course, you may need to parse the data returned by the request prior to appending.
$(function(){
var rows = [];
$('.compareRow').click(function(){
var ele_id = $(this).attr('id');
$.ajax({
type : 'post',
url : 'query.php', //query
data : 'post_id='+ ele_id, // passing id via ajax
success : function(data){
rows.push(data);
}
});
});
$('.displayTable').click(function(){
// append to table or divs
});
});
I would suggest you avoid a page reload here. Or, if you must, make the Ajax request on the following page. You want to avoid tightly coupling your logic between different jQuery modules. Ajax should be utilized to load data asynchronously, without requiring a page reload.
On your code. your sending ajax request everytime you click the checkbox.
better to make another button or something before sending ajax request.
$('SOME_ELEMENT').click(function(){
var ids = [];
//loop to all checked checkboxes
$('.compareRow:checked').each(function(){
//store all id to ids
ids.push($(this).attr('id'));
});
$.ajax({
type : 'post',
url : 'query.php', //query
data : {post_id:ids}, // passing id via ajax
success : function(r)
{
other code?
});
}
});
});
I have an HTML form that I am trying to convert to submitting using the Jquery load() function. I have it working for a single field, but I have spent hours trying to get it to work for multiple fields, including some checkboxes.
I have looked at many examples and there seems to be about three of four ways of approaching this:
Jquery .load()
jquery .ajax()
jquery .submit()
and some others. I am not sure what the merits of each approach is but the first example I was following used the .load(), so that is what I have persisted with. The overall object is to submit some search criterion and return the database search results.
What I have at present:
<code>
// react to click on Search Button
$("#SearchButt").click(function(e){
var Options = '\"'+$("#SearchText").val()+'\"' ;
var TitleChk = $("#TitleChk").prop('checked');
if (TitleChk) Options += ', \"TitleChk\": \"1\"';
// load returned data into results element
$("#results").load("search.php", {'SearchText': Options});
return false; //prevent going to href link
});
</code>
What I get is the second parameter appended to the first.
Is there a way to get each parameter sent as a separate POST item or do I have to pull it apart at the PHP end?
It would seem as if you're stumbling over the wrapper, let's go ahead and just use the raw $.ajax() and this will become more clear.
$("#SearchButt").click(function(e){
var Options = {};
Options.text = $('#SearchText').val();
Options.title = $('#Titlechk').prop('checked')) ? 1: 0; //ternary with a default of 0
$.ajax({
url: 'search.php',
type: 'POST',
data: Options
}).done(function(data){
$('#results').html(data); //inject the result container with the server response HTML.
});
return false;
});
Now in the server side, we know that the $_POST has been populated with 2 key value pairs, which are text and title respectively.
I'm using coldfusion and jquery. This is my first real go at jquery and I've searched and read for a long time without cracking this so any help would be greatly appreciated...
Ok, I have an autocomplete returning an id. I'm then passing the id to a second function that returns an array of datatype json. The autocomplete works great and I can get the json to display in an alert box but am a bit stuck on how to use the json results.
I'm trying to loop through the json array and write the values into radio buttons, which then dynamically display on page... So the whole idea is this.
user is selected from drop box and id is returned
user id from selection is passed to user options function and user options are returned in json arrary.
json array is looped through and on each iteration a radio button is created with appropriate values.
all radio buttons are then output to screen for access and selection.
The code I have so far is this :
<script type="text/javascript">
// <!--
$(document).ready(function() {
$("#userName").autocomplete({
cache:false,
source: "/jqueryui/com/autocomplete.cfc?method=getUser&returnformat=json",
//setup hidden fields
select:function(event,ui) {
var uid = ui.item.id;
$("#userid").val(ui.item.id);
// start call to get user options
$.ajax({
type: "POST",
url: "/jqueryui/com/autocomplete.cfc?method=getUserOptions&returnformat=json",
data: ({ userid: uid }),
success: function(data) {
alert(data)
}
});
/// end call to get user options
}
});
});
// --->
</script>
The json displayed in the "alert(data)" popup, which looks fine, is this :
[{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}]
I need to know how to loop through this data and create a radio button for each option, probably something like this, and display them all on screen, which I'm guessing I'll just write to a via the dom once I have something to write :
<input type="radio" name="userOption" value="#id#|#qty#|#term#">#productname#
I have tried a few things, without success, such as :
for(var i =0;i<Data.length-1;i++)
{
var item = Data[i];
alert(item.productname + item.id);
}
And
$.each(data.items, function(i,item){
alert(item);
if ( i == 3 ) return false;
});
I couldn't get either of these to work.
Anyway this is getting a bit long winded. Hope it's clear, and again any help or suggestions appreciated.
Thanks!
First check the datatype of the data parameter returned. You might first need to use .parseJSON() to construct a JSON object.
Then your for loop syntax is not correct. this code works for me:
var data = [{"productname":"licence free","quantity":1,"term":12,"id":1},
{"productname":"licence basic","quantity":1,"term":24,"id":1},
{"productname":"licence full","quantity":1,"term":12,"id":2}];
for (var i=0; i<data.length; i++) {
alert(data[i].productname);
}
Here's a jsfiddle
Try checking parseJSON jquery function.
I quess that the type is a string? If so try it with the javascript function eval. It converts a string to a javascript type.. in your case something like this should work:
Var new_data = eval(data);
Now it should be a workable array/object
Edit: to stay with the data variable:
data = eval(data);
Edit 2:
Your ajax call misses the dataType property:
dataType: "json"
With this you dont need the stuff above i said
Use a each loop to get data and appendTo function to print data in an HTML element with result1 id:
dataType:"json", //nature of returned data
success: function(data) {
var content = '';
$.each(data, function(i, dbdata) {
content += '<p>' + dbdata.columnName + '<p>';
});
$(content).appendTo("#result1");
}
All,
I have a Jquery ajax request calling out a URL. The ajax response I receive is an HTML form with one hidden variable in it. As soon as my ajax request is successful, I would like to retrieve the value of the hidden variabl. How do I do that?
Example:
html_response for the AJAX call is :
<html><head></head><body><form name="frmValues"><input type="hidden"
name="priceValue" value="100"></form></body></html>
$.ajax({
type: 'GET',
url: "/abc/xyz/getName?id="+101,
cache: false,
dataType: "html",
success: function(html_response)
{
//Extract form variable "priceValue" from html_response
//Alert the variable data.
}
});
Thanks
The html_response you get will be a string. As such, if you happen to know exactly what the page will look like, you can just search the text using indexOf.
...But that solution is messy and error prone. Alternatively, you could create a new HTML element (like a div), put your response html in there, and then obtain the hidden variable as you would access any normal html element.
For example:
var tempDiv = $("<div/>");
tempDiv.append(html_response);
var myValue = tempDiv.find("input[name='priceValue']").val();
You can create JQuery object:
var form = $(html_response);
Then get your input PriceValue using JQuery selectors & traversal.
You can read it with $(html_response).find("input[name='priceValue']").val();