I'm new to Parse and I'm not a very well-experienced PHP developer.
I'm trying to run a search query using Parse.com PHP SDK on _User class.
Here is my code:
<?php $query = new ParseQuery('_User');
$query->startsWith("s_first_name", $user);
$results = $query->find();
foreach ($results as $result) { ?>
<?php echo $result->get('s_first_name')." ".$result->get('s_last_name'); ?>
<?php } ?>
It works but it's case sensitive. Also I don't think the "startsWith" is the best function to use since I needed something similar to "contains" in MYSQL.
Any help will be much appreciated.
I wasn't able to fix this using PHP so I used their Javascript SDK instead with toUpperCase() and toLowerCase() functions.
function capitalize(str) {
var pieces = str.split(" ");
for ( var i = 0; i < pieces.length; i++ ) {
var j = pieces[i].charAt(0).toUpperCase();
pieces[i] = j + pieces[i].substr(1);
}
return pieces.join(" ");
}
//get search term from php
var searhTerm = <?php echo json_encode($user); ?>;
//capitalize keyword for accurate results
var keyword = ".*"+capitalize(searhTerm);+".*";
//start search
var searchUser = Parse.Object.extend("_User");
//queries
var query1 = new Parse.Query(searchUser);
query1.matches("s_first_name", keyword.toLowerCase());
query1.equalTo("type", "seaman");
.
.
.
//do query find
Related
Edit:
I can output the table now but the strange thing is, trying to parse the JSON returned from PHP using JS or jQuery methods results in skipping all remaining lines in the debugger with zero output to the browser. Where as not parsing and using it to construct at table works.
Also, trying to .append() the JSON using the parse methods or not to a ` does not work.
I'm so confused right now.
Anyways, the jQuery that worked looks like this making a .post() request, notice I added the 'json' fourth parameter although it might work without it.
$(document).ready(function(){
$('#disease_btn').click(function(){
showDisease();
});
});
function showDisease(){
//var disease = $("#disease-dropdown:selected").text();
//var disease = $("#disease-dropdown:selected").val();
var disease_dropdown = document.getElementById("disease-dropdown")
var disease = disease_dropdown.options[disease_dropdown.selectedIndex].text;
var controller = 'controller.php';
$.post(controller, //url, data, callback, dataype=Json
{
page: 'SpaPage',
command: 'search-disease',
search_term: disease
},
function(disease_json, status){
//#search-results display table
//var disease_obj = JSON.parse(disease_json); this did not work
//var disease_obj = jQuery.parseJSON(disease_json); //this did not work
var disease_obj = disease_json;
//$('#test-out').append(disease_obj); /this did not work
var table = $.makeTable(disease_obj);
$('#search-results').append(table); //this worked!
}, 'json');
//https://stackoverflow.com/a/27814032/13865853
$.makeTable = function(disease_obj){
var table = $('<table border=1>');
var tblHeader = "<tr>";
for (var h in disease_obj[0]) tblHeader += "<th>" + h + "</th>";
$(tblHeader).appendTo(table);
$.each(disease_obj, function(index, value){
var tblRows = "<tr>";
$.each(value, function (key, val){
tblRows += "<td>" + val + "</td>";
});
tblRows += "</tr>";
$(table).append(tblRows);
});
return ($(table));
}
};
That table code I mimicked what I saw here: https://stackoverflow.com/a/27814032/13865853
I sort of get it but still not crystal clear on all of it. I guess it's outputting HTML so I can throw in a class for the table to take advantage of bootstrap.
On the PHP side I do this:
case 'search-disease':
$matches_arr = [];
$disease = $_POST['search_term'];
$matches_arr = search_disease($disease);
//todo: decide to use session or returned arr
if(isset($_SESSION['disease-matches_arr'])){
$matches_arr = $_SESSION['disease-matches_arr'];
}
if(count($matches_arr) > 0) {
//jsonify array here to send back
//https://stackoverflow.com/a/7064478/13865853
//https://stackoverflow.com/a/58133952/13865853
header('Content-Type: application/json');
$disease_json = json_encode($matches_arr);
echo $disease_json;
exit;
}
and then the model.php interaction with database looks like this:
function search_disease($disease_option){
// search DB for substring of question
//add results to an array of strings
//return array of strings or empty array
//
$user_id = -1;
$matches_arr = array();
$sql = "SELECT * FROM diseases
WHERE disease LIKE '%$disease_option%'";
$result = mysqli_query(Db::$conn, $sql);
if (mysqli_num_rows($result) > 0) {
//iterate
while($row = mysqli_fetch_assoc($result)){
//get username
$disease = $row['disease'];
$food = $row['food'];
$en_name = $row['en_name'];
$health_effect = $row['healthEffect'];
$metabollite = $row['metabollite'];
$citation = $row['citation'];
$next_row = array("Disease"=>$disease, "Food"=>$food,
"Name"=>$en_name, "Health Benefits"=>$health_effect, "Metabollite"=>$metabollite,
"Sources"=>$citation);
$matches_arr[] = $next_row;
}
}
$_SESSION['disease-matches_arr'] = $matches_arr;
return $matches_arr;
//https://stackoverflow.com/questions/1548159/php-how-to-sen
So I set a session variable and also return it, still have to decide which way but they are both working.
My questions still remaining are:
Why do the parse methods cause this strange behavior?
How can I just output the JSON to a testing <div>?
If you have to return data from PHP to javascript you must have use json_encode() if data type is array otherwise just return.
To take action with array type data by javascript you have to decode this json data by JSON.parse() function.
Array example
$data = array('carname' => 'TOYOTA','model'=>'ARTYIR500');
echo json_encode($data);
exit;
String example
echo 'lorem ipsum is a simple text';
exit;
How do I get the html space characters out of my dynamic text loaded from a text file?
This is what my loaded text looks like in my .swf:
Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D
And it's my actionscript:
var select_obj:LoadVars = new LoadVars();
select_obj.onLoad = function(success:Boolean) {
if (success) {
isi.text = select_obj;
trace (select_obj);
} else {
trace('error...');
}
};
filepath = "http://localhost/adaptasi/";
select_obj.sendAndLoad(filepath + "morfologi.php", select_obj, "GET");
Here is my PHP script:
<?php
mysql_pconnect ("localhost", "root", "");
mysql_select_db ("adaptasi");
$qResult = mysql_query ("SELECT isi FROM materi WHERE id = 1");
$nRows = mysql_num_rows($qResult);
$rString ="";
for ($i=0; $i< $nRows; $i++){
$row = mysql_fetch_array($qResult);
$rString .= $row['isi'];
}
echo $rString;
?>
To get your values sent by your script, you should return them as a URL-encoded query string containing name/value pairs like this :
message=hello&from=user1&to=user2
which can be returned by your PHP script :
<?php
echo "message=hello&from=user1&to=user2";
?>
then the LoadVars object will decode (parse) that variable string automatically for you as properties of the LoadVars object :
var result:LoadVars = new LoadVars();
result.onLoad = function(success:Boolean) {
if (success) {
trace(result.message); // gives : hello
trace(result.from); // gives : user1
trace(result.to); // gives : user2
trace(result); // gives : to=user2&from=user1&message=hello&onLoad=%5Btype%20Function%5D
} else {
trace('error !');
}
};
result.sendAndLoad(filepath, result);
Hope that can help.
Use urldecode() function:
<?PHP
$string = "Adaptasi%20morfologi%20adalah%20penyesuaian%2E%2E%2E%0D%0A%0D%0A=&onLoad=%5Btype%20Function%5D";
//$string = $_GET['variable'];
$rString = urldecode($string);
echo $rString;
I wanna erase %20, %2E%2E%2E%, and etc..
For that you can try either decodeURIComponent or just decodeURI. Read that manual for differences (but for your current result, any of these two is good).
An example with your code :
var result:LoadVars = new LoadVars();
var filepath:String;
filepath = "localhost/adaptasi/";
result.sendAndLoad(filepath + "morfologi.php", result, "GET");
result.onLoad = function(success:Boolean)
{
if ( success )
{
text_morfo.text = result;
text_morfo = decodeURIComponent( text_morfo );
trace("success route : "); trace( text_morfo );
}
else { trace("error in result..."); }
}
Also I don't know what else your AS & PHP code will add later so if you need a quick testing tool you can try this link. Just put your traced results into the bottom box and choose option (like unescape, decodeURI etc). This will quickly help you see which command is best to use in your AS code.
I have a array stored in a PHP file in which I am storing all the values.
I am trying to loop through the entire array in JavaScript. How should I do that?
The following does not work:
var index = 0;
var info = 1;
while(index<4) {
info = <?php echo $a[?>index<?php];?>
index++;
}
You can copy array from php to JavaScript and then process it.
var array = <?php echo json_encode($a); ?>
var index = 0;
var info = 1;
while(index<4) {
info = array[index];
index++;
}
I don't know what version of php you're using, but try something like this:
var info = null;
var a = <?php echo json_encode($a); ?>;
for(var index=0;index<a.length;index++) {
info = a[index];
}
You need to process the PHP into Javascript first. You can use json_encode to do this.
var index = 0;
var info = 1;
var a = <?php echo json_encode($a); ?>;
while(index < 4) {
info = a[index];
index++;
}
PHP runs on the server side, before the final page is served to the client.
Javascript runs on the client side (on the browser).
Therefore, what you are trying to achieve won't work. What you can do is use PHP to print the javascript code dynamically.
So i'm working on a javascript/php chatbox. Everything works except for it updating the contents of my div (this works once, but after that it doesn't keep updating it when a new message has been put into the database). Here is my code:
Javascript part:
<script language=javascript type='text/javascript'>
setInterval(function () {
var arrayOfObjects = <?print_r(getChatArray());?>;
var chat = "";
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
chat += "["+object.date+"]"+object.op+": " + object.msg + "</br>";
}
$('#chat').html(chat);
}, 10);
</script>
Php part:
<?php
function getChatArray() {
$result = mysql_query("SELECT * FROM shouts ORDER BY id DESC");
$to_encode = array();
$count = mysql_num_rows($result);
$size = 0;
if($count > 0) {
while($row = mysql_fetch_assoc($result)) {
$to_encode[$size]['id'] = $row['id'];
$to_encode[$size]['msg'] = $row['msg'];
$to_encode[$size]['op'] = $row['op'];
$to_encode[$size]['date'] = $row['date'];
$size += 1;
}
} else {
return "None";
}
return json_encode($to_encode);
}
?>
Any ideas as to why it isn't continually updating it?
Thanks.
Because every 10 milliseconds your JS is parsing the original chat room contents, you're not fetching any new contents. You'll need to implement an ajax call, and I'd highly recommend changing that setInterval to a recursive setTimeout with a more realistic delay of say 500ms so you don't kill the client.
Instead of this:
setInterval(function() {
var arrayOfObjects = <?print_r(getChatArray());?>;
...
You would use something like this:
(function updateChat(){
var arrayOfObjects,
chat,
max,
_object,
i = 0;
$.ajax({
url : '/getChatArray.php', // php echoes the json
success: function(arrayOfObjects){
for (max = arrayOfObjects.length; i < max; i++) {
_object = arrayOfObjects[i];
chat += "["+_object.date+"]"+_object.op+": " + _object.msg + "</br>";
}
$('#chat').html(chat);
setTimeout(updateChat, 500);
}
});
}());
Obviously you would populate that ajax handler to your needs, add some more params like dataType, etc, and some error handling.
Your database contents will only be output to the page on initial navigation to it.
This code:
var arrayOfObjects = <?print_r(getChatArray());?>;
Will only output the contents of getChatArray()'s return when PHP renders the page. So the script can only see one state of that functions return at the time of rendering.
You need to use AJAX to retrieve the content from your database asynchronously.
I suggest you:
Create a PHP script which outputs your data in JSON format
Use jQuery, specifically the getJSON function to retrieve that script's output
Do what you want to do with that data.
I have a foreach loop that creates a string in php , I'm unable to pass the string value to mootools in wordpress (I'm integrating a MooTool function ) :::
I need to substitute the "hard coded" image URL's in the new Array() (below) with a variable created from my php string eg. new Array( $myimageurl ) :::
I've created a var from the php string even tried json_encode , with no luck :::
window.addEvent("domready", function(){
var counter = 0;
var images = new Array('http://localhost/square/wp-content/uploads/2011/10/test-foo/foo.jpg','http://localhost/square/wp-content/uploads/2011/10/test-foo/foo1.jpg');
er, why not just:
var foo= <?=json_encode(Array("foo.jpg", "bar.jpg"))?>;
EDIT
Since you implied in a comment your files source is comma separated, then do this instead:
<? $files = "foo.jpg,bar.jpg"; ?>
var foo = <?=json_encode(explode(',', $files))?>;
where the array could be anything of any length, read from wherever. it will result in an array literal looking like so:
var foo = ["foo.jpg","bar.jpg"];
// eg use.
foo.each(function(img) {
new Element("img", {src: img}).inject(document.body);
));
nb: just noticed #Marc B has already mentioned json_encode. sorry, will delete
try:
var images = new Array('<?php echo $miImageUrl[0];?>', '<?php echo $miImageUrl[1];?>');
Other way:
<?php
//sample data
$descargables[0] = 'cero';
$descargables[1] = 'uno';
$descargables[2] = 'dos';
$descargables[3] = 'tres';
// end sample data
$arrayToJs="var descargables = new Array();";
for ($i=0; $i < count($descargables); $i++) {
$arrayToJs .= "descargables[" . $i . "]='" . $descargables[$i]. "';";
}
?>
<script>
<?php echo $arrayToJs;?>
idx = 3;
alert("descargable:" + descargables[idx]);
</script>