No results obtained with JQuery $.getJSON in the PhoneGap environment - php

Here is my funciton:
function getEmployeeList() {
alert("hello world3!");
$.getJSON(serviceURL + 'getemployees.php', function(data) {
alert("hello world4!");
$('#employeeList li').remove();
employees = data.items;
$.each(employees, function(index, employee) {
$('#employeeList').append('<li><a href="employeedetails.html?id=' + employee.id + '">' +
'<img src="pics/' + employee.picture + '"/>' +
'<h4>' + employee.firstName + ' ' + employee.lastName + '</h4>' +
'<p>' + employee.title + '</p>' +
'<span class="ui-li-count">' + employee.reportCount + '</span></a></li>');
});
$('#employeeList').listview('refresh');
});
}
When the page is ready, it will run this function, however, nothing is appended.
I have tested, all php can return correct format. What wrongs?? Please please help me...

You need to add the external host (in my case was mysite.localhost) in PhoneGap.plist under the "ExternalHosts" key.

I presume serviceURL is not on the same domain.
In that case you add callback=? in the end, and jQuery does some magic:
$.getJSON(serviceURL + 'getemployees.php?callback=?', function(data) {
...
If the URL includes the string "callback=?" (or similar, as defined by the server-side API), the request is treated as JSONP instead. See the discussion of the jsonp data type in $.ajax() for more details.
jQuery API

Related

Ajax: Getting a Post Error when trying to use Relative Path

Struggling to get the relative path of an Ajax post request to pickup the php file. I'm not getting an error just nothing happens.
Browsed this site, but cannot find a previous answer on Ajax relative paths that I understand. Still a novice at this. Would really appreciate it, if someone could explain it in layman terms.
I'm trying to access the php file 'search/search.php' from the root file 'index.php' (this file contains the Ajax request). This worked when both files were in the same directory.
File structure below:
JQuery code snippet:
$(function() {
$('form').on("submit", function(e) {
e.preventDefault();
$('#error').text(""); // reset
var name = $.trim($("#search").val());
if (name.match(/[^a-zA-Z0-9 ]/g)) {
$('#error').text('Please enter letters and spaces only');
return false;
}
if (name === '') {
$('#error').text('Please enter some text');
return false;
}
if (name.length > 0 && name.length < 3) {
$('#error').text('Please enter more letters');
return false;
}
$.ajax({
url: 'search/search.php',
method: 'POST',
data: {
msg: name
},
dataType: 'json',
success: function(response) {
$(".content").html("")
$(".total").html("")
if(response){
var total = response.length;
$('.total') .append(total + " Results");
}
$.each(response, function() {
$.each($(this), function(i, item) {
var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' : '';
$('.content').append('<div class="post"><div class="post-text"> ' + item.MessageText + ' </div><div class="post-action"><input type="button" value="Like" id="like_' + item.ID + '_' + item.UserID + '" class="like" ' + mycss + ' /><span id="likes_' + item.ID + '_' + item.UserID + '">' + item.cntLikes + '</span></div></div>');
});
});
}
});
});
});
The leading forward slash simply means “begin at the document root”, which is where index.php lives. So /search/search.php should be correct. If the server is unable to find the file, it stands to reason that there must be some url rewriting happening.
You can test by simply pointing your browser to http://localhost:8000/search/search.php. If you get a 404, you know it has nothing to do with ajax

purge deleted documents from couchdb in php

I am trying to write an automated script to run through a couchdb, find the deleted documents (About 100,000 doc deletetions a month) and purge them and their revisions.
I haven't found documentation explaining how to get all deleted documents, all their revisions, and construct them into the POST request shown here.
http://docs.couchdb.org/en/stable/api/database/misc.html
How do I construct the views, get the data, and create the POST to do this?
Thanks
So I ended up making a nodejs script for it that runs periodically.
Some things are hard coded since this was for testing, and not production (yet). Anyone referencing this should watch for hard coded references.
I used pouchdb to handle the replication, as it was able to run all 400,000 tombstones in a few minutes, whereas I never actually got couchdb to finish replicating after a full day of running.
This is my first node script ever, so I apologize if it's awful.
var PouchDB = require('pouchdb');
var fs = require('fs');
var child = require('child_process');
var originalDB = "dbName";
var tempDB = "dbName_clean";
var serviceName = "Apache CouchDB";
var couchDBDataPath = "C:\\bin\\couchdb\\couchdb.2.1.1\\data\\";
var db = new PouchDB('http://URL/' + originalDB);
var db2 = new PouchDB('http://URL/' + tempDB);
console.log("Compacting");
return db.compact().then(function (result) {
console.log("Compacting done, replicating");
var batch_size = 100;
return db2.destroy().then(function () {
db2 = new PouchDB('http://URL/' + tempDB);
return db.replicate.to(db2, {
batch_size: batch_size,
filter: function (doc, req) {
return !doc._deleted;
}
}).on('change', function (info) {
console.log("batch done");
}).on('complete', function () {
console.log('complete');
}).on('paused', function (err) {
// replication paused (e.g. replication up to date, user went offline)
console.log("paused", err);
}).on('active', function () {
// replicate resumed (e.g. new changes replicating, user went back online)
console.log("Active");
}).on('denied', function (err) {
// a document failed to replicate (e.g. due to permissions)
console.log("Denied", err);
}).on('error', function (err) {
// handle error
console.log("error", err);
// reject(err);
}).then(function () {
//replicate done, rename everything
var date = new Date();
console.log("Stopping service");
child.execSync('net stop "' + serviceName + '"');
console.log("Service Stopped");
var newName;
var counter = 0;
do {
newName = "_" + date.getFullYear() + date.getMonth() + date.getDay() + "_" + counter;
counter++;
} while (fs.existsSync(couchDBDataPath + originalDB + newName + ".couch") || fs.existsSync(couchDBDataPath + "." + originalDB + "_design" + newName));
console.log("Renaming original couch to backup labeled", originalDB + newName);
fs.renameSync(couchDBDataPath + originalDB + ".couch", couchDBDataPath + originalDB + newName + ".couch");
fs.renameSync(couchDBDataPath + "." + originalDB + "_design", couchDBDataPath + "." + originalDB + newName + "_design");
console.log("Renaming clean couch back to original", tempDB);
fs.renameSync(couchDBDataPath + tempDB + ".couch", couchDBDataPath + originalDB + ".couch");
fs.mkdirSync(couchDBDataPath + "." + originalDB + "_design");
console.log("Starting service");
child.execSync('net start "' + serviceName + '"');
console.log("Service started");
});
});
}).catch(function (err) {
console.log(err);
});

How to load Json data to drop down

here in this code i am trying to get the json value. i am able to get the key value, but i am not able to get the val's value.
How can i do this?
Jquery code:
$.getJSON('data.json', function(data) {
var items = [];
$.each(data, function(key, val) {
alert(key);
alert(val);
items.push('<option value="' + key + '">'+key+'</option>');
//items.push('<li id="' + key + '">' +key + '</li>');
});
$('#project-list').html(items.join(''));
});
here is json data
{
"trng-java": {"1":"5"},
"trng-jast": {"2":"5"},
"trng-caml": {"3":"4"},
"trng-linx": {"1":"5"}
}
When i run this, i am getting the key value, but val's value is coming as Object object.
the value is an array it seems, like others suggested use val[index] to get the values but if you want it to be a string use
var valString = val.toString();
this will return 1,5 , 2,5 ...
Try accessing: val[0]
$.getJSON('data.json', function(data) {
var items = [];
$.each(data, function(key, val) {
alert(key);
alert(val[0]);
items.push('<option value="' + key + '">'+key+'</option>');
//items.push('<li id="' + key + '">' +key + '</li>');
});
$('#project-list').html(items.join(''));
});

Select boxes auto populated by JSON sometimes need a refresh before displaying

I have a JSON file that is being used to autopopulate some select boxes. Every now and then (I can't recreate the fault, it appears to be random) the items in the drop down do not display until I refresh the page.
I've checked the console and log etc, the file is loading fine, no errors are appearing and I'm a little at a loss.
Any ideas?
Example of JSON and the script that reads it below.
Thanks.
"radAbsorbed" : [
{
"value" : "rad",
"name" : "Rad(rd)"
},
{
"value" : "millirad",
"name" : "Millirad(mrd)"
}]
and the script:
<script>
// JSON:
// The key is the class identifier, temp, area etc etc
// Value is being used for both ID and Value when the list is being populated
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
</script>
EDIT:
Updated script.
$(document).ready(function(){
$.getJSON('JSON/conversionJSON.json', function(data){
console.log(data);
//for testing output only
var list = $("<ul />");
$.each(data, function (key, conversions) {
console.log(key + ":" + conversions);
$.each(conversions, function (index, conversion) {
console.log("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>");
if(key == "<?php echo $conversionType ?>"){
$("#from").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
$("#to").append('<option class="'+key+'" id="'+conversion.value+'" value="'+conversion.value+'">'+conversion.name+'</option>');
//testing output
var elem = $("<li>Name: " + conversion.name + " :Value: " + conversion.value + "</li>").appendTo(list);
}
});
});
//$("#testJSON").html(list);
});
});
EDIT: Thanks everyone for their help, it seems to be working fine and looked like an amateur mistake on my part.
I think the problem is that your script is sometimes running before the document is ready.
Try wrapping your code in a document ready function:
$(function() {
$.getJSON(...)
// ...
});
This will make it so that the code doesn't execute before the elements it's affecting are created. For instance, if your code executes before the element with the ID from gets created, then $('#from') will not match any elements, and it won't work.
Wrapping it in a document ready function will make sure that your code waits until the elements have been created before executing.
Alternatively, you could move your <script> tag out of the head and place it right after the #from element in your HTML. This might help it load slightly faster.

Textbox 'this.value' stops JavaScript with single quotes

I cannot get single quotes to work in JavaScript this.value. Double quotes work fine. I tried to use escape() and it didn't work and I cannot think of a way to use PHP to fix this, so does anyone else have any ideas?
function editItemInCart(newValue,fieldName,itemNum,cnt) {
//alert(newValue);
if (count == cnt) {
count = 0;
jQuery.ajax({
type:"POST",
url: "editItem.html",
data: "newvalue=" + escape(newValue) + "&fieldname=" + fieldName + "&itemNum=" + itemNum,
})
document.getElementById('status' + itemNum).innerHTML = "SAVED";
jQuery("#status" + itemNum).show();
setTimeout("fade_out('"+itemNum+"')", 1000);
}
//alert(newValue + fieldName + itemNum);
}
if ($cart['title'] != "")
echo "<label>Title: </label> <input type=\"text\" onKeyUp=\"doEditItemInCart(this.value,'title',".$itemNum.")\" onChange=\"editItemInCart(this.value,'title',".$itemNum.")\" value=\"".htmlspecialchars($cart['title'])."\"><br />";
function doEditItemInCart(newValue,fieldName,itemNum) {
count++;
setTimeout("editItemInCart(escape('"+newValue+"'),'"+fieldName+"',"+itemNum+","+count+")",200);
}
try this
jQuery.ajax({type:"POST",
url: "editItem.html?newvalue=" + escape(newValue) + "&fieldname=" + fieldName + "&itemNum=" + itemNum,
})
it also appears that you are setting the status of saved regardless of the ajax response. i suggest added an ajax success function
http://api.jquery.com/jQuery.ajax/

Categories