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

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);
});

Related

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);?>");

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.

How to alert PHP value in JavaScript?

<script type="text/javascript">
var jvalue = 'this is javascript value';
<?php
$abc = "<script>document.write(jvalue)</script>" ?>
</script>
<?php echo 'php_'.$abc; ?>
<script type="text/javascript">
var test = "<?php echo $abc; ?>";
</script>
<?php
echo '<script language="javascript">';
echo 'alert(test)';
echo '</script>';
?>
How to alert test variable, which contains PHP value?
I would like to get the PHP value in javascript, for further execution in my project.
try this code
<?php
echo '<script language="javascript">alert("'.$test.'"); </script>';
?>
this is updated code for you using javascript and PHP
<?php
$user = "rebel";
echo '<script> var name = "'.$user.'";
alert(name);</script>';
?>
This is the third code for you if this does not work then you have other problem
<?php
$abc= "Hello";
?>
<script type="text/javascript">
var test="<?php echo $abc; ?>";
</script>
<?php
echo '<script language="javascript">';
echo 'alert(test)';
echo '</script>';
?>
why are you assigning the variable to a javascript variable and then echoing that? sounds like extra work to me...
echo 'alert("' . $abc . '");';
Your code is not so clear, i think you want something like this:
<?php
$test = "hi there!";
echo '<script type="text/javascript">';
echo 'alert("'.$test.'")';
echo '</script>';
?>
var test="<?php echo $abc; ?>"
<script language="javascript">alert(test); </script>
If you want to alert the value of $abc, you need to escape the slash in the following line with a backslash, like this.
<?php $abc = "<script>document.write(jvalue)<\/script>" ?>
You also need to remove this line (or escape the < and the > in $abc). If you don't, the script tags will mess up the rendered html code.
<?php echo 'php_'.$abc; ?>

how to convert the jquery element text() into string

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>

How to get the returned php page in json format?

I’m trying to get the contents of the returned php page, as follows:
(<?php echo json_encode(array("color"=>"Red")); ?>)
My JavaScript:
<script>
;
$.get("page.php",
function(data){
$('body').append("Color: " + data.color)
}, "json");
;
</script>
My page.php:
<?php echo json_encode(array("color"=>"Red")); ?>
How to make it work?
Try this
<?php
header('Content-type: application/json');
echo json_encode(array("color"=>"Red"));
die;

Categories