unable to retrive + characters using php and ajax - javascript

Hello friends facing a problem with AJAX and PHP ???
Let me tell you what i did ...!
I created 2 pages
one page (AJAX_view.php) with a drop down with all the blood group in short code like (b+, b-) and i placed my ajax code on the same page. to asynchronously search for the blood groups available in database (MySql).
Now the another page (search.php) has all the php code and the query to retrieve the data from database..
Now the real problem is from the 1st page i passed the string in url to the another page using the code
xmlhttp.open("POST","search.php?q="+str,true);
xmlhttp.send();
and the str here is 'B+' without quotes
and it doesnt reads the "+" , what it reads is only B... this only happens in the case of "+ " while if i pass the string str as "A-" its give the result without any problem or error and returns result from database
but there are certain blood group like B+ ,AB+ , O+ and there is no result show for them.
$q=$_GET['q'];
this is how i retrieve the string on search page..
$select_query="SELECT * FROM blood_donate WHERE blood_group='$q'";
$res=mysql_query($select_query);
this is how i select data from database??
please help

You need to encode +, otherwise it'll be treated as space (). Use encodeURIComponent on str for this.
xmlhttp.open("POST","search.php?q="+encodeURIComponent(str),true);
if str is A+ without encodeURIComponent it'd generate url search.php?q=A+. This makes $_GET['q']='A ' at the PHP end. (note the space)
With encodeURIComponent it'd be search.php?q=A%2B which yields $_GET['q']='A+'.

Related

send string from javascript to php to sql (and reverse)

I'm going mad with string encoding between js/php/sql
I created a web site, with a public and an administrative part. I use javascript in the front end (I'm not using jquery). Php and mysqli in backend.
In the public part, I have some text in differents parts : as full visible text ans in tag like title="", alt=""
In the administrative part, the owner of the site can add text from input[text] element. He can write any text he want, so I need to encode everything correctly. Then the text is send to a php page by a xmlHttpRequest/JSON
[removed text, I edit the question below]
If I have a quote or &quot ; or ", or & or &amp ; or #xx;, the text in the title tag or in the display text will be different.
Is there a clear/simple way to send/retreive/display data from js to php and from php to js ?
EDIT
I didn't send code because I try lots of possibilities, and never ever found a solution.
I try to explain better
admin :
the user can add photos, with title and text to each. I use an input for title and text.
When he save the data
for(i=0;i<listimage.length;i++)
{
listimage[i]['title']=encode(document.getElementById("inputtitle"+i).value);
listimage[i]['texte']=encode(document.getElementById("imputtext"+i).value);
}
gdata={big:masonrybig,larg,listimage:listgalerieimage};
let postdata="key="+keypage+"&data="+JSON.stringify(gdata);
In the encode function, I try lots and lots of thing
function encode(str)
{
return encodeURIcomponent(str);
return encodeURIcomponent(he.encode(str));
return he.encode(encodeURIcomponent(str));
return myOwnEncodingFunction(str); //like htmlspecialchar, htmlentities,..
}
in php :
$data=json_decode($_POST["data"]); //always, the data received are JSON string
//and one or more of the following functions
$data=trim($data);
$data=stripslashes($data);
$data=strip_tags($data);
$data=htmlspecialchars($data);
$data=mysqli_real_escape_string($data);
$data=htmlentities($data);
$data=str_replace('\','\',$data);
$data=str_replace('"','\"',$data);
$data=str_replace("'","\'",$data);
$data=addslashes($data);
$data=htmlspecialchars($data,ENT_NOQUOTES | ENT_SUBSTITUTE | ENT_HTML401, "UTF-8");
And when I want to display the data
reading from the database
while ($row = $result->fetch_object())
{
$image=array();
$image['title']=$row->title;
$image['text']=$row->text;
array_push($listimage,$image);
}
echo($listimage)
displaying the data ($datapage['content']['listimage'] = echo($listimage)
for($i=0;$i<count($datapage['content']['listimage']);$i++)
{
$ititle=$datapage['content']['listimage'][$i]['title'];
$itexte=$datapage['content']['listimage'][$i]['text'];
$tititle=htmlspecialchars($ititle);
$titext=htmlspecialchars($itext);
echo('<a href="someurl" title="'.$tititle.$titext.'>');
echo('<img id="img'.$i.' src="someurl" alt="'.$tititle.'">');
echo('<div>'.$ititle.'</div>');
echo('</a>');
}
Here I use htmlspecialchars, but I tried almost every (combination of) functions I can imagine
When the input text contains quote, &, slash, ', ... Some part of the display is ok, some are not, depends of the encoding/decoding functions I use, and the characters.
For exemple with & : with no coding, the json_decode in php send an error, as the & is considered as a url paramater (https:www.xxx.com?a=1 & b=2). If I encodeURIcomponent the &, the json_decode is ok, but when I want to display it, the title tag in the img tag will show &amp ; and the html text will show & (of course it depends of the functions I use to decode the string). Sometimes it works well everywhere, except for one character at one point of the process. And when I find a solution for this particular case, it creates a problem somewhere else for another character.
The problem occurs mainly with the characters & " ' \ < >. For example, I try that string : < " '& \ \ \ ' <<> "'"' (here another problem : \ ' is two characters written by the user, and must no be interpreted as an escaping ' )
I never find the good combinations of functions to send, store and retreive the text, there is always a problem somewhere

javascript add text to string sent to DB

I am using appery.
I want the number in a text input to be sent to a database, which it is. Problem is that I need to add the short text 'Tel:' before the actual number. So the string in the database will sa Tel: XXX(the number).
I have tried now for two days and really can't get it to work even if it seems like an easy task. All it does is that is sends the number. (trying prepend, but obviously doing it wrong)
Any help would be very appreciated!
If you are using Appery try this,
"tel:" + Apperyio(name of your text component in string).val();
You can try this
var number = "tel:" + document.getElementByID("Input_Field_ID").value;
now sent this number (variable) to Database

apostrophe mark is sent with Backslash in javascript string which is being sent to php page using ajax as part of json object

apostrophe mark is sent with Backslash in JavaScript string which is being sent to php page using ajax as part of json object
var qry="SELECT
invpurchaseitme.Code,
invpurchaseitme.Description,
invunits.Description,
invpurchaseitme.StoreGroup
FROM
invpurchaseitme
LEFT JOIN
invunits
ON
(invpurchaseitme.UOMCode = invunits.Code)
WHERE (
invpurchaseitme.Code LIKE '%d#t#%'
OR
invpurchaseitme.Description LIKE '%d#t#%'
OR
invunits.Description LIKE '%d#t#%'
OR
invpurchaseitme.StoreGroup LIKE '%d#t#%'
)
AND
invpurchaseitme.StoreGroup='"+$("#StoreCode").val()+"'
ORDER BY invpurchaseitme.Code ASC
LIMIT 70"
I am replacing d#t# character with a php variable in the php page using explode() after it is being sent using ajax to the php page. But what I get in the final query is \'%variablename%\' instead of '%variablename%'. I have tried using slashes for escaping ' but the result is same. how to get string without slashes
This solved my problem. stripslashes(str).
http://us1.php.net/stripslashes

javascript and html character escaping

I have this problem:
I have a javascript, saved in a database field, that is going to be used in a web page as a href target, e.g.
insert into table_with_links (id, url)
values (1, 'javascript:var url="blö blö";.....');
// run scripts that use the database values to generate web pages
// part of the generated html code:
<a href="javascript:var url='blabla';..... </a>
So far no problems. I have german letters (Umlaute - e.g. ö) in the javascript. I shouldn't save the german letters in the database, so I escape them:
insert into table_with_links (id, url)
values (1, 'javascript:var url="bl%F6 bl%F6";.....');
Now comes the problem - I shouldn't store the % sign in the database either, because the scripts that generate the web pages cannot handle it properly. I guess you can imagine how these scripts are 3-rd party scripts and cannot be changed.
So, my question is - can I also escape the % sign?
did you tryed this? :
var str= "remove the %";
var str_n = str.replace("%","");
here are the basics http://www.w3schools.com/jsref/jsref_replace.asp
then you can use an array of chars to replace take a look here javascript replace globally with array
I would suggest using oracle's built in internationalization, Oracle is capable of handling special german characters:
http://docs.oracle.com/cd/B19306_01/appdev.102/b14258/u_i18n.htm
If you want to handle it on your own, I would suggest doing a string replace to some sequence you know:
var str = str.replace(/ö/g,"[german-umlaute]");
(the g at the end of /ö/g is to replace all occurrences in the string)

POST data issues

I have an issue with submitting post data. I have a form which have a couple of text fields in, and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string like
title=test&content=some content
which is then submitted to the server. The problem I had is when I have '&' (eg &nbsp) entered into one of the inputs which then breaks up the query string. Eg:
title=test&content=some content &nbsp
How do I get around this?
Thanks in advance,
Harry.
Run encodeURIComponent over each key and value.
var title = "test";
var content = "some content &nbsp ";
var data = encodeURIComponent('title') + /* You don't actually need to encode this as it is a string that only contains safe characters, but you would if you weren't sure about the data */
'=' + encodeURIComponent(title) +
'&' + encodeURIComponent('content') +
'=' + encodeURIComponent(content);
Encode the string..when you want to encode a query string with special characters you need to use encoding. ampersand is encoded like this
title=test&content=some content %26
basically any character in a query string can be replaced by its ASCII Hex equivalent with a % as the prefix
Space = %20
A = %41
B = %42
C = %43
...
You need to encode your query to make it URL-safe. You can refer to the following links on how to do that in JS:
http://xkr.us/articles/javascript/encode-compare/
http://www.webtoolkit.info/javascript-url-decode-encode.html
You said:
...and when a button is pressed to submit the data, it is run through a custom from validation (JS), then I construct a query string...
In the section where you are building the query string you should also run the value of each input through encodeURIComponent() as David Dorward suggested.
As you do - be careful that you only assign the new value to your processed query string and NOT the form element value, otherwise your users will think their input was somehow corrupted and potentially freak out.
[EDIT]
I just re-read your question and realized something important: you're encoding an &nbsp ;character. This is probably a more complicated issue than other posters here have read into. If you want that character, and other &code; type characters to transfer over you'll need to realize that they are codes. Those characters &, n, b, s, p and ; are not themselves the same as " " which is a space character that does not break.
You'll have to add another step of encoding/decoding. You can place this step either before of after the data is sent (or "POSTed").
Before:
(Using this question's answers)
var data = formElement.value;
data = rhtmlspecialchars(data, 0);
Which is intended to replace your "special" characters like with " " so that they are then properly encoded by encodeURIComponent(data)
Or after:
(using standard PHP functions)
<?PHP
$your_field_name = htmlspecialchars_decode(urldecode($_POST['your_field_name']));
?>
This assumes that you escaped the & in your POST with %26
If you replaced it with some function other than encodeURIComponent() you'll have to find a different way to decode it in PHP.
This should solve your problem:
encodeURIComponent(name)+'='+encodeURIComponent(value)+'&'+encodeURIComponent(name2)+'='+encodeURIComponent(value2)
You need to escape each value (and name if you want to be on the safe side) before concatenating them when you're building your query.
The JavaScript global function encodeURIComponent() does the escaping.
The global function escape() (DOM) does this for you in a browser. Although people are saying it is not doing the escaping well for unicode chars. Anyway if you're only concerned about '&' then this would solve your problem.

Categories

Resources