I am getting a users details from a MongoDB database like this:
$user=$collection->findOne(array('_id' => new MongoId($_SESSION['user']['userid'])));
if (!empty($user)){
json_encode($user);
print_r($user);
}
I can get an entire JSON array from the AJAX but not individual elements - I get undefined:
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
alert(msg);
}
});
The actual JSON is structured like this:
username: john
password: hello
email: me#mailserver.com
I'm stuck.
you returning array object from getUser.php but you display it as a normal variable
$.ajax({
type: 'json',
url: '../scripts/getUser.php',
method: 'GET',
success: function(msg){
$.each(msg,function(key,value){
alert(value.id);
});
}
});
i guess this will work..
You need to get the return value
$encoded = json_encode($user);
print_r($encoded);
The method you are using does not encode in place. It returns a left side value.
success: function (response)
{
if(response != 'error')
{
//parse into JSON
var jsonObj = JSON.parse(response);
var HTML = '';
//extract single value using each
$.each(jsonObj, function(key, val) {
HTML += '<tr><td>' + val.id + '</td><td>' + val.first_name + '</td><td>' + val.last_name + '</td><td>' + val.gender + '</td>'
+'<td>' + dt + '</td><td>' + val.phone + '</td><td>' + val.mobile + '</td><td>' + val.email + '</td>'
+'<td>' + val.address + ',' + val.city + ',' + val.state + '</td><td>' + val.country + '</td>'
+'<td>' + val.zip + '</td><td>' + val.hobbies + '</td><td>' + 'INR ' +val.salary + '</td><td>' + val.countryCode + '</td>'
+'<td>' + val.username + '</td><td>' + val.pwd + '</td></tr>';
});
Related
I'm trying to load from my database using ajax and it work.
here is my source code:
$.ajax({
type: "GET",
url: "a/aa.php",
dataType: "json",
success: function(response){
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr role="row" ><td class="" >' + item.id + '</td><td class="copyte">'+ item.zuser + '</td><td class="copyte"> ' + item.user + '</td><td>' + item.zcode + '</td><td>' + item.zcountry + '</td><td>' + item.zsc + '</td><td>' + item.zip + '</td><td data-id="' + item.zid + '" class=" deltype"><i class="fa fa-trash-alt"></i></td></tr>';
});
$('#myTable').append(trHTML);
}
});
I am trying to make the content in "td" copyable by clicking on it. I made this attempt and it works fine but it is not working on the table created from the connection and it gives this error
Uncaught TypeError: Cannot read property 'createDocumentFragment' of undefined
the code
$('.copyte').click(function(e) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(this).html()).select();
document.execCommand("copy");
$temp.remove();
Command: toastr["success"]($(this).html() + " copied", "DONE");
});
I use a tag onclick function to delete specific documents.
I call the function with three arguments.
but my regex does not include a specific case.
Generally, it works, like "test".
but some case doen't work.
Like this case => "St. John's"
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item);
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + "\"" + value + "\"" + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
});
this is expected key value example
const key = "en";
const value = "test"; // it works
const value = "St. John's"; // it doesn't work.
const regionCode = "AG-ANU";
if onclick function call success,
it calls this function
function deleteName(key, value, regionCode) {
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + key + "&name=" + value,
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
I need help for value part regex expression.
It is not good way, but I solved like this.
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item)[0];
var valueStr = JSON.stringify(value);
var valueString = value.replace(/'/gi, "\\\'");
var keyValueRegionCode = key + "|" + valueString + "|" + regionCode;
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '[ 삭제 ]' + '</td></tr>';
});
then calls keyValueRegionCode
function deleteName(keyValueRegionCode) {
var keyValue = keyValueRegionCode.split("|")[0];
var nameValue = keyValueRegionCode.split("|")[1];
var regionCode = keyValueRegionCode.split("|")[2];
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + keyValue + "&name=" + encodeURIComponent(nameValue),
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
1) value.replace(/'/gi, "\\'"); -> this regex makes single apostrophe like this. (\')
2) make parameters one for calling function easily .
I'm using the google news API and I want to add the value of the URL to be on the article title and convert the image from the JSON data to be viewable. Below is my code so far.
/*$.getJSON(url, function(data){
console.log(data);
});*/
$.ajax({
url:
"https://newsapi.org/v2/everything?apiKey=xxx&q=nrcs",
dataType: "json",
type: "get",
cache: false,
success: function (data) {
$(data.articles).each(function (index, value) {
//console.log(value);
$('#news').append('<div>' + '<h3 id="title" style="color:#B8860B;">' + value.title + '' + value.url + '</h3>' + '<p>' + '<span style="color:#C4BFBF; font-style: italic;">' + value.author + '</span>' + '<br>' + value.publishedAt + '<br>' + value.description + '</p>' + '</div>');
$('#link').append(value.url);
});
}
});
Judging just by this and not seeing the whole picture (returned Json, css styles and layout of the page; basically any conflicting factors) I’d try:
$.ajax({
url:
"https://newsapi.org/v2/everything?apiKey=xxx&q=nrcs",
dataType: "json",
type: "get",
cache: false,
success: function (data) {
$(data.articles).each(function (index, value) {
//console.log(value);
$('#news').append('<div>' + '<h3 id="title" style="color:#B8860B;">' + value.title + '' + value.url + '</h3>' + '<p>' + '<span style="color:#C4BFBF; font-style: italic;">' + value.author + '</span>' + '<br>' + value.publishedAt + '<br>' + value.description + '</p>' + '<br>' + value.url + '</div>');
});
}
});
Instead of appending to the appended div, add it direct within; check the console for any errors and if there are none your issue may be related to the container / style of your page.
I'm working on fetching data from a JSON URL in jQuery with $ajax call and I'm using bootstrap in the HTML.
$.ajax({
url: 'https://services.web.bilinfo.dk/api/vehicle/?user=demo&password=ocfB6XzF73&format=json',
type: 'GET',
data: {
format: 'JSON'
},
error: function() {
$('#info').html('<p>An error has occurred</p>');
},
success: function(data) {
$.each(data, function(index, data) {
$('.col-md-4')
.append("picture" + '<img src= "' + data[0].Pictures + '">')
.append("<h1> Model:" + data[0].Model + "</h1>")
.append("<h1> make:" + data[0].Make + "</h1>")
.append("<p> variant:" + data[0].Variant + "</p>")
.append("<p> registrationDate:" + data[0].RegistrationDate + "</p>");
})
},
});
The image doesn't seem to come out, but displays a broken img like thing, any hints or suggestions?
And right now I'm only getting one car out, at data[0].
Now I'm using a $.each, but what if I would receive all cars?
I would generate a complete example, but the access control on that site does not allow it.
In your success handler try:
$.each(data.Vehicles, function(index, item) {
$(".col-md-4")
.append("picture" + '<img src= "' + item.Pictures[0] + '">')
.append("<h1> Model:" + item.Model + "</h1>")
.append("<h1> make:" + item.Make + "</h1>")
.append("<p> variant:" + item.Variant + "</p>")
.append("<p> registrationDate:" + item.RegistrationDate + "</p>");
})
I have this code which is fetching data from service according to button click. What I want this when I click previous or next button, I want to change pagenumber on bottom of dataTable.
$('.paginate_button.previous', this.api().table().container())
.on('click', function(){
// alert("Doruk");
if(pageNumber > 1) {
$.ajax({
url: "http://192.168.1.171:8080/LogWS/rest/v1/logs/normalized-logs-paged?pageNumber=" + pageNumber-- + "&&pageCount=10",
type: "post",
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
processData: false,
headers: {
Authorization: "Bearer " + localStorage.getItem("globalAuthenticationKey")
},
data:
JSON.stringify(hostAddresses)
,
success: function (response) {
var Table = document.getElementById("applicationviewTableID");
Table.innerHTML = "";
for (var i = 0; i < response.logData.length; i++) {
var trHTML = '';
// var trHTML2 = '';
trHTML += '<tr><td>' + response.logData[i].ip + '</td><td>' + response.logData[i].application + '</td><td>' + "" + '</td>';
$('#applicationviewTableID').append(trHTML);
/* trHTML2 += '<tr><td>' + response.logData[i].ip + '</td><td>' + response.logData[i].application + '</td><td>' + response.logData[i].operation + '</td><td>' + response.logData[i].entityType + '</td><td>' + response.logData[i].entity + '</td><td>' + response.logData[i].time + '</td>'
$('#DetailedApplicationsMalwareTableBodyID').append(trHTML2);*/
}
console.log( $('.paginate_button.active')[0]);
},
Below code shows me html code piece that I want to change in console.
console.log( $('.paginate_button.active')[0]);
It shows
<li class="paginate_button active">1</li>
And I want to change that "1" inside "a" tag
How can I do that
You have to select the inner a-tag too.
Then you can get the text like this:
$('.paginate_button.active a').text();
or edit like this:
$('.paginate_button.active a').text("2")