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.
Related
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);?>");
This is my script:
<script>
$(document).ready(function(){
$("#ID_Blangko").on("change", function() {
var blangko = $("#ID_Blangko").val();
var baseUrl = '<?php echo base_url(); ?>program/administrasi/blangko_rusak/ajax_jumlah';
$.ajax({
url: baseUrl,
data: {nama : blangko},
dataType: "json",
success: function(datas){
$("#Jumlah_Blangko").val(datas);
},
error: function (xhr, ajaxOptions, thrownError) {
$('#Jumlah_Blangko').val("some error.");
}
});
});
});
</script>
and this is my controller code:
public function ajax_jumlah($nama)
{
$this->db->select('Jumlah_Blangko');
$this->db->where('Nama_Blangko', $nama);
$result = $this->db->get('tb_blangko');
$amount = $result->row()->Jumlah_Blangko;
return json_encode($amount, JSON_NUMERIC_CHECK);
}
i've double checked the onchange function and controller function is working well and returning value. The problem is I cant pass this value to my ajax code and print it on input form. Here's my html:
<?php echo form_open($form_action, array('id'=>'myform', 'class'=>'myform', 'role'=>'form')) ?>
<div class="row">
<div class="col-md-6">
<?php
$atribut_blangko = 'class="form-control" id="ID_Blangko"';
$selectedBlangko = $values->ID_Blangko;
echo form_dropdown('ID_Blangko', $dropdown_Blangko, $selectedBlangko, $atribut_blangko);
?>
</div>
<div class="col-md-6">
<?php echo form_input('Jumlah_Blangko', '', 'id="Jumlah_Blangko" class="form-control" placeholder="Jumlah" maxlength="50" readonly="true"') ?>
</div>
</div>
<?php echo form_close() ?>
update #2 and this solve my problem
this the controller function im accessing directly from browser URL that is http://localhost/amc/program/administrasi/blangko_rusak/ajax_jumlah/Malaysia
and i found out that
return json_encode($amount, JSON_NUMERIC_CHECK); this doesnt work and then i changed to:
echo json_encode($amount, JSON_NUMERIC_CHECK); this work.
I dont know how this is possible, anyone can explain?
Please check the line no 3 in your code it should be "$("#ID_Blangko").val()" instead of "$("#ID_Blangko").val"
Explanation:
in the above code line you were expecting to get the value of the element having id "ID_Blangko" and you are using the jQuery, but the main thing here is that the "val" is a function and not a variable so you can not access the value by just saying "$("#ID_Blangko").val" because it looks for a property named as 'val'
I think
var blangko = ID_Blangko.value;
should be
var blangko = $('#ID_Blangko').val();
or
var blangko = $(this).val();
EDIT
Your problem with controller/action not seeing the variable could be because it expects params instead of query string vars like most frameworks do. Something like this could help you with that
var baseUrl = '<?php echo base_url(); ?>program/administrasi/blangko_rusak/ajax_jumlah/' + blangko;
I must to check the result of Ajax are same with some PHP variable value.
Is there anyway to do this?
Thank you in advance for help.
My Ajax HTML:
<?php
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
if($x == $y){
echo $x;
}
?>
<a id="input" href="#">Get value<input type="hidden" value="2_2_1_3"></a>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
jQuery(document).ready(function(){
$("#input").on("click", function(){
$.ajax({
type: 'POST',
url: "ip2.php",
data:'ip=' + $(this).parent().find('input').val(),
success: function(data){
$("#ip").html(data);
}
});
});
});
</script>
The PHP script:
<?php
if($_POST['ip'] >= 0){
$ip = $_POST['ip'];
echo $ip;
}
?>
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
if($x == $y){ // this will never be true because $x is diferent of $y
echo $x; //so you will never print this out
}
And you won't have the element with id="ip" to print the result from your ajax
success: function(data){
$("#ip").html(data);
}
For it to work try this:
<?php
$x = '<p id="ip"></p>';
$y = '2_2_1_3';
echo $x;
?>
I'm not entirely sure what you want to do, but you can always send your post data as an object in javascript, for simplicity you can use the post function.
Example:
$.post( "ip2.php", { ip: $(this).parent().find('input').val() }, function( data ) {
console.log( data );
});
More info:
https://api.jquery.com/jquery.post/
https://api.jquery.com/jQuery.ajax/
i'm creating a plugin for WooCommerce
in my plugin php file when i call a php file with jquery ajax i get empty result
this is my ajax code:
jQuery(function() {
jQuery.ajax({
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
success: function(output) {
alert(output);
}
});
});
and this is my php file:
<?php
$output = 'test';
return $output;
?>
You should change this:
<?php
$output = 'test';
return $output;
?>
To this:
<?php
$output = 'test';
die($output); // or echo or print
?>
Returning a variable will not return it as a response to an ajax call.
try this
<?php
$output = 'test';
echo $output;
?>
You can try this:
create a empty variable and insert your data to this.
var response = '';
$.ajax({ type: "GET",
url: '<?php echo RAKHSH_WC_QUICK_VIEW_URL ?>/rakhsh-data-for-pop.php',
async: false,
success : function(text)
{
response = text;
}
return response;
});
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>