search box result == Json result - javascript

I have a Node.js server that reads a JSON file and there are a lot of information in it. One of them is ID of a person, I have a search box in my HTML page I wanna right a jquery method(ajax required) for the client side to find if the ID that the user put in the search box is the same as the ID in JSON, if it is I wanna return some information about that person, let's say name and username of the user.
Note: I am 100% sure that my server.js file works.
Please help me, I am kind of a newbie in Jquery.
I have so far;
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
url: '/url_of_the_related_server_side',
dataType: 'json'
})
.done(function(data){
console.log(data);
alert(JSON.stringify(data));
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.search_box_ID == any_function_variable_name.name_in_the_JSON_file_for_one_of_the_searched_ID){
$userElement = $("<li>").html("<strong>ID: </strong>" + any_function_variable_name.id); //id is defined in JSON and I was able to use in another part of the jquery
$userBlock = $("<ul>")
.append(
$("<li>").html("<strong>Name: </strong>" + any_function_variable_name.name) //name of the user
)
.append(
$userElement
)
.append(
$("<li>").html("<strong>User User Name: </strong>" + any_function_variable_name.userName)
);
$any_function_variable_nameBlock.insertAfter("#search");
}
});
});})})
Note: I don't know if I could close the brackets right.
Thanks in advance!

I guess you are looking for something like as shown below ...
Instead of making an ajax call, I wrote with static data as below ...
HTML
<input id="searchBox" type="text" />
<button id="id_of_the_search_box_button">
Search
</button>
<ul>
</ul>
JS
var data = [
{
"id": 37595960858,
"in_reply_to_screen_name": null,
"user": {
"id": 2384451,
"id_str": "238678",
"name": "Doga I",
"screen_name": "IDoga"
}
},
{
"id": 65739068412,
"in_reply_to_screen_name": null,
"user": {
"id": 2878009,
"id_str": "235678",
"name": "Jon Doe",
"user_name": "JD"
}
}
];
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
var searchText = parseInt($('#searchBox').val());
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.id === searchText){
$("ul")
.append('<li> <strong>ID: </strong>' + any_function_variable_name.user.id)
.append('<li> <strong>User Name: </strong>' + any_function_variable_name.user.user_name)
.append('<li> <strong>Name: </strong>' + any_function_variable_name.user.name)
.append('<li> <strong>Screen Name: </strong>' + any_function_variable_name.user.screen_name);
} //End if
}); //End forEach
});
});
which makes your ajax call like this ...
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
url: '/url_of_the_related_server_side',
dataType: 'json'
})
.done(function(data){
var searchText = parseInt($('#searchBox').val());
data.forEach(function (any_function_variable_name) {
if(any_function_variable_name.id === searchText){
$("ul")
.append('<li> <strong>ID: </strong>' + any_function_variable_name.user.id)
.append('<li> <strong>User Name: </strong>' + any_function_variable_name.user.user_name)
.append('<li> <strong>Name: </strong>' + any_function_variable_name.user.name)
.append('<li> <strong>Screen Name: </strong>' + any_function_variable_name.user.screen_name);
} //End if
}); //End forEach
});
});
});
Following is the fiddler
https://jsfiddle.net/rrtbz4bo/7/
Enter 37595960858 in search box and hit search.
UPDATE: call the /find/id?id=... api directly if it returns data like
{
"id": 37595960858,
"in_reply_to_screen_name": null,
"user": {
"id": 2384451,
"id_str": "238678",
"name": "Doga I",
"screen_name": "IDoga"
}
}
Then following should work.
$(document).ready(function(){
$("#id_of_the_search_box_button").click(function (any_function_variable_name) {
$.ajax({
type: 'GET',
//Or whatever your URL structure is
url: 'http://127.0.0.1:5230/find/id?Id=' + $('#searchBox').val(),
dataType: 'json'
})
.done(function(data){
$("ul")
.append('<li> <strong>ID: </strong>' + data.user.id)
.append('<li> <strong>User Name: </strong>' + data.user.user_name)
.append('<li> <strong>Name: </strong>' + data.user.name)
.append('<li> <strong>Screen Name: </strong>' + data.user.screen_name);
});
});
});
If this doesn't work, post a fiddler and i'll try and make it work.
Hope this helps ...

Related

jQuery - Getting Correct UserID - AJAX

so I am at a bit of a bind here. So I have 2 jQuery scripts that handle a simple database row update (per the user ID, session), this lets the user send a "Gift" that adds value to the users database row column "bonus".
I got this working practically perfect, but the problem is: It will only get the first ID of the results when gifting, not any other user ID. I suspect this is a fault in the looping logic.
RequestBin tells me I have my correct ID for myself, and the user ID is stuck with the first iterated userid (we cant send to any other user ID). We need to be able to gift any result (user ID).
We use a dialog to trigger the AJAX call with Yes / No. Yes firing the AJAX event, no closing model.
The AJAX JS - Sends value to database
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: 'Gift this user new Gift?',
zIndex: 10000,
autoOpen: true,
width: '600',
height: '200',
resizable: false,
buttons: {
Yes: function () {
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
var sender = $('input[name=sender]').val();
var receiver = $('input[name=receiver]').val();
$.ajax({
url: 'https://xxxxx.m.pipedream.net',
type: 'POST',
data: {
sender: sender,
receiver: receiver
},
beforeSend: function () {
$('#gift-bonus-status').text('Sending...').delay(100).fadeIn().delay(100).fadeOut();
},
success: function (response) {
$('#gift-bonus-status').text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
}
});
},
No: function () {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function (event, ui) {
$(this).remove();
}
});
};
function fetchTopTransfers() {
$(function () {});
$.ajax({
url: '/ajax/ajax_user_list.php',
method: 'GET',
dataType: 'JSON',
success: function (data) {
var html_to_append = '';
$.each(data, function (i, item) {
$('input[name=receiver]').val(item.user_id);
html_to_append +=
'<div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
formatBytesProduct(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\')" id="gift-bonus-status">Give Gift</a></div></div><div style="padding-bottom:5px">' +
item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
item.progress + '%</div></div></div><div style="clear:both"></div><input type="hidden" name="sender" value="<?=$account->getId()?>" /><input type="hidden" name="receiver" value="' +
item.user_id + '" />';
});
$("#top-transfers").html(html_to_append);
}
});
}
fetchTopTransfers();
setInterval(function () {
fetchTopTransfers()
}, 5000);
AJAX responce:
What is happening here???
Any help is much appreciated
As there many inputs with name receiver that's why you are not able to pass correct values. So, inside your ConfirmDialog function pass this as well it will refer to current element which is clicked. Then , inside your function to get required values you can use $(this).closest(".outer").find(..)...
Demo Code :
//just for demo..
var data = [{
"user_id": 1,
"product_id": 12,
"username": "acc",
"name": "swi",
"progress": "20",
"speed": 15
}, {
"user_id": 2,
"product_id": 12,
"username": "acc",
"name": "swi22",
"progress": "10",
"speed": 12
}]
var html_to_append = "";
$.each(data, function(i, item) {
//give outer div.. also pass `this` inside your function
html_to_append +=
'<div class="outer"><div style="float:left"><a href="/details/?id=' + item.product_id + '/"><img src="/images/' +
item.cover + '" style="width:50px;height:75px;margin:5px" /></a></div><a href="/user/?id=' +
item.user_id + '/"><img src="/' + item.avatar + '" style="width:45px;height:45px;border-radius:50%;margin:5px" /></a><div style="float:right;padding:10px;text-align:right"><b>' +
(item.speed) + '</b><div style="padding-top:5px;text-align:right"><span class="material-icons" style="vertical-align:middle;color:#C0C0C0">redeem</span> <a onclick="ConfirmDialog(\'Do you wish to gift ' + item.username + ' with gift? This will deduct 70 points from your current balance.\',this)" >Give Gift</a></div></div><div style="padding-bottom:5px">' +
item.name + '</div><div style="max-width:235px;margin-left:60px;margin-top:-4px;background:#D3D3D3;border-radius:4px;overflow:auto"><div style="height:15px;width:' +
item.progress + '%;background:#E92324;padding:5px;text-align:center;color:#FFF;border-radius:4px">' +
item.progress + '%</div></div><div style="clear:both"></div><input type="hidden" name="sender" value="23" /><input type="text" name="receiver" value="' +
item.user_id + '" /></div>';
});
$("#top-transfers").html(html_to_append);
//add el it refer to `this`
function ConfirmDialog(message, el) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '</h6></div>')
.dialog({
modal: true,
title: 'Gift this user new Gift?',
zIndex: 10000,
autoOpen: true,
width: '600',
height: '200',
resizable: false,
buttons: {
Yes: function() {
$('body').append('<h1>Confirm Dialog Result: <i>Yes</i></h1>');
$(this).dialog("close");
//get closest div(outer) then find required inputs values
var sender = $(el).closest(".outer").find('input[name=sender]').val();
var receiver = $(el).closest(".outer").find('input[name=receiver]').val();
console.log("Reciver --" + receiver + " Sender ---" + sender)
$.ajax({
url: 'https://xxxxx.m.pipedream.net',
type: 'POST',
data: {
sender: sender,
receiver: receiver
},
beforeSend: function() {
//use el here as well..
$(el).text('Sending...').delay(100).fadeIn().delay(100).fadeOut();
},
success: function(response) {
//use el here as well
$(el).text('Gift Sent!').delay(100).fadeIn().delay(100).fadeOut();
}
});
},
No: function() {
$('body').append('<h1>Confirm Dialog Result: <i>No</i></h1>');
$(this).dialog("close");
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" />
<div id="top-transfers">
</div>

Pagination in popup from JSON data

I am looking to add pagination in a pop-up window. I tried looking for a plug in but didn't find anything that would work with a pop-up.I am getting JSON data. the reason is because of the data coming back been too big to even allow the pop-up window to scroll. Has anyone done something like that where I can see how its done. Sample code below.
Thank you!
JSON Data Sample:
[
{
"name" : "Jonathan Suh",
"gender" : "male"
},
{
"name" : "William Philbin",
"gender" : "male"
},
{
"name" : "Allison McKinnery",
"gender" : "female"
},
{
"name" : "Becky Borgster",
"gender" : "female"
},
{
"name" : "Victoria Einsteen",
"gender" : "female"
}
{
"name" : "Suh EH",
"gender" : "male"
},
{
"name" : "Mar Lee",
"gender" : "female"
},
{
"name" : "Croc Dyllo",
"gender" : "male"
},
{
"name" : "Auter Naddo",
"gender" : "male"
},
]
JS code:
$("document").ready(function(){
$('#myForm').submit(function(e) {
// To stop the default behavior, a # will be added to the URL in the address bar.
e.preventDefault();
var datastring = $("#myForm").serialize();
$.ajax({
type: "POST",
dataType: "json",
url: "get_json.pl",
data: datastring,
success: function(data) {
var stable = '<div class="popup-inner">' +
' <h2>Results</h2>' +
' <div>';
$.each(data,function(key,value) {
stable += '<p>Name: ' + value.name + ' | ' + 'Gender: ' + value.gender + '</p>';
});
stable += ' </div>'+
'<p><a data-popup-close="popup" href="#">Close</a></p>'+
'<a class="popup-close" data-popup-close="popup" href="#">x</a>'+
'</div>';
// Popup will be called here and opended in the div below
$('#popup').append(stable).fadeIn(350);
// This function will close the popup on click.
$('[data-popup-close]').on('click', function(e) {
var targeted_popup_class = jQuery(this).attr('data-popup-close');
$('#'+targeted_popup_class).fadeOut(350);
// Or use the id from the div below to close it.
//$('#popup').fadeOut(350);
e.preventDefault();
});
},
error: function() {
alert('Error handing data');
}
});
});
});
HTML code:
<form id="myForm">
<input type="text" name="name" value="" placeholder="Search by Name" />
<input type="submit" name="submit" value="Submit form" />
</form>
<div class="popup" id="popup">
</div>
Thanks again!
Here you have an easy option to do it. You can complicate it as much as you want....
$.ajax({
type: 'POST',
dataType: 'json',
url: 'get_json.pl',
data: datastring,
success: function(data) {
var stable = '<div class="popup-inner">' +
'<h2>Results</h2>' +
'<div id="results">';
$.each(data,function(key,value) {
stable += '<p>Name: ' + value.name + ' | ' + 'Gender: ' + value.gender + '</p>';
});
stable += '<div id="pagination">' +
'<span id="previous">Previous</span> ' +
'<span id="next">Next</span>' +
'</div>' +
'</div>' +
'<p><a data-popup-close="popup" href="#">Close</a></p>' +
'<a class="popup-close" data-popup-close="popup" href="#">x</a>' +
'</div>';
// Popup will be called here and opened in the div below
$('#popup').append(stable).fadeIn(350);
// Pagination.
var pageSize = 4,
pageStart = 0,
nItems = $('div#results p').length;
$('div#results p').hide().slice(pageStart,pageStart+pageSize).show();
$('div#pagination span').click(function() {
if ( (this.id == 'previous') && (pageStart>=pageSize) )
pageStart -= pageSize;
else if ( (this.id == 'next') && ((pageStart+pageSize)<nItems) )
pageStart += pageSize;
$('div#results p').hide().slice(pageStart,pageStart+pageSize).show();
});
// This function will close the popup on click.
$('[data-popup-close]').on('click',function(e) {
e.preventDefault();
$('div#popup div.popup-inner').fadeOut(350);
});
},
error: function() {
alert('Error handing data');
}
});

select2 ajax not working

I'm working with select2 library to make a dropdown using ajax. I cant make it work. Here is my code:
$("#guests").select2({
multiple: true,
minimumInputLength: 1,
formatInputTooShort: function () {
return "Enter 1 Character";
},
data: function() {
return data;
},
ajax: {
url: 'some url',
dataType: 'json',
processResults: function (data) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
return {
results: data.data,
pagination: {
more: 30
}
}
}
/*,
cache: true*/
},
escapeMarkup: function (markup) { return markup; },
templateResult: formatRepo,
templateSelection: formatRepoSelection
})
function formatRepo (results) {
var markup = "<div class='select2-result-resultssitory clearfix'>" +
"<div class='select2-result-resultssitory__avatar'><img src='" + results.id + "' /></div>" +
"<div class='select2-result-resultssitory__meta'>" +
"<div class='select2-result-resultssitory__title'>" + results.text + "</div>";
if (results.description) {
markup += "<div class='select2-result-resultssitory__description'>" + results.guest_first_name + "</div>";
}
markup += "<div class='select2-result-resultssitory__statistics'>" +
"<div class='select2-result-resultssitory__forks'><i class='fa fa-flash'></i> " + results.guest_last_name + " Forks</div>" +
"<div class='select2-result-resultssitory__stargazers'><i class='fa fa-star'></i> " + results.guest_do_b + " Stars</div>" +
"<div class='select2-result-resultssitory__watchers'><i class='fa fa-eye'></i> " + results.text + " Watchers</div>" +
"</div>" +
"</div></div>";
return markup;
}
function formatRepoSelection(results) {
return results.text || results.guest_first_name;
}
html:
<select id="guests" class="form-control input-guests " data-placeholder="Search guest..." multiple=""></select>
here is the JOSN data i'm getting from remote url:
[{
"id": 1,
"guest_first_name": "Jon",
"guest_last_name": "Doe",
"guest_do_b": "1954-07-13T00:00:00+0100",
"text": "Jon Doe"
}, {
"id": 2,
"guest_first_name": "Janne",
"guest_last_name": "Doe",
"guest_do_b": "1960-01-14T00:00:00+0100",
"text": "Janne Doe"
}]
A bit late, but was your error that options.results is undefined?
If that's the case, then you may want to rename the function processResults to results
I know it's in the docs with the processResults function, but I had the same problem and this article had the solution for me.

Handling json data using jQuery sent by using Newtonsoft.Json

I have tried searching all possible matches of my problem and also have tried a couple of solutions but unfortunately none worked
My backend code:
Person p;
foreach(DataRow dr in dt.Rows)
{
p = new Person();
p.id = Convert.ToInt16(dr["Id"]);
p.name = dr["Name"].ToString();
p.phone = Convert.ToInt64(dr["Phone"]);
pList.Add(p);
}
string ans = JsonConvert.SerializeObject(pList, Formatting.Indented);
jQuery.ajax
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Alert output
[
{
"id": 1,
"name": "Bhavik",
"phone": 9601109585
},
{
"id": 2,
"name": "Xyz",
"phone": 1234567890
},
{
"id": 3,
"name": "Abc",
"phone": 9876543210
}
]
console.log(list.Person.length); returns undefined and hence does not enters the for loop.. So to work out with it.. and why is it necessary to specify contentType while dataType already exist.. Also can I use $.getJSON instead of $.ajax.
You should change your code to be var list = {"Person": data.d}; to reflect what you're alerting.
function ShowData() {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Default.aspx/Data",
data: "{}",
dataType: "json",
success: function (data) {
alert(data.d);
var list = { "Person": +data.d };
for (i = 0; i < list.Person.length; i++) {
alert('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
console.log('Id: ' + list.Person[i].Id + '/nName: ' + list.Person[i].Name + '/nPhone: ' + list.Person[i].Phone);
}
console.log(list.Person.length);
},
error: function (result) {
alert("Error");
}
});
}
Also this should be a GET request not a post, then you would be able to use $.getJSON.

jquery.ajax multiple data retrieval

When I use this code, I only manage to retrieve recaptcha_response_field. If I remove recaptcha_response_field, I retrieve recaptcha_challenge_field. However, I am unable to retrieve the two at the same time.
I only managed to send 1 data.
challengeField = $("#recaptcha_challenge_field").val();
responseField = $("#recaptcha_response_field").val();
var html = $.ajax(
{
global: false,
type: "POST",
async: false,
dataType: "html",
data: "recaptcha_response_field=" + responseField + "&recaptcha_challenge_field=" + challengeField,
url: "../ajax.recaptcha.php"
}).responseText;
if(html == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
you wrote this line data: "recaptcha_response_field=" + responseField + "&recaptcha_challenge_field=" + challengeField, was wrong.
you can try this:
$.ajax({
type: "POST",
url: "some.php",
data: { name: "John", location: "Boston" }
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
or
data: {recaptcha_response_field : responseField , recaptcha_challenge_field :challengeField
thanks,
Chintu
Try
data: {
recaptcha_response_field: responseField,
recaptcha_challenge_field: challengeField
}
??
What do you mean that $_POST["recaptcha_response_field"] and $_POST["recaptcha_challenge_field"] are not both set "inside" ajax.recaptcha.php.
That's impossible Firebug's Net-Tab shows that the request just works fine.
Did you check your server logs (enable post data logging temporarily )
Maby something like this?
var challengeField = $("#recaptcha_challenge_field").val();
var responseField = $("#recaptcha_response_field").val();
/* Debug */ alert ("Going to send channengeField with value '" + challengeField + "', and responseField with '" + resonseField + "'");
$.post ("../ajax.recaptcha.php", {
recaptcha_response_field: responseField,
recaptcha_challenge_field: challengeField
},
function(data)
{
/* Debug */ alert ("Data Recieved: " + data);
if (data == "success")
{
$("#captchaStatus").html("Success. Submitting form.");
return true;
}
else
{
$("#captchaStatus").html("Your captcha is incorrect. Please try again");
Recaptcha.reload();
return false;
}
});
You can try like this
data: "recaptcha_response_field=" + $("#recaptcha_challenge_field").val() + "&recaptcha_challenge_field=" + ("#recaptcha_response_field").val(),

Categories