This particular code performs a live AJAX search of the student names. It works on the keyup function.
This script is performing AJAX while I press the Backspace key and loading the search.php file.
I don't want this function to work on any keys but only alphabet.
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function() {
var search = $(this).val();
if (search != '') {
load_data(search);
} else {
load_data();
}
});
});
This is all I learned so far so if there's any other method to do this it will be helpful. Thank You.
Give this a try:
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(ev) {
var searchString = $(this).val();
if (searchString != '') {
var letters = /^[A-Za-z]+$/;
if (searchString.match(letters)) {
load_data(searchString);
} else {
load_data();
}
}
});
});
-- Edit -- per your comment, the below code will return a sliced value; removing the last or invalid character from our search.
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(ev) {
var searchString = $(this).val();
if (searchString != '') {
var letters = /^[A-Za-z]+$/;
if (searchString.match(letters)) {
load_data(searchString);
} else {
searchString = searchString.substring(0, searchString.length - 1);
$('#search_text').val(searchString);
}
}
});
});
-- Edit (3rd request) the below code will clear your result div is the last keyup has determined that the search input box is empty (contains no value).
$(document).ready(function() {
load_data();
function load_data(query) {
$.ajax({
url: "search.php",
method: "POST",
data: {
query: query
},
success: function(data) {
$('#result').html(data);
}
});
}
$('#search_text').keyup(function(ev) {
var searchString = $(this).val();
if (searchString != '') {
var letters = /^[A-Za-z]+$/;
if (searchString.match(letters)) {
load_data(searchString);
} else {
searchString = searchString.substring(0, searchString.length - 1);
$('#search_text').val(searchString);
}
} else {
$('#result').html('');
}
});
});
Related
I want the html value of AJAX in outside of AJAX Call or in the $('#username').blur(function() function.. Is this possible ?
<script>
$(document).ready(function() {
$('#username').blur(function() {
var username = $(this).val();
availibilityCheck(username);
})
function availibilityCheck(username) {
var result = "";
$.ajax({
url: "action.php",
method: "POST",
data: {
action: "availibilityCheck",
data: username
},
dataType: "text",
success: function(html) {
$('#usernameresponse').html(html);
}
})
}
});
</script>
<script>
$(document).ready(function() {
$('#username').blur(function() {
var username = $(this).val();
availibilityCheck(username);
var return_first;
function callback(response) {
return_first = response;
//use return_first variable here
}
})
function availibilityCheck(username) {
var result = "";
$.ajax({
url: "action.php",
method: "POST",
data: {
action: "availibilityCheck",
data: username
},
dataType: "text",
success: function(html) {
callback(html);
$('#usernameresponse').html(html);
}
})
}
});
</script>
I need to show a confirm box before performing this ajax request.
$(document).on("click", ".deletecustomer", function() {
var id = $(this).attr("id");
$.ajax({
method: "post",
url: "deletecustomer.php",
data: {
id: id
},
success: function(data) {
console.log(data);
if (data == "success") {
window.location.href = "customer.php";
}
}
});
});
$(document).on("click", ".deletecustomer", function() {
if (confirm('Are you sure?')) {
var id = $(this).attr("id");
$.ajax({
method: "post",
url: "deletecustomer.php",
data: {
id: id
},
success: function(data) {
console.log(data);
if (data == "success") {
window.location.href = "customer.php";
}
}
});
}
});
I am trying to use Wikipedia's API to make a search query, then append those results to my page. This is what I have so far :
"use strict";
$(document).ready(function(){
function searchWikipedia(searchCriteria){
$.getJSON('https://en.wikipedia.org/w/api.php?action=query&format=json&limit=15&callback=?&titles=' + searchCriteria, processResult);
}
$('#btn').click(function searchCriteria() {
var searchCriteria = $("input[name=Wikipedia]").val();
searchWikipedia(searchCriteria);
})
function processResult(apiResult){
if (apiResult.query.pages[-1]){
console.log("No results");
} else {
for (var i = 0; i < apiResult.length; i++){
$('#display-result').append('<p>'+apiResult+'</p>');
}
}
}
});
So far nothing appends to my html and there's no errors in my console.
#Ali Mamedov's answer is the way to go (it's from Wikipedia)
But the wikipedia link is missing the http:. Also, you can handle the response on your function:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: 'http://en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: processResult
});
});
});
function processResult(apiResult){
for (var i = 0; i < apiResult.query.search.length; i++){
$('#display-result').append('<p>'+apiResult.query.search[i].title+'</p>');
}
}
<script type="text/javascript">
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=opensearch&search=" + txt + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
$.each(data, function (i, item) {
if (i == 1) {
var searchData = item[0];
WikipediaAPIGetContent(searchData);
}
});
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
function WikipediaAPIGetContent(search) {
$.ajax({
type: "GET",
url: "http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text§ion=0&page=" + search + "&callback=?",
contentType: "application/json; charset=utf-8",
async: false,
dataType: "json",
success: function (data, textStatus, jqXHR) {
var markup = data.parse.text["*"];
var blurb = $('<div></div>').html(markup);
// remove links as they will not work
blurb.find('a').each(function () { $(this).replaceWith($(this).html()); });
// remove any references
blurb.find('sup').remove();
// remove cite error
blurb.find('.mw-ext-cite-error').remove();
$('#results').html($(blurb).find('p'));
$('#results').html(blurb);
},
error: function (errorMessage) {
alert(errorMessage);
}
});
}
</script>
Try this sample:
$(document).ready(function(){
$('#btn').click(function() {
$.ajax({
url: '//en.wikipedia.org/w/api.php',
data: { action: 'query', list: 'search', srsearch: $("input[name=Wikipedia]").val(), format: 'json' },
dataType: 'jsonp',
success: function (x) {
console.log('title', x.query.search[0].title);
}
});
});
});
Source
This will show the query result with image:
$(document).ready(function(){
$('#btn').click(function() {
var search_text = $("input[name=Wikipedia]").val();
var url = 'https://en.wikipedia.org/w/api.php?format=json&action=query&generator=search&gsrnamespace=0&gsrlimit=10&prop=pageimages|extracts&pilimit=max&exintro&explaintext&exsentences=1&exlimit=max&gsrsearch=';
$.getJSON( url + search_text +'&callback=?',function(data){
for(var key in data.query.pages){
var titleArt = data.query.pages[key].title;
var extractArt = data.query.pages[key].extract;
var linkArt = 'https://en.wikipedia.org/?curid=' + data.query.pages[key].pageid;
var imgArt;
if(data.query.pages[key].hasOwnProperty('thumbnail')){
imgArt = data.query.pages[key].thumbnail.source;
} else {
imgArt = 'http://www.wallpaperup.com/uploads/wallpapers/2014/04/02/319530/big_thumb_e96d0c33f97706bc093572bc613cb23d.jpg';
}
var contentHTML = '<div class="col-md-4"><div class="box-result"><div class="bg-result"></div><div class="box-content center-block"><div class="article-thumbnail"><img src="' + imgArt + '" alt="" /></div><h1>'+ titleArt +'</h1><p>' + extractArt + '</p></div></div></div>';
$('#display-result').append(contentHTML);
}
});
});
});
function Wiki(lang) {
this.lang = lang || "fr";
this.inuse = false;
}
Wiki.prototype.research = function(s, callback) {
if (this.inuse) {
console.error("Wiki est déjà en cours d'utilisation !");
} else {
this.inuse = true;
var r = new XMLHttpRequest();
r.onload = function() {
Wiki.prototype.inuse = false;
var j = JSON.parse(r.responseText);
callback(j);
}
r.open('GET', "https://" + this.lang + ".wikipedia.org/w/api.php?%20action=opensearch&format=json&origin=*&profile=normal&search=" + encodeURIComponent(s));
r.send();
}
}
var c = new Wiki();
c.research("Victor Hugo", function(result) {
console.log(result);
});
//EXEMPLE
var c = new Wiki("en");
c.research("Victor Hugo", function(result) {
console.log(result);
}
Here's my code:
First the execution of the program comes here:
refreshTree(function() {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh();
}
});
});
Here's the definition of refreshTree():
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
if (data == 'True') {
isOk = false;
}
callback();
}
});
}
And here's the refresh() method:
function refresh() {
if (isOk) {
//do something
}
}
The problem is, I don't know how to get the isOk variable in refresh(). Is there some way to send the variable to refresh(), without it being a global variable?
You capture it in a closure here:
refreshTree(function(isOk) {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh(isOk);
}
});
});
And pass it in here:
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
if (data == 'True') {
isOk = false;
}
callback(isOk);
}
});
}
and here:
function refresh(isOk) {
if (isOk) {
//do something
}
}
Simply Pass it as parameter:
refreshTree(function(status) {
$.ajax({
type: "POST",
url: "/ControllerName/MethodName1",
success: function (data) {
refresh(status);
}
});
});
refreshTree() function:
function refreshTree(callback) {
var isOk = true;
$.ajax({
type: "GET",
url: "/ControllerName/MethodName2",
success: function(data) {
var isOk=true;
if (data == 'True') {
isOk = false;
}
callback(isOk);
}
});
}
Refresh() method:
function refresh(status) {
if (status) {
//do something
}
}
The question is that the controller can give json or html piece. How to know what is it?
$(document).on("submit", "form.client-form", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
if (result is json) {
...
} else if (result is html) {
$("#result").html(result);
}
}
});
});
Another solution...found here: jquery how to check response type for ajax call
$(document).on("form.client-form", "submit", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function(result, status, xhr){
var ct = xhr.getResponseHeader("content-type") || "";
if (ct.indexOf('html') > -1) {
//html here
$("#result").html(result);
}
if (ct.indexOf('json') > -1) {
//json here
}
}
});
});
How about using converters? Take a look at Using Converters on jquery ajax api: http://api.jquery.com/jQuery.ajax/
$(document).on("form.client-form", "submit", function () {
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (result) {
try {
var response = $.parseJSON(result);
}
catch (ex){
//something else
$("#result").html(result);
}
}
});
});