jQuery php variable echo not working - javascript

I have a little contact form, where I would like to ask the user to calculate and enter the correct value in order to prevent spam. Now, when the send button is clicked, I fire a php script, where I change the calculation values. I would like to echo these values and show them as the new placeholder in case of both, success, as well as failure.
$("#send_button").click(function() {
var url = "contact.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#contact_form").serialize(), // serializes the form's elements.
success: function(data)
{
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>";
$("#form_info_label").css('color','#0ed68d');
$("#form_info_label").text(data);
$("#user_answer").attr("placeholder",txt);
},
error: function(data) {
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>";
alert(txt);
$("#form_info_label").css('color','#f2275e');
$("#form_info_label").text("Error. Please try again.");
$("#user_answer").removeAttr('value');
$("#user_answer").attr("placeholder",txt);
}
});
return false; // avoid to execute the actual submit of the form.
});
However my placeholder ends up not interpreting it as php code, but just simply copies the text. So my placeholder then ends up displaying:
<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier';?>

I ended up returning a json-encoded array with my desired values from php back to javascript and parsed the response there.

You'll need PHP tags
var txt = "<?php echo 'Spam protection: Calculate ($first_num + $second_num) x $multiplier'; ?>";
You actually have it right in the error handler, so you probably just forgot, and now you've edited the question to include them ?
If you have PHP tags, and it's still not being parsed, the file the javascript is in is not being parsed by PHP.

Remember on comuputers to use the * for multiply things, not the x.
And it´s also not clear, what your function "Calculate($param)" does, but usally you don´t need a function for adding one variable to another. But the brackets still needed...

In my case the PHP tag was not interpreted by js either. A solution I found was:
In my php file I defined the variable in a non-visible div:
?>
<div id="first_num" style="display: none">
<?php echo $first_num; ?>
</div>
<?php
In the jquery file I read the div value like this:
var first_num= $("#first_num").text().trim();

First of all what adeneo already said: .js files are not parsed by PHP.
Secondly PHP variables will not be expanded when they occur in single quoted strings. http://www.php.net/manual/en/language.types.string.php#language.types.string.syntax.single
You should use either double quotes or
echo 'Spam protection: Calculate ('.$first_num.' + '.$second_num.') x '.$multiplier;

Related

Store JavaScript variable in a php variable without page refresh

I've been been through numerous articles on here and tried dozens of variations including ajax. What I want to do is click a button and store the id of that button in a php variable without having to refresh the page.
I've tried using isset and POST and I get some variation of Undefined key array.
Ajax was suggested but when I use ajax I can get the variable stored, but I'm unable to get it into a php variable.
Current setup...
I have an HTML button from which I need the id stored in a php variable so I can use it in another SQL statement. This button is part of an HTML table of MySQL records returned from the db.
<input type='button' value='Edit' name='editbtn' onclick='edit(this.id)' id = '" . $row['id'] . "'/>
JavaScript...
function edit(clicked_id){
var selid = clicked_id;
var seleid = selid.toString();
$.ajax({
type: 'post',
data: {name: seleid},
datatype: 'text',
success: function(data){
console.log(name);
alert("Success, data is: " + data); // This correctly returns the id of the button clicked
},
});
}
The PHP at the top of the page is...
if(isset($_POST['name']) && !empty($_POST['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}
PHP is not receiving anything. Is there a way to do this? I guess it's a backend/frontend issue?
Note: I have been able to store a JavaScript variable in an HTML tag but I've been unable to use it as part of a SQL statement, even after trimming the tags off of it.
Please help and thank you!
Try something like this in your php code :
$data = json_decode(file_get_contents('php://input'), true);
if(isset($data['name']) && !empty($data['name'])){
ob_clean();
$varid = $_POST['name'];
echo $varid;
exit;
}

Passing PHP integer to JavaScript

I have been reading so many posts and none of them seem to work for me I have no idea what I am doing wrong. I want to call a PHP integer in JavaScript and set it to a JavaScript variable so I am then able to use that variable in my calculations.
average = '<?php echo $average; ?>';
console.log("value" + " " + average);
This is the code I have been using and it prints to the console:
value <?php echo $average; ?>
This is clearly not the resulted I wanted, I wanted it to print the integer.
My $average PHP integer is also located in a different file so I used:
<?php include 'DBObject.php';?>
I want to be able to do a calculation like:
drone1percentage = 1000 / average * 100;
but since the average variable isn't taking the php integer $average from my other file it doesn't work.
You could add this to your .htaccess, so PHP will interpret js files too.
<FilesMatch "\.(js)$">
AddHandler application/x-httpd-php .js
</FilesMatch>
Or rename that .js to .php and add this header in front of the file:
header('Content-Type: application/javascript');
You "cannot" execute php inside a javascript file.
However there are some tricks to get to your variables from php.
One of them is creating a javascript variable with php and use this variable inside your javascript file.
Example:
// Inside your php file
<script>
var average = <?php echo $average; ?>
</script>
<script src="yourjavascriptfile.js"></script>
// Inside your javascript file
console.log(average);
use jQuery.ajax - http://api.jquery.com/jquery.ajax/
var average;
$(function(){
$.get("path/to/script", function(data, status){
average = data;
});
});
For me the most reliable way to get information from PHP into javaScript is using jQuerys ajax functionality.
So if you have something like
yourPHPFile.php
<?php
if($_POST['action'] == 'getAverage') {
echo returnAverage();
die;
}
function returnAverage() {
//your average calculation here
return $average
}
You could do something like
yourJavaScriptFile.js
var average = null;
$.ajax({
method: 'POST',
url: '/path/to/yourPHPFile.php',
data: {action: 'getAverage'},
success: function(response) {
average = response;
}
});
Just put this inside a function that is triggered whenever you need it.
For this to work you need to have jQuery included. For further information about the jQuery.ajax() functionality see The Documentation.
Please also note that some ajax parameters might differ depending on the version of jQuery you use.
Your js file has to end in .php for example example.js.php in order for the php code to be parsed.
While you cannot put php code into a .js file, you can create a js file from php
You could also setup the web server to parse all .js files as php code, but that would be a bit too much perhaps.
Try this:
average = parseInt('<?php echo $average; ?>');

Jquery takes last output as value

I have some code and it is for sending comments to database.
And I have jquery and ajax code:
<script type="text/javascript">
$(document).ready(function() {
$('#comm1').keypress(function(event) {
var key = (event.keyCode ? event.keyCode : event.which);
if (key == 13) {
var comment = $('#comm1').val();
var fromstatid = '<?php echo $status->fromid; ?>';
var status = '<?php echo $status->id;?>';
var fromid = '<?php echo $frid; ?>';
$.ajax({
method: "POST",
url: "d/includes/counts.php",
data: {u: fromid, status: status, comment: comment, fus: fromstatid},
success: function(status) {
$('#comm1').val('');
}
});
};
});
});
</script>
#comm1 is textarea for comment ..
For php I have like basic output from database and the problem is that my jquery use only last output from database as value. In other words where ever I type a comment it send to database for the last output. It works if I have button for Reply and then it sends me to new page or something where I can limit output from database to 1 or to only that where I want to comment. But can I do it here on the page where are all comments... Also I was trying to set id as some word + php id from database for that output but it seem like when I add this to jquery code noting going to work....
The code I tried is : $("#something<?php echo $status->id; ?>").keypress.....
It stops the script it looks like the whole script is not working...
I asked similar question but no one answered me the right question... Also I was thinking of can I like make foreach in jquery here on this code.. And say for each output do something. I really don't know why it use only last output on page as value but it will help a lot if someone have some explanation?
EDITED:
Or do I need to echo for each output the jquery code?
UPDATE:
Tried by echoing the whole jquery code and it is not working....
NEW:
As you asked I have d/includes/counts.php file and the index.php
Inside counts.php i just input in database values send via ajax...
Inside index.php I said I have basic foreach database output to echo something like $status->text and for comment to echo textarea where I can type comment for text... Code is too long and I dont have problems with that code I have problems with connecting jquery code to all outputs not only last one....
Why does my var status = '<?php echo $status->id; ?>'; AND var fromstatid = '<?php echo $status->fromid; ?>'; use only last output values? Can I make some var inside echo for each output and use that var here in code to navigate which one is commented on?
I founded that also the script work only on one output like if I try to comment on the other one and press ENTER it wont work....
You must know that only the last output of the PHP file will be retrieved. So I'm wondering what did you output in the PHP file ? Can you post the PHP code please ? (Sorry, for answering here but not enough points to comment).

Ajax Jquery and php: How to control feedback?

Let's suppose you're sending data through ajax. The server will process it (PHP) and sends a feedback that you can grab using Complete: function(data) { //WRITE HTML TO DIV $('#somehing').html(data) }
The question is:
is there a way to modify data (edit, delete) before passing it to an html element?
Here's a simple example of what I mean :
//php side
echo 'Invalid email';
echo 'Enter your username';
echo 'fine';
echo 1;
echo 2;
// Jquery and Ajax
$.ajax({
type: 'POST',
url: 'render.php',
data:values,
complete: function(data) {
$('#something').html(data) /* all those messages in php will be printed
into #something including the numbers. how to delete or edit those numbers
from appearing in #something? */
}
});
Try this to remove the numbers like,
complete:function(data){
data=data.replace(/\d+/,''); // Regular expression without quotation marks.
// or you can replace the something text like
// $('#something').text(function(){
// return this.innerText.replace(/\d+/,'');
// });
alert(data);
}
Data is returned as basically just a string the way you say you are doing it "receive it as 'html'" You should be able to use simple javascript to control it right out of the gate, for example the way I do things sometimes is this:
the PHP returns something like:
echo $variable_1 . ":" . $variable_2
Then when I get that as data it is just a string that says
variable 1:variable 2
So what I do next is I separate the variables by the colon
var var1 = data.split(":")[0];
var var2 = data.split(":")[1];
Now, this is just a simple example. I'm not exactly sure what you're returning, but it seems that you're searching for an index of 1 instead of "1". This could make a difference. Try searching for 1 in quotes, this would then be searching through a string.

Send variable that contains an equation through ajax and return it to jquery fully computed

im trying to write a code where i will be able to send a variable that contains a mathematical equation through ajax and have it computed using php
the problem that i am getting is that once the php it returns the variable to jquery it doesnt compute it and still returns it as an equation
this is how i made it
jquery
$(".equals").click(function(e){
e.preventDefault();
var firstnum= $("#firstnum").val();
var secnum= $("#secnum").val();
var operator= $('#operator').val();
var compute = firstnum+operator+secnum;
content = {compute:compute}
$.ajax({
url:'compute.php',
type:'POST',
data:content,
success:function(response){
console.log(response);
}
});
});
php
<?php
$compute =$_POST['compute'];
echo $compute;
?>
for example the content of my variable compute is...
10+10
the php will still return it as is
what i want to happen is once it comes back from php it will return as
20
is there a way to make this happen?
thanks
If you want PHP to compute it, you should write something like this. Because when you send 10+10, PHP sees it as a string.
Javascript:
$(".equals").click(function(e){
e.preventDefault();
var firstnum= $("#firstnum").val();
var secnum= $("#secnum").val();
var operator= $('#operator').val();
content = {first_number:firstnum,second_number:secnum,operator:operator}
$.ajax({
url:'compute.php',
type:'POST',
data:content,
success:function(response){
console.log(response);
}
});
});
And at the PHP:
<?php
$content = $_POST['content'];
if( '+' == $content['operator'] ){
echo $content['first_number'] + $content['second_number'];
}
else if( '-' == $content['operator']){
//extraction
}
// so on..
?>
You must have a calculator script on server side in PHP.
The mathematical expression must be parsed. You could use something like this
http://20xxproductions.com/code-samples?s=phpsc
for parsing more complex expressions.
If you have to process simpler ones you can specifiy an operator and give both numbers as extra POST variables.

Categories