Javascript Quotes Problem When Dynamically Adding Content - javascript

I'm trying to dynamically add content stored in a variable. However, single quotes are causing problems.
var dynamicelementcode = $("<div id='container'>" + data + "</div>");
dynamicelementcode.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);
If the data variable contains a single quote, it breaks my code. How can I solve this problem? The data variable gets its content from a serverside php script.
Any php/js/jquery solution appreciated
Edit:
PHP Code Serverside
$comment_body = "The boy's bicycle";
echo '{ "author": "'.$author.'", "message": "'.$comment_body.'","parentid": "'.$parent_id.'","currentid": "'.mysql_insert_id().'","timestored": "'.$timestampa.'" }';
Jquery Code, Clientside
var newrootcomment = $("<div class='comment'><div class='comment-holder'><div class='comment-body'>"+ data.message + "</div> <abbr class='timestamp' title=''>" + data.timestored + "</abbr><div class='aut'>" + data.author + "</div> <a href='#comment_form' class='reply' id='id"+ data.currentid + "'>Reply</a> </div> </div>");
newrootcomment.prependTo($('#wholecontainer')).hide().fadeIn(300).slideDown(1000);

var dynamicelementcode = $('<div id="container">').text(data)
jQuery text function automatically escapes quotes for you.
UPD. Escaping only single quotes:
var dynamicelementcode = $('<div id="container">').html(data.replace(/'/g,'''))
UPD 2. If you look at the source of your page you'll see something like "message": 'The boy's bicycle' - that's a syntactic error.
Here's a better way to pass PHP data to JavaScript, works with quotes too:
$comment_body = "The boy's bicycle";
echo json_encode(array(
'author' => $author,
'message' => $comment_body,
'parentid' => $parent_id,
'currentid' => mysql_insert_id(),
'timestamp' => $timestamp
));

jQuery already has methods to insert text, you don't need to concatenate strings or take care yourself of escaping. Use the .text() method:
var dynamicelementcode = $('<div id="container"></div>').text(data);
Reference and examples: http://api.jquery.com/text/#text2

Related

How to add rel="nofollow" to all external links that do not related to my domain with javascript?

I have the following html string with three links:
var html = '
Go to help page
Go to blog page
Go google
';
My domain name is example.com. As you can see from the code above there is two internal links and one external.
I need to write "magic" function that adds rel="nofollow" attribute to all external links (not internal ones). So I need to get the following result:
var html = '
Go to help page
Go to blog page
Go google
';
I'm trying to write that function and this is I have at the time:
function addNoFollowsToExternal(html) {
// List of allowed domains
var whiteList = ['example.com', 'blog.example.com'];
// Regular expression
var str = '(<a\s*(?!.*\brel=)[^>]*)(href="/https?://)((?!(?:(?:www\.)?' + whiteList.join(',') + '))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>',
// execute regexp and return result
return html.replace(new RegExp(str, 'igm'), '$1$2$3"$4 rel="nofollow">');
}
Unfortunately my regexp seems does't work. After executing addNoFollowsToExternal(html) rel="nofollow" don't added to external link with href="https://google.com"
Please help me with fixing my regular expression to resolve my task.
There were some minor mistakes in your RegEx. Here is a corrected version:
function addNoFollowsToExternal(html){
var whiteList = ['([^/]+\.)?example.com'];
var str = '(<a\s*(?!.*\brel=)[^>]*)(href="https?://)((?!(?:' + whiteList.join('|') + '))[^"]+)"((?!.*\brel=)[^>]*)(?:[^>]*)>';
return html.replace(new RegExp(str, 'igm'), '$1$2$3"$4 rel="nofollow">');
}
you can also use function below
private function _txt2link($text){
$regex = '/'
. '(?<!\S)'
. '(((ftp|https?)?:?)\/\/|www\.)'
. '(\S+?)'
. '(?=$|\s|[,]|\.\W|\.$)'
. '/m';
return preg_replace_callback($regex, function($match)
{
return '<a'
. ' target="_blank"'
. ' rel="nofollow"'
. ' href="' . $match[0] . '">'
. $match[0]
. '</a><br/>';
}, $text);
}

Reg Ex doesnt validate if i use # along with other characters or number

this is the same question i asked before. sorry but i check all the link provided it doesnt help. and sorry this is the first time i asked question here so was not very clear about how to ask
I am explaining here again with full details:
i have an input text field.
I Use jquery to validate the input date entered by user in this input box.
I pass the data enter as parameter in javascript GET method and pass it to PHP and validate it there with simple REG Ex. It does validate in all account. But if i add # with any test case this validation fails.
my code:
Input field:
<div id="clntFstName" >
<label for="clnt_fst_name">First Name</label>
<input type="text" id="clnt_fst_name" name="clnt_fst_name" onBlur="checkFieldValid(this.value, this);" value=""/>
<div class="msgError"></div>
</div>
If you the function CheckFieldValid is called as the user leaves a field input box.
java script:
function checkFieldValid(value, obj) {
var elem = obj.name;
$('#' + elem).parent().children('.msgError').html('');
var $label = $("label[for='" + obj.id + "']").text();
var $id = obj.id;
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" + value + "&lab=" + $label + "&id=" + $id, function(json) {
if (json.status.length > 0) {
$.each(json.status, function() {
if (this['fail'] == 'fail') {
var info = '<div class="warningMsg"> ' + this['message'] + '</div>';
$('#' + elem).parent().children('.msgError').html(info);
$('#' + elem).focus();
$('#' + elem).val("");
}
if (this['success'] == 'success') {
$('#' + elem).parent().children('.msgError').html('this is success');
}
});
if (json.status == 'empty') {
$('#' + elem).parent().children('.msgError').html('this is empty');
}
}
});
}
PHP code:
if($_GET['action'] == 'checkInputFieldValid'){
if(!empty($_GET['varField'])){
// this creates dynamic session variables and add values to it.
$_SESSION[$_GET['id']] = $_GET['varField'];
if(preg_match('/^[a-zA-Z]+$/',$_GET['varField'])){
$txtVar = 'It is a valid '.$_GET['lab'];
array_push($validFieldArray, array('success' => 'success', 'message' => $txtVar));
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 0;
}else{
$txtVar = 'Enter a valid '.$_GET['lab'];
array_push($validFieldArray, array('fail' => 'fail', 'message' => $txtVar));
unset($_SESSION[$_GET['id']]);// unset the session variable to clear when page refresh
echo json_encode(array('status' => $validFieldArray));
$errorJScript = 1;
}
}
}
I dont know where I am wrong? I did all as told by other members May be I am doing something wrong with Java script when I pass the GET request variables? as far as
I think I did exactly what other member told me about PHP part. but may be the data is wrong when i take it from Java script part? As i checked it with other values return from PHP. but when I put # in my input box IT does not make the AJAX call and doesnt return the JSON nor set the session variable. So probably when I pass the varible as GET parameter It doesnt run the AJAX and just doesnt validate so plz tell me how can i pass # as GET parameter so that i correctly validate the fields in my PHP .
Plz help I will loos my job :(
Your $.getJSON call should use encodeURIComponent() to make sure you're not creating the wrong URL:
$.getJSON("ajax/registerClient.php?action=checkInputFieldValid&varField=" +
encodeURIComponent(value) +
"&lab=" +
encodeURIComponent($label) +
"&id=" +
encodeURIComponent($id), function(json) {
If you don't do that, then a # character will be interpreted as signalling the start of the hash field of the URL, and the rest of the URL will be ignored.

Bring from a PHP file data sent by $.ajax using Json

As I need to bring separate data from a php file, and create an HTML piece to be injected with jQuery, I've choosen Json.
I send it from my PHP main file (between script tags) like this:
$.ajax({dataType: "json", url:'course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
This sends properly editedCourseId value. And what's inside course_generator.php is:
$courseId = $_POST['co_subj_co'];
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$newCourseId = $result_co['co_id'];
$newCourseName = $result_co['co_name'];
$newCourseAbbrev = $result_co['co_abbrev'];
$newCourseTypeId = $result_co['co_fk_ct_id'];
$newCourseTypeName = $result_co['ct_name'];
$isMultisubjectValue = $result_co['co_multisubject'];
$newCourseValues = '{"newCourseId":'.$newCourseId.',"newCourseName":'.$newCourseName.',"newCourseAbbrev":'.$newCourseAbbrev.',"newCourseTypeId":'.$newCourseTypeId.',"newCourseTypeName":'.$newCourseTypeName.',"isMultisubjectValue":'.$isMultisubjectValue.'}';
I am afraid Im not receiving it properly by $courseId = $_POST['co_subj_co'];, and neither $newCourseValues are being received properly on my main PHP file as my newCourseStructure is not generating anything. Could you please identify the several errors I am sure I'm making? Thank you.
UPDATE:
After changing my PHP main file to:
$.ajax({type : 'POST', dataType: "json", url:'config/forms/course_conf/course_generator.php', data:{co_subj_co:editedCourseId}}).done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow" data-isMultisubjectValue="'+isMultisubjectValue+'" data-subjectsNum="'+subjectsNum+'" data-id="'+courseId+'" id="'+courseId+'" data-abbrev="'+newCourseAbbrev+'" data-courseTypeId="'+newCourseTypeId+'" title="'+newCourseName+'"><div class="contentColumn40"><span class="tableContentText">'+newCourseName+' ('+newCourseTypeName+')</span></div><div class="contentColumn40">'+subjectList+'</div><div class="contentColumn10"><div class="tableIconLink"><div class="editIcon" data-id="'+courseId+'" title="Editar '+newCourseName+'"></div></div></div><div class="contentColumn10"><div class="tableIconLink"><div data-id="'+courseId+'" class="discontinueIcon" title="Discontinuar '+newCourseName+'"></div></div></div></div>';}
And my course_generator.php file to:
$courseId = intval($_POST['co_subj_co']);
$subjectList = "";
$data ="";
$select_co = mysql_query("SELECT * FROM course_conf JOIN course_type ON co_fk_ct_id=ct_id JOIN co_rel_subj ON co_subj_co='$courseId' JOIN subject_conf ON su_id=co_subj_subj WHERE co_id='$courseId'");
$result_co = mysql_fetch_array($select_co);
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
$outArr['newCourseAbbrev'] = $result_co['co_abbrev'];
$outArr['newCourseTypeId'] = $result_co['co_fk_ct_id'];
$outArr['newCourseTypeName'] = $result_co['ct_name'];
$outArr['isMultisubjectValue'] = $result_co['co_multisubject'];
$subjectsNum=mysql_num_rows(mysql_query("SELECT * FROM co_rel_subj WHERE co_subj_co = '$courseId'"));
$outArr['subjectsNum'] = $subjectsNum;
echo json_encode($outArr);
Instead of showing the HTML piece structured, this is what $newCourseStructure results:
{"newCourseId":"243","newCourseName":"a","newCourseAbbrev":"ae","newCourseTypeId":"1","newCourseTypeName":"M\u00e1ster","isMultisubjectValue":"1","subjectList":"
Edici\u00f3n y Acabado de Imagen Digital<\/div>
","subjectsNum":1}
Your JSON string is not valid JSON because you don't use quotes around the string values. Instead of manually creating JSON, create an array or object and then json_encode() it.
You don't apper to output the JSON string. Use echo or print.
Add dataType : 'json' to your ajax request so that jQuery will parse the JSON, returning the native JavaScript object. All of the variables you use in the success function are undefined. After parsing the JSON you should use
var courseId = newCourse.newCourseId; // and so on
Your ajax request doesn't have a type and so will default to GET. add type : 'POST' if you want to use POST.
Try $_GET['co_subj_co']; instead of POST.
As long as you don't specify the method to jQuery's ajax call, it's made by GET, not POST.
I have annotated two things in the code:
$.ajax({
type : 'POST',
dataType: "json",
url:'config/forms/course_conf/course_generator.php',
data:{
co_subj_co:editedCourseId
}})
.done(function(newCourse){
var courseId = newCourse.newCourseId;
var newcourseName = newCourse.newCourseName;
var isMultisubjectValue = newCourse.isMultisubjectValue;
var subjectsNum = newCourse.subjectsNum;
var newCourseAbbrev = newCourse.newCourseAbbrev;
var newCourseTypeId = newCourse.newCourseTypeId;
var newCourseTypeName = newCourse.newCourseTypeName;
var newCourseStructure = '<div class="tableRow dynamicRow noHeight injectedRow"'
+ ' data-isMultisubjectValue="' + isMultisubjectValue + '"'
+ ' data-subjectsNum="' + subjectsNum + '"'
+ ' data-id="' + courseId + '"'
+ ' id="' + courseId + '"'
+ ' data-abbrev="' + newCourseAbbrev + '"'
+ ' data-courseTypeId="' + newCourseTypeId + '"'
+ ' title="' + newCourseName + '">'
+ '<div class="contentColumn40"><span class="tableContentText">'
+ newCourseName + ' (' + newCourseTypeName + ')</span></div>'
// WHERE IS subjectList DEFINED?
+ '<div class="contentColumn40">' + subjectList
+ '</div>'
+ '<div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div class="editIcon" data-id="' + courseId + '"'
+ ' title="Editar ' + newCourseName + '"></div>'
+ '</a></div></div><div class="contentColumn10"><div class="tableIconLink">'
+ '<a href="#"><div data-id="'+courseId+'" class="discontinueIcon" '
+ 'title="Discontinuar '+newCourseName+'"></div></a></div></div></div>';
/*
* your HTML is generated, but you never put it in the DOM
*/
$('#idOutputWrapper').empty().html(newCourseStructure);
}
When you use subjectList from the json response, please notice that it comes with a closing </div> tag for some reason, maybe you should change that, too.
btw: Your code formatting is horrible, sorry to say so. You can compress your js before uploading it to the server, but while working on it, it NEEDS to be readable. I just edited it to fit better in the codeblock here.
Are you actually using POST, or are you firing off a GET request (your browser's developer tools should tell you this easily). You should also make sure that $courseId is an integer by $courseId = intval($_POST['co_cubj_co']);. In addition, you should add a condition for the event that the requested ID is not found.
As MueR suggests, the reason to make sure that courseID is an integer is to prevent SQL injection (unless you want people to do things like delete your entire DB at will). This, of course, assumes that courseID is something like an autoincrement int.
However, you've got a number of other problems. Your JSON is invalid since you're ostensibly writing out unquoted strings... you should just use json_encode:
$outArr = array();
$outArr['newCourseId'] = $result_co['co_id'];
$outArr['newCourseName'] = $result_co['co_name'];
...
echo json_encode($outArr);
Personally, I prefer to just use $_REQUEST, which concatenates both $_POST and $_GET. Makes it easier.

How to send variable from javascript to PHP on azure websites?

To simplify the problem, all I want is passing 3 variable from javascript to PHP. So let say I have 4 varible : a,b,c,message.
I have tried the following ways:
1)The code below is in my javascript file
window.location.href="somewebsite.php?x=" + a + "&y=" + b + "&z=" + c + "&msg=" + message;
I saw that it actually passing the values to URL, it jump to the PHP website that specifies in the code above but somehow nothing is getting from $_POST['x'] ( I even try $_GET['x'] and $_REQUEST('x') but none of them works at all)
2) Then I tried with ajax
$.post("somewebsite.php",{x:a, y:b, z:c, msg:message})
And same as above nothing are passed to the PHP website.
3) I tried with form submit
I put everything into a form and submit it to the PHP website but what I get from $_POST is an empty array.
So I conclude that something is wrong with azurewebsites server. This is the first time I used window azure so I don't know how it even works. Any suggestion would be appreciated.
you can try out ajax function
$.ajax({
url:"url",
method:"post",
data:{x:a, y:b, z:c, msg:message},
success:function(data)
{
// success code
},
error:function(error)
{
// error code ;
}
});
Should work:
Your js file:
$(document).ready(function(){
var aval = "testas";
var bval = "testas2";
var cval = "testas3";
var msg = "testas4";
$.post('test.php',{a:aval,b:bval,c:cval,message:msg},function(resp){
alert(resp);
});
});
php file should look like:
<?php
$resp = "";
foreach($_POST as $key => $val){
$resp .= $key.":".$val." \n";
}
echo $resp;
?>
After post alert should give response of all sent post values.
I hope it helped you. If yes, don't forget resp. Thanks.
Try sending an array to your somewebsite.php write this inside a function on jquery code.
It must work if you place it on a good place on your code.
var x=new Array();
x[0]='field0';
x[1]='field1';
x[2]='fieldN';
$.post('somewebsite.php',x,function(x){
alert(x);
});
Your somewebsite.php could be like this.
<?php
if(!isset($_POST['x']))$x=array();else $x=#$_POST['x'];
for($i=0;$i<count($x);$i++)
echo "X ($i) = ".$x[$i];
?>
Happy codings!

Passing variables to ajax with onclick

I have a problem with the variables, that I want to pass through ajax to php.
In an php file, I generate some divs with id and name attributes.
livesrc.php
echo "<div class=\"search-results\" id=\"" . $softwareArray['Sw_idn'] . "\"
name=\"" . $softwareArray['SoftwareName'] . "\"
onclick=\"addBasket(this.id, this.name)\" >
" . utf8_encode($softwareArray['SoftwareName']) . "</div>";
The relevent part is this:
onclick="addBasket(this.id, this.name)
Sorry for the escapes, in html the div looks like:
<div class="search-results" id="235"
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this.id, this.name)">...</div>
This looks okay, but in the js "addBasket", the variable sw_name is not set. (undefinded)
The JS in the head section:
<script type="text/javascript">
function addBasket(sw_id, sw_name)
{
alert(sw_name);
$.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data)
{
$("#basket").html(data);
});
}
</script>
The sw_id is set, but the sw_name is not working. Is the call in html with "this.name" correct?
it's because this.name did not exists if you want to access the attribute you have to call this.getAttribute('name') id are particular and can be access directly.
Personally I will give juste this to the function and extract id and name in the function
onclick="addBasket(this)";
<script type="text/javascript">
function addBasket(el)
{
var
sw_id = el.id,
sw_name = $(el).attr('name');
alert(sw_name);
$.post("assets/basket.php",{sw_id: sw_id, sw_name: sw_name}, function(data)
{
$("#basket").html(data);
});
}
</script>
You could pass the whole element into your js:
<div class="search-results" id="235"
name="Adobe Acrobat Writer 9.0 Professional"
onclick="addBasket(this)">...</div>
Then grab what you want in your function
function addBasket(sw) {
alert( sw.id + ' ' + sw.getAttribute( 'name' ) );
}

Categories

Resources