Jquery : JSON changes string of path - php

I am trying to get list of image path from my db and with help of Jquery and Json triying to add to my site. But I dont know why after encoding my string usingjson_encode` in php it changes it path and shows me like
[{"0":"user\/photogallery\/images\/members\/2\/2_1.jpg","src":"user\/photogallery\/images\/members\/2\/2_1.jpg"},{"0":"user\/photogallery\/images\/members\/2\/2_2.jpg","src":"user\/photogallery\/images\/members\/2\/2_2.jpg"}]
I need only user/photogallery/images/members/2/2_2.jpg part to create new <img src ="user/photogallery/images/members/2/2_2.jpg " /> component.
Here my php code and script
$member_id = $GET['member_id'];
$files = find_all_photos($member_id);
$encoded = json_encode($files);
echo $encoded;
unset($encoded);
function find_all_photos($id)
{
db_connect();
$query = sprintf("SELECT src FROM photo_album_list WHERE user_id = '%s'",
mysql_real_escape_string($id));
$result = mysql_query($query);
$result = db_result_to_array($result);
return $result;
}
function db_result_to_array($result)
{
$res_array = array();
for ($count=0; $row = mysql_fetch_array($result); $count++)
{
$res_array[$count] = $row;
}
return $res_array;
}
And script
$.get('photostack.php', {member_id:2} , function(data) {
console.log(data);
var items_count = data.length;
for(var i = 0; i < items_count; ++i){
var item_source = data[i];
var cnt = 0;
$('<img />').load(function(){
var $image = $(this);
++cnt;
resizeCenterImage($image);
$ps_container.append($image);
var r = Math.floor(Math.random()*41)-20;
if(cnt < items_count){
$image.css({
'-moz-transform' :'rotate('+r+'deg)',
'-webkit-transform' :'rotate('+r+'deg)',
'transform' :'rotate('+r+'deg)'
});
}
if(cnt == items_count){
$loading.remove();
$ps_container.show();
$ps_close.show();
$ps_overlay.show();
}
}).attr('src',item_source);
}
},'json');

It sounds like you're bothered that backslashes are being added prior to the slashes in the path. Completely agree that that's very odd (there's no need whatsoever to "escape" a slash in JSON strings), but in most notations it's harmless to escape a character that doesn't require escaping if that character doesn't have a special escaped meaning. (That is, it's harmless to escape / even though it doesn't need it, but obviously not harmless to escape n even though it doesn't mean it, since \n means something).
To my eyes, the JSON page is silent on what to do with invalid escapes, but Crockford's own parser allows them (disregards the unnecessary backslash), so... (Crockford being the inventor of JSON.)

It's possible that the escaped backslashes are stored in the DB that way, so your JSON string is just pulling them verbatim. If you want to remove them you'll need to process the string returned from the DB before you return or json_encode() them.

Related

php how to return JSON for jQuery .get() or .post() request, parse it and output to browser

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;

Fatal error: Uncaught Error: Class 'Func' not found php

My Questions is Find a 7 letter string of characters that contains only letters from
acegikoprs
such that the gen_hash(the_string) is
675217408078
if hash is defined by the following pseudo-code:
Int64 gen_hash (String s) {
Int64 h = 7
String letters = "acegikoprs"
for(Int32 i = 0; i < s.length; i++) {
h = (h * 37 + letters.indexOf(s[i]))
}
return h
}
For example, if we were trying to find the 7 letter string where gen_hash(the_string) was 677850704066, the answer would be "kppracg".
Solution
test1.php
I did that question solve in php, I am unable to run this code I am in php i don't have that much knowledge regarding php class and their function, Can any one solve this code and describe me. thanks in advance i will be very great full if anyone help me.
<?php
$set = "acdegilmnoprstuw";
$CONST_HASH = 7.0;
$CONST_MULT = 37.0;
$hash = new Func(function($string = null) use (&$CONST_HASH, &$CONST_MULT, &$set) {
$_hash = $CONST_HASH;
for ($i = 0.0; $i < get($string, "length"); $i++) {
$_hash = _plus(to_number($_hash) * to_number($CONST_MULT), call_method($set, "indexOf", get($string, $i)));
}
return $_hash;
});
$decode = new Func(function($_hash = null) use (&$CONST_MULT, &$Math, &$set) {
$decoded = ""; $positionsInSet = new Arr();
for ($i = 0.0; $_hash > $CONST_MULT; $i++) {
set($positionsInSet, $i, call_method($Math, "floor", (float)(to_number($_hash) % to_number($CONST_MULT))));
$_hash /= 37.0;
}
for ($i = to_number(get($positionsInSet, "length")) - 1.0; $i >= 0.0; $i--) {
$decoded = _plus($decoded, get($set, get($positionsInSet, $i)));
}
return $decoded;
});
I realize that this question was asked well over a year ago and I'm only just stumbling on it right now but seeing as there hasn't been an answer I figured I'd answer it.
You used a third party JavaScript to PHP converter utility and expected the demo to work out of the box. You should have read up on it's usage as it clearly states in the ReadMe.md that, ...this tool is using esprima JavaScript parser with rocambole to walk the AST and escope to figure out the variable scope, hoist function declarations and so on...
The developer goes on to say, After AST manipulation tools/codegen.js generates the PHP code by walking the tree. Now here's where it gets good. Pay attention now..
Various constructs get wrapped in helper functions, for instance,
property access, method calls and + operator. The runtime helpers
can be found in php/helper and there are a bunch of classes in
php/classes for Array, RegExp and such. All this PHP gets packaged
into your output file, or you can save it to a standalone runtime and
reference that from your output file like so:
js2php --runtime-only > runtime.php
js2php --runtime runtime.php example.js > example.php
You can also specify the output file using -o or --out and you can
compile multiple input files into one output file like so:
js2php -o example.php file1.js file2.js
So as you can see my friend, to get your code to work you merely need to include the runtime helpers functions so your converted script can be interpreted. I'm not sure as to which files it'll take to get your script to parse correctly, however now that I've pointed you in the right direction I'm confident you'll be able work it out yourself.
Happy coding..
=)
Instead of assigning the inline function with new operator to variable, create a separate functions encode and decode where you can do the hashing and matching the hash code.
Let me give you the snippet of how to do it. I am assuming that your using plain PHP.
/* Call to function encode which returns you the encoded value and store in $encode variable */
$encode = encode($par1, $par2);
/* Call to function decode which returns you the decoded value and store in $decode variable */
$decode = decode($par1, $par2);
/* Function to encode your code */
function encode($par1, $par2){
return $encode_value
}
/* Function to decode your code */
function decode($par1, $par2){
return $decode_value
}
I have written this in Javascript to generate both Hash String and Number
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
var gen = gen_hash('kppracg');
document.write("kppracg hash value is ", gen);
document.write('<br><br>');
var gen = gen_hash('iorocks');
document.write("iorocks hash value is ", gen);
var hash = 675217408078;
var gen_rev = gen_hash_rev(hash);
document.write('<br><br>');
document.write("675217408078 hash value is ", gen_rev);
function gen_hash(s) {
var h = 7;
var acegikoprs = "acegikoprs";
for(var i = 0; i < s.length; i++) {
h = (h * 37 + acegikoprs.indexOf(s[i]));
}
return h;
}
function gen_hash_rev(hash) {
var arr_values = ['a','c','e','g','i','k','o','p','r','s'];
var min = 0;
var max = 99999999;
while (min <= max) {
var final_result = "";
var tempInt = parseInt(((max - min) / 2) + min);
var arr_tempInt = num_array(tempInt);
for(var i = 0; i < arr_tempInt.length; i++) {
final_result = final_result + arr_values[arr_tempInt[i]];
}
var result = gen_hash(final_result);
if(result < hash) {
min = tempInt + 1;
}
else if( result > hash) {
max = tempInt - 1;
}
else {
return final_result;
}
}
}
function num_array(num){
var output = [],
sNumber = num.toString();
for (var i = 0, len = sNumber.length; i < len; i += 1) {
output.push(+sNumber.charAt(i));
}
return output;
}
</script>
</body>
</html>

%20 and other misc stuff in my dynamic text

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.

undetermined string literal error

How do I fix this unterminated string literal error. What does this error mean and how can it be fixed
Below is the full code:
<?php
session_start();
if(isset($_POST['fileImage'])){
$idx = count($_POST ['fileImage']) -1 ;
$output = isset($_POST ['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";
}
?>
function stopImageUpload(success) {
var imageNameArray = ['<?php echo json_encode($output); ?>'];
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (var i = 0; i < imageNameArray.length; i++) {
$('.listImage').append(imageNameArray[i] + '<br/>');
}
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
return true;
}​
It means that there's something wrong with your quotes (an extra single quote in the echo'd content, or a line feed) and it's messing up the parser. Make sure any characters that are special in JS (quotes, line breaks etc) are properly escaped.
json_encode does this for you.
A better solution might look like this:
<?php
session_start();
$results = array();
if(isset($_POST['fileImage'])){
// not entirely sure what you're trying to achieve here
// so just replicating the logic you already had
// but I'm sure there's a better way to do whatever this is trying to do
$idx = count($_POST['fileImage']) -1 ;
$results[] = isset($_POST['fileImage'][$idx]) ? $_POST ['fileImage'][$idx]['name'] : "";
}
?>
function stopImageUpload(success) {
var imageNameArray = <?php echo json_encode($results); ?>;
var result = '';
if (success == 1) {
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
for (var i = 0; i < imageNameArray.length; i++) {
$('.listImage').append(imageNameArray[i] + '<br/>');
}
} else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
// you might want to use the "result" variable before returning
return true;
}​
What changed? I removed the [] around the output of json_encode and made the array in PHP instead of JS. This way, when you do post the form, $results will be an array with a single element, and when you don't, it'll be an empty array. The rest of the logic should work just like before, but do read the comments I added.

not validating special character "_" in javascript

hello i am using javascript to validate field
i am checking special characters.. the code i am implementing validates all the special characters except _ underscore..
<script type="text/javascript" language="javascript">
function validateForm()
{
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?_";
for (var i = 0; i < document.reg_form.txtusername.value.length; i++)
{
if (iChars.indexOf(document.reg_form.txtusername.value.charAt(i)) != -1)
{
alert ("Special Characters are not allowed.");
return false;
}
}
return true;
}
</script>
for this filed
<input name="txtusername" type="text" id="txtusername" maxlength="10" style="background-color:#CCC" />
but its not validating the underscore
Would it not make sense to just shove it into your iChars variable, which is quite obviously your "blacklist"?
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?_";
var iChars = "!##$%^&*()+=-[]\\\';,./{}|\":<>?_";
for (var i = 0; i < document.reg_form.firstname.value.length; i++)
{
if (iChars.indexOf(document.reg_form.firstname.value.charAt(i)) != -1)
{
alert ("Special Characters are not allowed");
return false;
}
}
characters in strings can be addressed as if the string were an array (which, if you think about it, it is). Since you're looping through the string char-per-char, again, as you would with an array, why not be consistent in your logic?
if (iChars.indexOf(document.reg_form.firstname.value[i]) !== -1)
{
alert('Foobar');
return false;
}
That should work... Also: there's no real need to escape the single quote, since the iChar string is delimited by double quotes... if all else fails, you might want to try omitting that backslash, too. Though I don't think that's what's causing the problem
It is working: here

Categories