Using PHP variables as parameters for JavaScript function - javascript

I'm having a bit of trouble working with the quotations for this. So, let's make an example of sending two strings we want concatenated through variables, and then running them through a JavaScript function to concatenate them (I understand that this is very basic in PHP and I know how to do it, I'm just using this example for the sake of simplicity).
JavaScript Code:
function con(first, last) {
answer = first+last;
alert(answer);
return;
}
HTML and PHP:
<?php
$first = "Butter";
$last = "Last";
echo '<input type="button" value="Get Answer" onclick="con(".$first.", ".$last.")" />';
?>
This code above does not work, how can I make it work?
Thanks all

If you have a look at the html that that's generating it will be something like this:
<input type="button" value="Get Answer" onclick="con(".$first.", ".$last.")" />
Which as you can see is not correct.
There are a couple of issues with your code, first of all, variables names, like $first won't get evaluated to their value if they are inside single quotes.
Try:
echo '<input type="button" value="Get Answer" onclick="con("'.$first.'", "'.$last.'")" />';
This will output :
<input type="button" value="Get Answer" onclick="con("Butter", "Last")" />
which is still not correct, as you're not passing the arguments to your javascript function correctly.
Try:
echo '<input type="button" value="Get Answer" onclick="con(\''.$first.'\', \''.$last.'\')" />';
which should output
<input type="button" value="Get Answer" onclick="con('Butter', 'Last')" />
that hopefully works :)

Here is your solution
JavaScript Code:
function con(first, last) {
answer= first+last;
alert(answer);
return;}
PHP and HTML code:
<?php
$first = "Butter";
$last = "Last";
echo '<input type="button" value="Get Answer" onclick=con("'.$first.'","'.$last.'") />';?>
when you pass the value to the javascript function through php you must pass the value in 'single quote' or "double quote" like onclick=con("'.$first.'","'.$last.'");

Related

I want to use onclick function to get data from HTML Form inside php loop to use it in Ajax

I'm developing discussion board and I want to make a reply system on each comment using jquery.
I created certain div inside a loop with different values in each iteration.
Now I'm working on submitting the reply form and I have a problem. It works only on the first comment. When I reply to the first comment only It works but when replying to any other comment It doesn't work and give me my error message the textbox is empty Then I realized that it reads data from the first form only through the loop.
Here is the code.
<div class="comment_form">
<textarea class="span10" id="replyC" name="replyC" placeholder="Reply comment" rows="6">
</textarea><br>
<input id="commentId" name="commentId" type="hidden" value="<?php echo $CommentID;?>">
<input id="userId" name="userId" type="hidden" value="<?php echo $uId;?>">
<input id="articleId" name="articleId" type="hidden" value="<?php echo $ArticleID; ?>">
<input class="btn btn-lg btn-default replyForm" id="<?php echo $CommentID; ?>" name="replyForm" type="submit" value="Reply">
</div>
The button with class name "replyForm" I get it by
$(".replyForm").click(function()
and here is the javascript and Ajax code.
$(".replyForm").click(function(){
//$(this).parents().next('.replyForm').click(function(){
var user_reply = $("#replyC").val();
var userId = $("#userId").val();
var comment_id = $("#commentId").val();
var articleId = $("#articleId").val();
$.ajax({
url:'articleReply.php',
data:{replyC:user_reply,userId:userId,commentId:comment_id,articleId:articleId},
type:'POST',
success:function(data){
$("#resultReply").html(data);
$('#replyC').val('');
}
});
});
The problem Now .. It doesn't work on all comments retrieved from the loop but works only on the first comment while trying reply on other comments I get my empty message appears under the first comment.
So it get data from the first comment only not from the rest.
Any help ??
Here it works:
Here is the problem:

Trying to pass multiple parameters from php to javascript

Heres my current code in php with one parameter which works
<?php
$sid = "012";
echo '<input type="button" value="Submit" onclick="changeConfirmed('.$sid.')">';
?>
Now im trying to pass two parameters or more, but cant seem to get it to work, here is my attempt:
<?php
$name="abc
$sid = "012";
echo '<input type="button" value="Submit" onclick="changeConfirmed('.$sid.','.$name.')">';
?>
You need quotes around the parameters or javascript treats them like variables instead of strings.
echo '<input type="button" value="Submit" onclick="changeConfirmed(\''.$sid.'\',\''.$name.'\')">';
If one of your JavaScript function parameters is a string, you'll have to correctly enclose it in quotes:
<?php
$name="abc";
$sid = "012";
echo '<input type="button" value="Submit" onclick="changeConfirmed('.$sid.',\''.$name.'\')">';
?>
You get away with $sid not enclosed in quotes because it looks like a number.

Submit multiple inputs through one form and append to array

So I am relatively new to JavaScript but I have experience with programming. I have this code which allows the user to define how many addresses they would like to enter so then I can query google maps and find the geographic center. The problem with this is that it looks very unprofessional in the sense that they have to enter the number of fields on one page and then they are prompted with that many boxes on the next page. Is there any way to make only one form(with all the parameters I require for one entry) and then after they click submit, I append it to an array and then when they decide they have enough addresses they hit the final submit so then I can process the data using a PHP call? Any help would be great, but I am new to this so I might need more spelt out explanations, sorry. Thanks again!
TL;DR: I want to create a single entry field which when submit is clicked, the page does not refresh or redirect to a new page and appends the data entry to an array. From there the user can enter a new input and this input would also be appended to the array until the user has decided no more inputs are necessary at which point they would click the final submit allowing me to process the data.
Here is the code I have so far:
<!DOCTYPE html>
<html class="no-js" lang="en">
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script>
$(function(){
var c = 0;
$("#button1").click(function(){
c = $("#inputs").val();
$("#mydiv").html("");
for(i=0;i<c;i++){
$("#mydiv").append('<input type="text" id="data'+i+'" name="data'+i+'" /><br/>');
}
});
$("#button2").click(function(){
$.post("getdata.php",$("#form1").serialize(),function(data){
});
});
});
</script>
</head>
<body>
<form id="form1">
Type the number of inputs:
<input type="text" id="inputs" name="inputs" />
<input type="button" id="button1" value="Create" />
<div id="mydiv"></div>
<input type="button" id ="button2" value="Send" />
</form>
</body>
</html>
getdata.php
<?php
for( $i=0; $i<$_POST["inputs"] ; $i++){
echo $_POST["data".$i]."\n";
}
?>
Here is code:
EDIT: I rewrite the code, so you can also delete each address
$(document).ready(function(){
$("#add-address").click(function(e){
e.preventDefault();
var numberOfAddresses = $("#form1").find("input[name^='data[address]']").length;
var label = '<label for="data[address][' + numberOfAddresses + ']">Address ' + (numberOfAddresses + 1) + '</label> ';
var input = '<input type="text" name="data[address][' + numberOfAddresses + ']" id="data[address][' + numberOfAddresses + ']" />';
var removeButton = '<button class="remove-address">Remove</button>';
var html = "<div class='address'>" + label + input + removeButton + "</div>";
$("#form1").find("#add-address").before(html);
});
});
$(document).on("click", ".remove-address",function(e){
e.preventDefault();
$(this).parents(".address").remove();
//update labels
$("#form1").find("label[for^='data[address]']").each(function(){
$(this).html("Address " + ($(this).parents('.address').index() + 1));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="form1" method="post">
<div class="address">
<label for="data[address][0]">Address 1</label>
<input type="text" name="data[address][0]" id="data[address][0]" />
</div>
<button id="add-address">Add address</button>
<br />
<input type="submit" value="Submit" />
</form>
After form submit you can loop through addresses like this:
foreach ($_POST['data']['address'] as $address){
...your code
}
Hope this help! :)
Normally how I do this kind of stuff is to provide a user ability to add many input fields at client level and send them all in one array when submitting the form. That is more professional I believe. Try this JSFiddle to see what I mean.
<input type="text" name="address[]" />
if you want to POST dynamic value in a form you can do it like this:
<input type="text" name="adress[]" />
so in your case you could add new fields with javascript or jquery with the same name name="adress[]".
and in your PHP you get an array:
$adresses= $_POST['adress'];
foreach ($adresses as $adress) {
echo $adress;
}
FIDDLE DEMO
To process an array of inputs you can use the following convention:
HTML: simply add square brackets to the name attribute
<input type="text" id="data'+i+'" name="data[]" />
PHP: Post returns an array
for( $i=0; $i<$_POST["data"] ; $i++){
echo $_POST["data"][$i]."\n";
}
JAVASCRIPT: $("#form1").serialize() will retrieve all the inputs data as name=value pairs even the inputs that are added dynamically. There's no need to keep an array you can just process all of them at the end.
You don't need to create an array, $_POST is actually doing it all for you already.
So I suggest you do the following: using javascript (or jQuery), keep the button clicks, but make sure the form submission is prevented (using preventDefault on the form) [EDIT: You actually won't need this, as if the buttons are just buttons, no submit inputs, the form will not submit anyway], and just make sure you append another element every time they click a plus button or something; make sure you increment the name attributes of each input element that gets created.
When the user then creates submit, use submit the form via js, then on your getdata.php you can simply loop through all the values and use them that way you want. You will even be able to know the exact number by calculating the number of times a new input element has been added to the form.
I'll try to write up something for you in a minute, but if I was clear enough, you should be able to do that too.
EDITED: So here is what I've come up with; give it a try and see if this is something for you.
This is how the form would look like:
<form id="form1" name="myform" method="post" action="getdata.php">
Enter address 1: <input type="text" name="address-1" /> <input type="button" value="More" onclick="createNew()" />
<div id="mydiv"></div>
<input type="submit" value="Send" />
</form>
And this would be the js code:
var i = 2;
function createNew() {
$("#mydiv").append('Enter address ' + i +': <input type="text" name="address-' + i +'" /> <input type="button" value="More" onclick="createNew()" /><br />');
i++;
}
...and then getdata.php:
foreach ($_POST as $key => $value) {
echo 'The value for '.$key.' is: '.$value.'<br />';
}
here is a fiddle demo

How to use a for loop variable in php that is declared in javascript language

I have a little bit complicated situation with codes but I made an easy example so that It is easier for you to understand what I actually need.
HTML:
<html>
<body>
<input type="button" value="Increase" name="increase" id="increase"></input>
<input type="button" value="Submit" name="submit" id="submit"></input>
</body>
</html>
Javascript:
$(document).ready(function() {
$count = 1;
$('input').click(function() {
$count++;
});
});
And the idea of all this web-page:
1)Click few times on button "Increase";
2)The javascript variable $count increases each time You clicked on that button;
3)When You click button "Submit", it makes php loop that repeats $count times and each repeating time it makes new record in some database table. Here is the example of possible php for loop:
for($i=1; $i<=$count; $i++) {
//Here makes new record in some database table. For example, it makes some tables rows "Number" = $i; <-- This is not important in my problem.
}
The question is about middle part of declaring for loop: "$i<=$count" - how it is possible to tell until what point I want this loop with variable, if that variable was made and increased in Javascript language? :?
PHP interpratate HTML, so you are can send variable via ajax only!
You could add an input field to your form and each time you increase your count variable you update its value, so when submitted, you can extract that number via the request.
$(document).ready(function() {
$count = 1;
$('input').click(function() {
$count++;
$('#your-input-field').val($count);
});
});
You should change your form like
<html>
<body>
<form method="post" action="/">
<input type="text" value="0" id="your-input-field" name="count"></input>
<input type="button" value="Increase" name="increase" id="increase"></input>
<input type="button" value="Submit" name="submit" id="submit"></input>
</form>
</body>
</html>
now you can extrach that number via $_POST['count']
You can't use the javascript variable directly in the PHP.
I think the best way to achieve what you want to do is using an AJAX request. You should use the javascript to send a request to another URL and then use the variable.
This is how you should do:
var url = 'create_database_records.php';
var request = $.post(url, { count: count });
request.done(function(data) {
// request is done
});
Notice that in this method you should have access to the count variable.
In the *create_database_records.php* you should use the $_POST['count'] variable.
Note: You should not use $ declaring javascript variables, use var count = 1 instead.
UPDATE: Another way to do this
You may want to put this buttons in a form, and add a new input (type: hidden) that will hold the counter.
<form action="create_database_records.php" method="POST">
<input type="hidden" value="1" name="count" id="count" />
<input type="button" value="Increase" name="increase" id="increase" />
<input type="submit" value="Submit" name="submit" id="submit" />
</form>
Then, in the click event you should change the hidden field value:
$(document).ready(function() {
count = 1;
$('#increase').click(function() {
count++;
$('[name=count]').attr('value', count);
});
});
In the *create_database_records.php* you should use the $_POST['count'] variable.

Two onclick on one element

I have a simple code to delete data from the database,and I want a warning message to appear before deleting. the code works fine when I put one onclick and when I put two only the first onclick works.
and I need to onclick one for the warning message and the other for delet.php page.
<form><input type="button" value="delete" onclick="return confirm('Really delete?');" onClick='window.location.href="delete.php?id= <?php echo $id; ?>"' ></form>
This is how I would handle it:
<input type="button" value="delete"
onclick="confirmDelete('<?php echo $id; ?>');">
Then elsewhere in the page:
<script type="text/javascript">
function confirmDelete(id) {
if(confirm('Really delete?')) {
window.location.href= "delete.php?id=" + id;
}
}
</script>
Notice I removed the <form> element. If this is the only context this is in, the <form> element is unnecessary since you're not actually filling out a form, just clicking a button. If there is more context you didn't include in your question, then it might be relevant to that.
Try using this with an if clause:
<form>
<input type="button" value="delete" onclick="
if(confirm('Really delete?')) {
window.location.href='delete.php?id=<?php echo $id; ?>';
}
else {
return false;
}
">
</form>
You can only use one onClick. But there's a way to do what you want in only one ;)
<form>
<input type="button" value="delete" onclick="
if(confirm('Really delete?')){
window.location.href=\"delete.php?id= <?php echo $id; ?>\"
}else{
return false;
}" />
</form>

Categories

Resources