I have a search function which executes on keyup. The messages could be
Shows loading when there are results
Reloads full table when user deletes values or does not add any chars to the search field. (This scenario recalls on the displayRecords() function.)
Tells the user there are no results.
I cannot seem to get the third scenario to work. My current code will shows "These are your search results..." and it will call the function to populate the table displayRecords() if the user deletes the chars they have entered. How can I get the program to take all 3 of my scenarios into its logic.
$("#itemID").keyup(function (){
var url = searchPath;
$.ajax({
type : "POST",
async : false,
url : url,
data: $('#itemID').serialize(),
cache : false,
success: function(html) {
$( "#productResults" ).html( html );
if (html === null) {
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('These are your search results... <img src="../wp-content/uploads/2016/02/loading.gif" alt="Loading">').show();
}
if( !$('#itemID').val() ) {
displayRecords(limit, offset);
}
html = null;
window.busy = false;
}
});
});
probably your variable html is not null, using jQuery.trim() to remove extra whitespaces from your response data, so that you can check for emptiness, as
..
if ($.trim(html) === '') { //check if its blank
$("#loader_message").html('<p>There were no results that match your search criteria</p>').show();
} else {
$("#loader_message").html('These are your search results... <img src="../wp-content/uploads/2016/02/loading.gif" alt="Loading">').show();
}
..
Related
I am using Twitter Typeahead (v0.11.1). I have configured an ajax call to get suggestion list upon typing each letter in textbox.
On entering every character an ajax call gets send and it brings results. If typed continuously in textbox then previous ajax calls are aborted and new ajax call is sent on pause of last character entered.
So, while this process if found some results after two characters and paused then it showing suggestion list. Now, if continue to type then exiting list goes away.
I would like to retain suggestion list for each ajax call till user not selected an item from it.
Below is the code used:
var typeahead_pre_written_xhr = null;
var helper_typeahead = $( "#input-box" ).typeahead({
highlight: true,
minLength: 0
},
{
name: "Search Suggestions",
display: ["title"],
templates: {
empty: function () {
return '<div class="tt-suggestion tt-selectable">No matching helper comment found</div>';
}
},
source: function (query, processSync, processAsync) {
if( typeahead_pre_written_xhr != null ) {
typeahead_pre_written_xhr.abort();
typeahead_pre_written_xhr = null;
}
action_url = "suggestion_list";
return typeahead_pre_written_xhr = $.ajax({ cache: false
, url: action_url + query
, type: 'POST'
, data: { 'search': query }
, dataType: 'json'
, success: function (data)
{
return processAsync(data.res);
}
});
}
}).bind("typeahead:selected", function(evt, item) {
// do some stuff
});
In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_tags').on("change", function(e) {
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag " + e.added.id + "?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.
I have a jquery something like
$(document).ready(function() {
$('#value').change(function() {
$.ajax({
type:'POST',
url:'../validation.php',
data: {
validate_year:$('#Year').val(),
validate_value:$('#value').val(),
validate_domain:$('#Domain').val(),
},
success: function (data) {
}
})
});
});
in validation.php I have a sql statement which basically uses whatever is in Year, value and domain and then runs a select statement and the result is then rendering into a table in the same validation.php using echo $something in the table <tr>. What I want to do this display the validation.php to the user so the can see this table... because so they can make changes to it such as update and delete.
How can I do this?
Could try something like this
$(document).on('change', '#value', function() {
$.post('/validation.php', {validate_year:$("#Year").val(),
validate_value:$("#value").val(),
validate_domain$("#Domain").val()}, function(data) {
//Take the output of validation.php and put them into a class or id target
$(".target-area").html(data);
}
});
Basically what is happening is that the $.post function is reaching out to a URL that you specify, in this case validation.php. I am guessing that you are trying to return something to the javascript file that indicates whether something is valid or not. So for example
//valiation.php
<?php
$validate_year = $_POST['validate_year'];
$validate_value = $_POST['validate_value'];
$validate_domain = $_POST['validate_domain'];
//Do something here to determine if it is valid or not
//If the result is $valid in this pseudo code example
if($valid) {
echo 'true';
} else {
echo 'false';
}
In this example, the PHP script is returning a value of true or false based on the checks that you made against a database, expected results, etc, etc to the posted variable, in this case it is returned as the data variable in javascript.
So if you did something like this,
$(document).on('change', '#value', function() {
$.post('/validation.php', {validate_year:$("#Year").val(),
validate_value:$("#value").val(),
validate_domain$("#Domain").val()}, function(data) {
//Take the output of validation.php and log it to the console
console.log(data);
}
});
You would see the true or false result from the validation.php file I wrote. You probably want to return something to notify the user whether or not the validation failed or succeeded. So to expand on this, say you had a div on your page setup like this
<div id="validation-result"></div>
Your javscript would interpret the response from validation.php and output something to the user ... like this
$(document).on('change', '#value', function() {
$.post('/validation.php', {validate_year:$("#Year").val(),
validate_value:$("#value").val(),
validate_domain$("#Domain").val()}, function(data) {
//Take the output of validation.php, parse it and update the page
if(data == 'true') {
var content = "Your validation succeeded";
} else {
var content ="Your validation failed";
}
$("#validation-result").html(content);
}
});
And the final result on your page would look like this for true
<div id="validation-result">Your validation succeeded</div>
or this for false
<div id="validation-result">Your validaiton failed</div>
Hope that help clears up the answer a little bit for you
Okay, so I have an AJAX function that sends data to the .php file, which processes it (simple as that):
$(document).on('click','#submit',function () {
var title = $('#title_submit').val();
var content = $('#content_submit').val();
var image = $('#image_url').val();
$.ajax({
type: "POST",
url: "../parts/add.php",
data: {
title: title,
content: content,
image: image
},
success: function (data) {
redirect(); //a function that redirects to the main page
}
});
});
The content passes fine, and the function processes it. So, if there is no image ("image_url" field is empty) it simply ignores it and just adds the title and the content... But if there is an image it checks it's type (switch ($info) { case 'image/jpg':...) if none of them match:
default:
$new_name = "";
break;
}
and here's the hard part (for me):
if ($new_name == "") {
...//stop from executing and say "That ain't no image you be sendin'";
} else { //continue with adding an image to the folder and than creating a thumbnail of it...
I tried die() but if I entered something like "11111111111111111111111" into the Image URL input it entered "11111111111111111111111" into the database and outputed it instead of the image.
You are checking wrong way, its like assigning empty string to $name use == operator to check against empty string
if ($new_name == "") {
Im performing an ajax query to check the name of a car in a mysql database, if a car is found it will return "Car name unavailable", otherwise "Car name available". This text is put into a div with an id of "checkname".
All this runs fine, but when I try to hide the add button if the car name is unavailable it fails to do so and I dont know why :/
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
}
});
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
Any code that relies on the response from the AJAX request, must be called inside a callback to the request.
function check_name() {
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function (html) {
$("#checkname").html(html);
// I placed your code here instead.
// Of course you wouldn't need to set and then get the HTML,
// since you could just do a direct comparison.
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml == compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
The reason is that by default, an AJAX request is asynchronous, which means that the code that comes after the request will execute immediately instead of waiting for the response to return.
Another possible issue when comparing HTML to keep in mind is white space. If you're doing a string comparison, it must be exactly the same, so if there's whitespace, you'll need to trim it first. You can use jQuery.trim()(docs) to do this.
You have to put the code inside of you AJAX requests success callback, otherwise it will be called before the AJAX call has completed. Putting it inside the success callback means that the code containing the IF statement will only run after the AJAX call has completed. Try:
function check_name(){
$.ajax({
type: "POST",
url: "http://localhost/Framework/library/php_files/check_car_name.php",
data: "carName=" + document.getElementById("carName").value,
success: function(html){
$("#checkname").html(html);
var currentHtml = $("#checkname").html();
var compareString = "Car name unavailable";
if (currentHtml==compareString) {
$("#submit").hide();
} else {
$("#submit").show();
}
}
});
}
You could probably solve the problem doing what patrick dw suggested (it's likely that the ajax call has not been completed yet (i.e. div content wasn't updated) and the check returns false), but since string comparison can really bring to many errors (like string not matching because of newlines, trailing spaces, case sensitiveness, etc...) I would suggest you use another comparison method.
For example you could add a class using .addClass() if the car is found, and then checking if that div has the "found" class using .hasClass()
I use .post(). The third argument of post() is the returned data from the file where the data was posted.
I pass to validate.php the inputed email address, validate.php checks it and if it is valid, it returns 1.
$('a.post').click(function() {
$.post('validate.php',{email : $("#email-field").val()},
function(data){
if(data==1)
{
//do something if the email is valid
} else {
//do other thing
});
});
Hope this helps.