how to convert the jquery element text() into string - javascript

I can not successfully get the string using the jquery text()
I have my HTML
<span>/</span>
<span onclick="
var inner_text=$.trim($(this).text());
if(inner_text=='Send Request'){
var post_id=<?php echo $blog_id ;?>;
var event_date='<?php echo $blog_feeds['valid_date'] ?>';
var post_text='<?php echo addslashes($blog_feeds['post_text']) ?>'; //if the string contains ' , then would have error
var request_text_id='<?php echo $blog_id.'comment_text';?>';
var request_content=$('#'+request_text_id).val();
var who_post='<?php echo $blog_feeds['username'] ;?>';
$.ajax({
url:'php/join_request.php',
method:'post',
data:{request_content:request_content,post_id:post_id,who_post:who_post,event_date:event_date,post_text:post_text},
success:function(data){
if(data=='ok'){
$('<?php echo '#'.$blog_id.'request_w' ?>').html('You have sent '+who_post+' a joining reuqest on this event');
$('<?php echo '#'.$blog_id.'request_button'; ?>').html('Request Sent');
$('<?php echo '#'.$blog_id.'request_button'; ?>').css('opacity','0.7');
$('<?php echo '#'.$blog_id.'request_button'; ?>').css('cursor','initial');
$('<?php echo '#'.$blog_id.'comment_text';?>').val('');
}
}
})
}
" id="<?php echo $blog_id.'request_button'; ?>" class="j_request_button">
<?php
$select_request=mysql_query("SELECT `id` FROM `join_request` WHERE `post_id`='$blog_id' AND `who_request`='$username'");
if(mysql_num_rows($select_request)>=1){
echo '<span style="opacity:0.7;cursor:initial">Request Sent</span>';
}
else{
echo '<span style="cursor:pointer">Send Request</span>';
}
?>
</span>
if I add a alert(inner_text) right before if statement, I can successfully alert "sent request",but I can not alert ok within the if statement

Try:
var inner_text=$.trim($(this).text());
This will remove any surrounding whitespace, which is likely if you have line breaks between your spans.

Don't put a full script like that in your HTML. Give your span an id, and use jQuery in a separate script tag:
<span id="sent_request">sent request</span>
<script>
$('#sent_request').click(function(){
var inner_text=$(this).text();
if(inner_text=='sent request'){
alert('ok'); //not working
}
});
</script>

Related

How can I swap the text inside html button, using a js function with id parameter?

I want to swap the text inside a html button, but using a function with 3 parameters, id, first_text, second_text.
I was looking on another questions with the same problem, but it won't help me.
This is not working:
Button(var1,value,id are variables from php):
<input type='button' id=".$id." onclick='swaptxt('"$.id."', '".$var1."','".$value."')' value=".$value.">
Function:
function swaptxt(index, text1, text2){
var elem = document.getElementById(index);
if (elem.value===text1)
elem.value = text2;
else
elem.value = text1;
You are not getting the correct output because you are passing the wrong id in argument. In input, you have given id as ".$id." but in the argument, you are passing the id as "$.id.". Provide the correct id and you will get your expected output.
function swaptxt(index, text1, text2){
var elem = document.getElementById(index);
if (elem.value===text1)
elem.value = text2;
else
elem.value = text1;
}
<input type='button' id=".$id." onclick='swaptxt(".$id.",".$value.", ".$var1.")' value=".$value">
Don't echo it from PHP, just drop out of PHP and only use PHP to add the variables.
?> <!-- we are no longer in PHP -->
<input type='button' id='<?php echo $id; ?>'
onclick='swaptxt('<?php echo $id; ?>',
'<?php echo $var1; ?>',
'<?php echo $value; ?>')'
value='<?php echo $value; ?>'>
<?php // back to PHP now
another way to concat it:
onclick="swaptxt(\'' . $id . '\',\'' . $var1 . '\',\'' . $value .'\');"

using php string with line breaks as javascript variable

I was working on project in which I have to get some text from the database and display it in the text area. Working fine with no line breaks and tabs. but when a line breaks occurs it gives the error
Uncaught SyntaxError: Invalid or unexpected token
My java script code is as :
<script type="application/javascript">
$(document).ready(function () {
document.getElementById('job_type').value = "<?php echo set_value('job_type') ?>";
document.getElementById('job_cat').value = "<?php echo set_value('job_cat') ?>";
if("<?php if(validation_errors() == false) echo "false"; else echo "true"; ?>"=="false")
{
$('#job_title').val("<?php echo $job[0]->job_title ?>");
$('#job_type').val("<?php echo $job[0]->job_type ?>");
$('#job_cat').val("<?php echo $job[0]->job_cat ?>");
$('#salary').val("<?php echo $job[0]->salery ?>");
$('#job_descp').text("<?php echo $job[0]->job_desc ?>");//error here
}
});
});
</script>
The text it was trying to set was
Error details are shown in images
Debug info
I have tried using .html() and .val() too but nothing worked. How can I handle it.
This has already been answered here https://stackoverflow.com/a/4270709/3004335
However, you can use json_encode
<script type="application/javascript">
$(document).ready(function () {
document.getElementById('job_type').value = "<?php echo set_value('job_type') ?>";
document.getElementById('job_cat').value = "<?php echo set_value('job_cat') ?>";
if("<?php if(validation_errors() == false) echo "false"; else echo "true"; ?>"=="false")
{
$('#job_title').val(<?php echo json_encode($job[0]->job_title); ?>);
$('#job_type').val(<?php echo json_encode($job[0]->job_type); ?>);
$('#job_cat').val(<?php echo json_encode($job[0]->job_cat); ?>);
$('#salary').val(<?php echo json_encode($job[0]->salery); ?>);
$('#job_descp').text(<?php echo json_encode($job[0]->job_desc); ?>);//error here
}
});
});
</script>
You do however need to be careful about cross site scripting
See here https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet in particular rule #0
Remove line break(CR LF) in job[0]->job_desc
like this:
$('#job_descp').text("<?php echo str_replace (array("\r\n", "\n", "\r"), '<br>', $job[0]->job_desc);?>");

syntaxerror unterminated string literal jquery

I get this weird error. It happens to be my PHP code that is embedded into jquery.
<?php $user=isset($_GET['u']) ? $_GET['u'] : NULL; //This returns a numeric value ?>
<script>
$("button[name='send_mail']").on('click',function(){
var user = '<?php echo $user;?>'; // <----The Problem
$.ajax({
type:"POST",
url:"ajax/scripts/user_mail.php?u="+user,
success: function(data){
alert(data);
},
});
});
</script>
I tried both, single and double quotes. This piece code happens to work in some of my files and doesn't work in others.
<?php
$user = (!empty($_GET['u']))?intval($_GET['u']):0;
?>
<script language="JavaScript">
console.log("User: " + <?php echo $user; ?>);
// try to debug what is really in the variable
var user = <?php echo $user; ?>;
// same as <?= $user; ?>
</script>
You have a rogue comma in this part of your code:
success: function(data){
alert(data);
}, //<--- here
});
It should be only:
success: function(data){
alert(data);
}
});
This works:
<?php $user=isset($_GET['u']) ? $_GET['u'] : NULL;?>
<span id="user_id_span" style="display:none;"><?php echo $user; ?></span>
<script>
var user = $('#user_id_span').text();
</script>
If your output is more than just a single string or number or single line, this would not work.

How to append add php conditions while replacing html text in jquery

basically , when document is ready , I would like to replace the td content with this html content that has some php conditions in it as shown below , but it's not working
<?php
echo "<script type='text/javascript'>";
echo "$(document).ready(function(){";
?>
$('#redeem_freebie).html('<a class="btn" <? if (!$freebies->expired) {?>onclick="applyFreebieNow('<?=addslashes($dialog_copy)?>','<?=addslashes($freebies->get_started_link)?>','<?=$freebies->promo_code_id?>');"<? } ?> style="<?=$freebies->expired ? 'cursor: default;':''?>">Redeem Freebie >></a>');
<?php
echo "});";
echo "</script>";
echo "}";
?>
<script type='text/javascript'>
$(document).ready(function(){
$('#redeem_freebie').html('<a class="btn" <?php if (!$freebies->expired) {?>onclick="applyFreebieNow('<?php echo addslashes($dialog_copy); ?>','<?php echo addslashes($freebies->get_started_link)?>','<?php echo $freebies->promo_code_id?>');"<?php } ?> style="<?php echo $freebies->expired ? 'cursor: default;':''?>">Redeem Freebie >></a>');
});
</script>
Some hint : dont use <?= really not clear and your error was here <? } ?> <- php short tag
If you want to use some php function when document is ready, you can call an other php page using ajax.
example in jQuery :
$.ajax({
url: 'yourpagewithfunction.php',
type: "POST",
data : {variable : value}
}).done(function(msg) {
alert(msg);
});

AJAX- getting a specific array value in post

Im making a like system and am encorporating ajax to make it smooth. Everything works okay except it always defaults to the last post in for loop. My thinking is there is no way for the javascript to know which element of id "like" to post to.
main.js:
$(".like>a").click(function() {
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
Im passing through the post variable from the view file. I grab the postID of each post.
userprofile_view.php:
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
model_posts.php:
function likePost($post) {
$data['user_ID'] = $this->session->userdata('id');
$data['post_liked'] = $post;
$insert = $this->db->insert('user_post_likes', $data);
return $insert;
}
userprofile.php(controller):
public function like_post() {
$this->load->model('model_posts');
$post = $this->input->post('post');
$this->model_posts->likePost($post);
}
If someone couldhelp me out that would be great!
The problem is your usage of a global variable in a loop, so the variable will have only the last value of the loop.
You can use a data-* attribute like
<script type="text/javascript">
var base_url = "<?php echo base_url(); ?>";
</script>
<?php foreach ($posts as $post)
{ ?>
<?php $postID = $this->model_posts->getPostData('id', $post->post); ?>
<div class='posts'>
<div class='posts_img'>
<img src="<?php echo base_url() . 'img/profilepictures/thumbs/' . $profilepicture?>">
</div>
<div class='posts_user'>
<strong><?php echo $prefname; ?></strong>
</div>
<div class='posts_date'>
<?php echo $this->model_posts->getPostTime($post->post); ?>
</div>
<div class='post'>
<p><?php echo $post->post ?></p>
</div>
<?php if($this->model_posts->doesUserLike($me, $postID)) { ?>
<div class='unlike'>
<?php echo anchor('userprofile/unlike_post/' . $me . '/' . $postID, 'unlike'); ?>
</div>
<?php } else { ?>
<div class='like' data-post="<?php echo $postID; ?>">
<?php echo anchor('#', 'like', array('id' => 'like')); ?>
</div>
<?php } ?>
then
$(".like>a").click(function () {
var post = $(this).parent().attr('data-post');
$.post(base_url + "index.php/userprofile/like_post/", {
post: post
}, function (data) {
alert('liked');
}, "json");
return false;
});
if you're sending same ID field with different values stop, send unique IDs with selected values OR send ID with values as post array, PHP can deal with it
<script type="text/javascript">
var post = "<?php echo $postID; ?>";
var base_url = "<?php echo base_url(); ?>";
</script>
This is your problem. You're declaring these variables in global scope. So every time your PHP foreach loop iterates, you're redefining the variable in global scope, overwriting the previous value.
Instead, set an id attribute on each <a> tag to be the $postID, and get that ID in your click handler, like so:
$(".like>a").click(function() {
var post = this.id;
$.post(base_url + "index.php/userprofile/like_post/", { post : post }, function(data) {
alert('liked');
}, "json");
return false;
});
You would have to modify the code that creates the <a> tags to include the id attribute with the $postID value assigned to it...I don't see that part included in your code samples.

Categories