I have a function for getting records from database on keyup event.
Here is my code:
function displaySearch(key) {
$.ajax({
type:"POST",
url:"searchprofile.php",
data:{
k:key
},
success:function(data){
var details_arr=data.split("+");
$('.searchresult').empty();
for(var i=0;i<details_arr.length-1;i++){
$('.searchresult').append("<div class='profile' id='searchprofile'><img class='profilepic' src='images/profile.jpg'/><div class='doctorname'><div class='pname' onclick='saveName("+details_arr[i]+")'>"+details_arr[i]+"</div></div></div>");
$('.searchresult').show();
$('.searchresult .profile').show();
}
details_arr.length=0;
}
});
}
But i am getting javascript error here saying "Unexpected token ILLEGAL".
How do i give the onclick function with the value of details_arr[i]?
Please help.
As you have jQuery, you really shouldn't inline code. As you see it makes it more difficult to handle quotes inside quoted strings (yes, you're missing quotes around your argument to saveName).
You may do this :
(function(i){
$('.searchresult').append(
"<div class='profile' id='searchprofile'>"
+ "<img class='profilepic' src='images/profile.jpg'/>"
+ "<div class='doctorname'>"
+ "<div id=someId class='pname'>"+details_arr[i] // <- give some Id
+"</div></div></div>"
);
$('#someId').click(function(){saveName(details_arr[i])});
})(i);
$('.searchresult').show();
Note that I used a closure to ensure that i has the needed value in the callback (not the value at end of iteration).
Be careful with the split: on most browsers "+aaa".split('+') makes ["", "aaa"] and as you don't iterate up to the end of the array, this sample string would made you iterate on nothing.
function openNow(x)
{
var pageUrl = '<%=ResolveUrl("~/OnFriends.php")%>'
$.ajax({
type: "POST",
url: pageUrl + '/CreateNew',
data: '{k: "'+ x +'"}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success:function(data)
{
<---Now Do Your Code Hear--->
}
});
}
CreateNew is my web service what i created in .php file
I would use something like that
bare in mind ID must be unique inside a document (HTML Page)
because the content is generated on the fly; it's better to use the JQuery "on"
$(".pname").on("click", function (event) {
saveName($(this).text());
});
event handler to bind the click event
function displaySearch(key){
$.ajax({
type: "POST",
url: "searchprofile.php",
data: {
k: key
},
success: function(data) {
var details_arr = data.split("+");
var searchResults = "";
for (var i = 0; i < details_arr.length - 1; i++) {
searchResults += "<div class='profile'>" +
"<img class='profilepic' src='images/profile.jpg'/>" +
"<div class='doctorname'>" +
"<div class='pname'>" + details_arr[i] +
"</div></div></div>";
}
$('.searchresult').html(searchResults).show();
}
});
}
$(".pname").on("click", function (event) {
saveName($(this).text());
});
use the Jquery html to replace everything inside searchresult outside the loop that way it
will be called once not details_arr.length - 1 times
you should tell the line at which you are getting error
i think you did not specified you web service in ajax call at...
"url:"searchprofile.php"
Finally got the onclick function working. :)
Instead of appending the div everytime, i just editted my php page by adding the html i needed in the data that is returned in ajax.
Related
THE CONTEXT
I'm developing a web app that loads contents dynamycally, retrieving data from a
catalogue of items stored as a MongoDB database in which records of the items and their authors are in two distinct collections of the same database.
Authors ID are stored in the item field creator and refer to the author field #id. Each item can have none,one or many authors.
Item sample
{
"_id" : ObjectId("59f5de430fa594333bb338a6"),
"#id" : "http://minerva.atcult.it/rdf/000000016009",
"creator" : "http://minerva.atcult.it/rdf/47734211-2637-3895-a690-4f33412931ec",
"identifier" : "000000016009",
"issued" : "fine sec. XIV - inizi sec. XV",
"title" : "Quadrans vetus",
"label" : "Quadrans vetus"
}
Author sample
{
"_id" : ObjectId("59f5d8e80fa594333bb1d72c"),
"#id" : "http://minerva.atcult.it/rdf/0007e43e-107f-3d18-b4bc-89f8d430fe59",
"#type" : "foaf:Person",
"name" : "Risse, Wilhelm"
}
WHAT WORKS
I query the database submitting a string in a form, using this PHP script
ITEM PHP SCRIPT
<?php
require 'vendor/autoload.php';
$title=$_GET['item'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->items;
$regex=new MongoDB\BSON\Regex ('^'.$title,'im');
$documentlist=$collection->find(['title'=>$regex],['projection'=>['_id'=>0,'title'=>1,'creator'=>1,'issued'=>1]]);
$items=$documentlist->toArray();
echo (json_encode($items));
?>
called by a Javascript script (new_search.js) using ajax, that has also the responsibility to attach to html document a <li class=item> for every item that matches the query, inserting the JSON fields and putting them in the provided tags ( <li class=item-name>,<li class=auth-name, and the last <li> in div class=item-info for date).
WHAT DOES NOT WORK
My intent is reproduce the pattern to retrieve author names from another collection in the same database, querying it using author field #id from the html tag <li class=auth-name, using a similar php script and a similar ajax call.
I tried to make a nested ajax call (in the one I used to retrieve the items infos) to invoke author_query.php that performs the MongoDB query on the collection of authors.
So, the question is: Is it possible use the $_GET superglobal to get the html tag that contains the author id #id in order to search it in the database?
Otherwise, how can I adjust the code to pass a javascript variable to php (not by user input) that lets me keep the content already loaded on the page?
UPDATES
To make clearer the question, I follow the tips in the comments and I updated my scripts using JSON directly to provide the needed data.
I also perfom a debug on the js code and it's clear that PHP don't provide any response,in fact ajax calls for authors name fails systematically.
I suppose that occurs because PHP don't receive the data dueto the fact I'm not using the correct syntax probably (in js code or in the php with $_GET or in both) to pass the variable author (I also tried data:'author='+author treating the JSON object author has a string). Anyway I don't understand what is the correct form to write the variable to pass using the data field of ajax().
MY SCRIPTS
JS SCRIPT new_search.js
$(document).ready(function () {
$("#submit").on("tap", function () {
var item = document.getElementById("search").value;
var author;
$.ajax({
url: "item_query.php",
type: "GET",
data: 'item=' + item,
dataType: "json",
async:false,
success: function (items) {
for (var i = 0; i < items.length; i++) {
$("#items-list").append(
'<li class="item">' +
'<div class="item-photo-container">' +
'<img src=images/item_126.jpg>' +
"</div><!--end item-photo-container-->" +
'<div class="item-info">' +
'<ul>' +
'<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
'<li class="auth-name">' + items[i].creator+ '</li>' +
'<li>' + items[i].issued + '</li>' +
'</ul>' +
'</div><!--end item-info-->' +
'</li><!--end item-->'
);
}
}
});
$('.item').each(function () {
author = $(this).find('.auth-name').text();
if (author == 'undefined')
$(this).find('.auth-name').text('Unknown');
else if(author.indexOf(',')!=-1) {
author='[{"author":"'+author+'"}]';
author=author.replace(/,/g,'"},{"author":"');
author = JSON.parse(author);
console.log(author);
$.ajax({
url: "author_query.php",
type: "GET",
data: author,
dataType: "json",
processData: false,
success: function (auth_json) {
$(this).find('.auth-name').text('');
var author_text=' ';
for(var i=0;i<auth_json.length;i++)
author_text+=auth_json.name+' ';
$(this).find('.auth-name').text(author_text);
},
error: function () {
console.log('Error 1');
}
});
}
else{
author='{"author":"'+author+"}";
author=JSON.parse(author);
$.ajax({
url: "author_query.php",
type: "GET",
data: author,
dataType: "json",
processData: false,
success: function (auth_json) {
$(this).find('.auth-name').text(auth_json.name);
},
error: function () {
console.log('Error 2');
}
});
}
});
});
});
AUTHOR PHP SCRIPT author_query.php
<?php
require 'vendor/autoload.php';
$auth=$_GET['author'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->persons;
if(is_array($auth)){
foreach ($auth as $a){
$document=$collection->findOne(['#id'=>$a],['projection'=>['_id'=>0,'name'=>1]]);
$auth_json[]=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
}
else{
$document=$collection->findOne(['#id'=>$auth],['projection'=>['_id'=>0,'name'=>1]]);
$auth_json=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
echo (json_encode($auth_json));
?>
"I'm sure that authors array... is not empty and actually contains the authors IDs". You mean the jQuery object $('.item')? I think that it is empty, because it is created too soon.
The first $.ajax call sends an ajax request and sets a handler to add more stuff to the HTML, including elements that will match the CSS selector .item. But the handler doesn't run yet because it's asynchronous. Immediately after this, the object $('.item') is created, but it's empty because the new .item elements haven't been created yet. So no more ajax requests are sent. Some time later, the call to item_query.php returns, and the new HTML stuff is added, including the .item elements. But by now it's too late.
You say the array was not empty. I suspect you checked this by running the CSS selector after doing the search, after the return of the ajax call.
A lot of newbies have problems like this with asynchronous javascript. If you want to use the result of an asynchronous function in another function, you have to call the second function inside the callback function of the first one. (Actually there are more sophisticated ways of combining asynchronous functions together, but this is good enough for now.)
On a side note, you've done this in a slightly strange way where you save data in HTML, and then read the HTML to do some more stuff. I wouldn't use HTML as a storage place - just use variables like you would for most other things.
Try this:
$.ajax({
url: "item_query.php",
...
success: function (items) {
for (var i = 0; i < items.length; i++) {
var author = items[i].creator;
var authors;
// insert code here to generate authors from author.split(',') .
// authors should look something like this: [{author: 'http://minerva.atcult.it/rdf/47734211-2637-3895-a690-4f33412931ec'}] .
$.ajax({
url: "author_query.php",
type: "GET",
data: JSON.stringify(authors),
...
success: function (auth_json) {
...
},
error: function () {
console.log('Error 1');
}
});
$("#items-list").append(
'<li class="item">' +
'<div class="item-photo-container">' +
'<img src=images/item_126.jpg>' +
"</div><!--end item-photo-container-->" +
'<div class="item-info">' +
'<ul>' +
'<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
'<li class="auth-name">' + items[i].creator+ '</li>' +
'<li>' + items[i].issued + '</li>' +
'</ul>' +
'</div><!--end item-info-->' +
'</li><!--end item-->'
);
}
}
});
I make the first call to retrieve the item infos asynchronous and the nested that search for the authors name synchronous. In this way I solved the problem.
For sure it is not the best solution, and it needs a quite long,but acceptable, time (<1 second) to load the content.
JS SCRIPT
$(document).ready(function () {
$("#submit").on("tap", function () {
var item = document.getElementById("search").value;
$.ajax({
url: "item_query.php",
type: "GET",
data: 'item=' + item,
dataType: "json",
success: function (items) {
for (var i = 0; i < items.length; i++) {
var authors_names=' ';
var authors= JSON.stringify(items[i]);
if(authors.indexOf('creator')!=-1){
if(authors.charAt(authors.indexOf('"creator":')+'"creator":'.length)!='[')
authors=authors.substring(authors.indexOf('"creator":"'),authors.indexOf('"',authors.indexOf('"creator":"')+'"creator":"'.length)+1);
else
authors=authors.substring(authors.indexOf('"creator"'),authors.indexOf(']',authors.indexOf('"creator"'))+1);
authors='{'+authors+'}';
//console.log(authors);
$.ajax({
url: "author_query_v3.php",
type: "GET",
data: 'authors='+authors,
dataType:"json",
async:false,
success: function (auth_json) {
authors=[];
authors=auth_json;
var author;
for(var j=0;j<authors.length;j++){
author=JSON.parse(authors[j]);
authors_names+=author.name+" | ";
}
console.log(authors_names);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(jqXHR+' '+textStatus+ ' '+errorThrown);
}
});
}
else{
authors_names='Unknown';
}
$("#items-list").append(
'<li class="item">' +
'<div class="item-photo-container">' +
'<img src=images/item_126.jpg>' +
"</div><!--end item-photo-container-->" +
'<div class="item-info">' +
'<ul>' +
'<li><a><h3 class="item-name">' + items[i].title + '</h3></a></li>' +
'<li class="auth-name">' + authors_names+ '</li>' +
'<li>' + items[i].issued + '</li>' +
'</ul>' +
'</div><!--end item-info-->' +
'</li><!--end item-->'
);
}
}
});
});
});
PHP SCRIPT
<?php
require 'vendor/autoload.php';
$auth=$_GET['authors'];
$client = new MongoDB\Client("mongodb://localhost:27017");
$db=$client->galileo;
$collection=$db->persons;
$auth=json_decode($auth);
$auth=$auth->creator;
if(is_array($auth)) {
foreach ($auth as $a) {
$document = $collection->findOne(['#id' => $a], ['projection' => ['_id' => 0, 'name' => 1]]);
$auth_json[] = (MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
}
else{
$document=$collection->findOne(['#id'=>$auth],['projection'=>['_id'=>0,'name'=>1]]);
$auth_json[]=( MongoDB\BSON\toJSON(MongoDB\BSON\fromPHP($document)));
}
echo(json_encode($auth_json));
?>
I have a feeling there is something wrong with my for loop. When my websites event is activated the first time, I get no response. It works as intended every time after that. I have tried tuning the numbers in the for loop looking for mistakes but as far as what I've tried. It works best as is.
For the full app: https://codepen.io/xcidis/full/KvKVZb/
var reference = [];
function random() {
$.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
});
}
$("button").click(function(){
random();
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
Your rest of the code ran before your ajax push the value to reference variable.
https://www.w3schools.com/xml/ajax_intro.asp
You can either put your page rendering code within the ajax or use some tips to run the rederer synchronously
$("button").click(function(){
$.when( $.ajax({
url: "https://api.forismatic.com/api/1.0/?",
dataType: "jsonp",
data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
success: function(quote) {
reference.push([quote.quoteText + "<br/><br/><br/><div class='tweet' align='left'></div><div align='right'>~" + quote.quoteAuthor + "</div>"]);
}
})).then(function() {
console.log(reference)
for(i=0;i<4; i++){
if(reference[reference.length-1] == undefined){continue}else{
var boxes = $("<div id='boxes'></div>").html("<p>" + reference[reference.length-1] + "</p>");
$('body').append(boxes);
break;
};
};
});
});
I can do this, simply doing it in for loop, but I need to do it without using loop.
Is there any way to make it possible?
Below I am writing some of my code:
function submitFormArchive(Status) {
var siteUrl = $("#pageurl").val();
$("#archive-loader").show();
var myCheckboxes = new Array();
$("input[type='checkbox'][name='archive[]']:checked").each(function () {
myCheckboxes.push($(this).val());});
alert(myCheckboxes);///this one i am getting dynamic ids
$.ajax({
type: 'POST',
url: siteUrl + 'Appadmins/ajaxUpdateArchive',
data: {"myCheckboxes": myCheckboxes, "status": Status},
success: function (data) {
$("#remove-id-"+myCheckboxes).slice(myCheckboxes).remove();
}
});
return false;
}
<tr class="message_box" id='remove-id-<?php echo $list->id;?>'></tr>
This one in for loop
I am posting some part of codes.
$("#remove-id-" + myCheckboxes).slice(myCheckboxes).remove();
Is there any for multiple, maybe I have written wrong in this above code.
Try the code below
$("input[type='checkbox'][name='archive[]']:checked").each(function() {
myCheckboxes.push($(this).val());
});
alert(myCheckboxes); //40,39,38 //it can be any id ,as i made it dynamic .
// construct array of IDs here
var ids = myCheckboxes.map(function(id) { return "#remove-id-" + id; });
// ["#remove-id-40", "#remove-id-39", "#remove-id-38"]
// concat all id selectors together using comma `,`
var idSelector = ids.join(",");
// "#remove-id-40,#remove-id-39,#remove-id-38"
// remove all at once.
$(idSelector).remove();
$("input[type='checkbox'][name='archive[]']:checked").each(function() {
$("#remove-id-" + $(this).val()).remove();
});
Can anyone tell me why I get an error on the 2nd line saying 'unexpected string' but works fine when I have it directly on my view (i'm using MVC 3, not that it makes a difference):
function getUsers(processId) {
$.ajax({
url: "#Url.Action('GetProcessApprovers', 'Risk')",
data: { processId: processId },
dataType: "json",
type: "POST",
error: function () {
alert("An error occurred.");
},
success: function (data) {
var items = "<option value=\"\">-- Please select --</option>"
if (data != "") {
$.each(data, function (i, item) {
items += "<option value=\"" + item.Value + "\">" + item.Text + "</option>";
});
}
$("#ProcessOwnerId").html(items);
}
});
};
Because your url: "#Url.Action('GetProcessApprovers', 'Risk')", only executes in the context of the view, not in an external JS file. It's razor code.
You need to pass the url to the Javascript in some other way, perhaps as a parameter of your function.
getUsers(processId, ajaxUrl)
Another way would be to write out the url from the HtmlHelper into a data attribute in your view and then pick it up in your Javascript.
HTML
<div id="someContainer" data-url="#Url.Action('GetProcessApprovers', 'Risk')">...
JS
var url = $("#someContainer").attr("data-url");
Your url parametre is has the issue.
please change it like this:
url: '#Url.Action("GetProcessApprovers", "Risk")',
Hope it works
I've looked over a lot of 'similar' q&a threads on SO but to be honest, as I don't have too much of a grip on js programming, I'm finding it difficult to make sense of a lot of the answers (as far as they may apply to my own situation).
The context is this, I have two php scripts one returning a list of customer_ids (json encoded) for a set period and the other returning their preferences for news feeds (json encoded).
I wrote the following, having googled a bit to get a basic understanding of how to setup an ajax function in jQuery:
$('document').ready(function() {
$.ajax({
type:'GET', url: 'cust_selection.php', data: '',
succes:function(cstmrid) {
var clistlen = cstmrid.length;
var i=0;
var cstmr;
for( ;cstmr=cstmrid[i++]; ) {
$('#adminPanel>ul>li').append("<a href='' onclick='alert("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>"); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType:'json'
});
var cstmrid = "483972258"; //hardcoded for testing purposes
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
success:function(npfdata) {
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
},
dataType:'json'
});
});
Now from the first ajax function, I get a list of links which I want to be able to click to launch the second ajax function and pass it the customer id so that it can grab a list of the news sources that they've configured for their pages.
The alert and the hard-coded customer id both suggest that the functions are 'working', but when I try and adjust the first function so that:
...
$('#adminPanel>ul>li').append("<a href='' onclick='getCustomerNP("+cstmr+")' class='lst_admin basic'>"+cstmr+"</a>");
... is calling a modified version of the second function, as below:
...
function getCustomerNP(cstmrid) {
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+cstmrid,
success:function(nprfdata) {
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
},
dataType:'json'
});
}
Everything seems to just fail at this point. The second function doesn't seem to 'receive' the variable and I'm not sure if it's something elementary that I've overlooked (like some muddled up " and ' placements) or if what I am trying to accomplish is actually not the way jQuery ajax functions interact with each other.
As you can see, I've cannibalised bits of code and ideas from many SO q&a threads, but copying without much of an understanding makes for a frustratingly dependent life.
I would appreciate as much - expansive - comment as you can provide, as well as a solution or two (naturally).
EDIT: Not to confuse anyone further, I've been modifying the above and correcting my (many) errors and typos along the way. At present, the code looks like below:
$('document').ready(function () {
$.ajax({
type: 'GET', url: 'cust_selection.php', data: '',
succes: function (cstmrid) {
var clistlen = cstmrid.length;
var i = 0;
var cstmr;
for (; cstmr = cstmrid[i++]; ) {
var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
getCustomerNP(cstmr)
})
$('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType: 'json'
});
function getCustomerNP(cstmr) {
alert(cstmr);
}
});
You've got a typo in the $.ajax() success function within getCustomerNP(). The function declaration:
success:function(nprfdata) {
... has a parameter nprfdata, but then within the function you use npfdata (missing the r).
Also this code:
var item;
var n=0;
for( ;item=npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>"+item+"</td></tr>");
}
...declares and sets variable news that you never use. And it doesn't seem right to increment n in the for test expression but then use n within the loop. You never set item to anything but you use it in your .append().
(Note also that JS doesn't have block scope, only function scope, so declaring variables inside an if or for loop doesn't limit them to that if or for block.)
I would not create inline onclick handlers like that. I'd probably do something more like this:
$('#adminPanel>ul>li').append("<a href='' data-cstmr='"+cstmr+"' class='lst_admin basic'>"+cstmr+"</a>");
...and then within the document ready setup a delegated event handler to catch the clicks on those anchors:
$('#adminPanel>ul>li').on('click', 'a.lst_admin', function() {
$.ajax({
type:'GET', url:'newsfpref.php?', data:'cref='+ $(this).attr('data-cstmr'),
success:function(npfdata) {
var item,
n=0,
// cache the jQuery object rather than reselecting on every iteration
$table = $('#adminMain>table>tbody');
// increment n only after the current iteration of the loop
for( ;item=npfdata[n]; n++) {
// change to use item
$table.append("<tr><td>"+item.nsource+"</td></tr>");
}
},
dataType:'json'
});
});
As you append your like with <a href='' onclick='getCustomerNP("+cstmr+")', Make sure you can access the function getCustomerNP.
Try to define getCustomerNP as
window.getCustomerNP = function(cstmrid) {
...
If you defined it in the $(document).ready(function(){ ... }) block, try this
$('document').ready(function () {
$.ajax({
type: 'GET', url: 'cust_selection.php', data: '',
succes: function (cstmrid) {
var clistlen = cstmrid.length;
var i = 0;
var cstmr;
for (; cstmr = cstmrid[i++]; ) {
var a = $("<a href='' class='lst_admin basic'>" + cstmr + "</a>").click(function () {
getCustomerNP(cstmr)
})
$('#adminPanel>ul>li').append(a); //alert to be replaced with a function call which passes customerid to the function below.
}
},
dataType: 'json'
});
function getCustomerNP(cstmrid) {
$.ajax({
type: 'GET', url: 'newsfpref.php?', data: 'cref=' + cstmrid,
success: function (nprfdata) {
var item;
var n = 0;
for (; item = npfdata[n++]; ) {
var news = npfdata[n].nsource;
$('#adminMain>table>tbody').append("<tr><td>" + item + "</td></tr>");
}
},
dataType: 'json'
});
}
});