This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I'm kinda new to working with JS and PHP and stumbled upon a little problem. Im trying to pass the ID of a textbox I clicked through to PHP and then query a database with that ID. I tried the following code to check if the variable gets passed on, but nothing is alerted:
<script type="text/javascript">
function Like(ID)
{
<?php
$id = ID;
print "alert('$id');";
?>
}
</script>
<input type="text" id="1" onclick="Like(this.id)" >
What I'm trying to accomplish:
I've got a database of videos with a unique ID. I have 2 buttons next to each video for either liking or disliking. The 2 buttons will have an id based on the ID of the video. For example video number 2 has 2 buttons: like(id=L2) and dislike(id=D2). When the user clicks either one of those buttons, I want to update the videos table's "likes" column without the page reloading. Would that be possible?
You aren't going to be able to do this the way you have written it. PHP runs once on page load. So, when you click the input, your function will already be evaluated by php as this:
<script type="text/javascript">
function Like(ID)
{
alert('ID');
}
</script>
The ID is a bareword to php, so it treats it like a constant if defined, or a string (and may generate a warning). Assuming you don't have a contant ID, then it prints the alert line with the string "ID" in the $id variable.
By the time your javascript is called, all you will ever get is alert('ID').
To query a database, you have to pass the data back to the server. This will either load a new page, or if you want it to happen without a page load, you need to make the call to the server asynchronously (in the background), and modify the page based on the result. This is called AJAX. You will need to understand how server-code (php) and client-code (php) work, and then you will better be able to understand how AJAX brings those together to do what you want.
Since you asked this in a comment:
Well, I've got a database of videos with a unique ID. I have 2 buttons next to each video for either liking or disliking. The 2 buttons will have an id based on the ID of the video. For example video number 2 has 2 buttons: like(id=L2) and dislike(id=D2). When the user clicks either one of those buttons, I want to update the videos table's "likes" column without the page reloading. Would that be possible?
I'll tell you a way to achieve it, and it doesn't even require Javascript! :) (at least at first).
It's an old fashioned HTML form element. Since you'll be posting data you should use action post. The code can look like this:
<form method="post" action="/requests/like-video/" class="like-video">
<div>
<input type="hidden" name="video_id" value="<?php echo $video->id ?>">
<input type="submit" value="Like">
</div>
</form>
<form method="post" action="/requests/dislike-video/" class="dislike-video">
<div>
<input type="hidden" name="video_id" value="<?php echo $video->id ?>">
<input type="submit" value="Dislike">
</div>
</form>
Once you have that in place (and working) it's just a matter of hijaxing those forms. A super easy way of doing that is to use jQuery's Form plugin and simply run:
$('form.like-video').ajaxForm(OPTIONS_GO_HERE);
$('form.dislike-video').ajaxForm(OPTIONS_GO_HERE);
Doing it this way ensures users without JS also get a fully functional site.
It's called progressive enhancement.
Related
I am having a problem where I am successfully setting a URL variable in the form of mywebsite.com/contact/?product=VAR1 from one page to another, and it will be read on the 2nd page with my simple code.
First use is fine but any thing after that is not. There is a problem with the variable not being cleared/re-read/reset. The URL Bar even reads fine in the URL bar mywebsite.com/contact/?product=VAR2 so that first part works.
But the code doesn't want to get the VAR2 part once it has stored VAR1. It just keeps re-displaying VAR1 once it is loaded once.
<?php echo htmlentities($_GET['product']); ?>
If it makes a difference, I am succesfully displaying the ?product= information inside of a jQuery value changer with this:
$(".input-text").val('<?php echo htmlentities($_GET['product']); ?>');
I have tried my own solutions like putting in a unset($product); before the last ?> but no avail.
I have a limited knowledge of PHP/jQuery and would like to use this way of setting/grabbing variable since it is simple. I am using it in jQuery because it can re-write the exact form input-box value with this variable passed along, and successfully send it in my CMS's contact form.
------------------------ updated: added code ------------------------
(I am just displaying all the code logically as I can think of)
#1: Set up the variable into the URL. The first echo getURL displays the url, I add my ?product= and then it gets the item name. This is all fine.
<a href="<?php echo Mage::getURL('webforms/index/index/id/2') ?>?product=<?php echo $_product->getName(); ?>">
#2: My form is set up within my CMS. It has a special class so I can select it exactly within my jQuery. I do not have access to all of this, it is generated by the CMS. The purpose obviously is to get selected products to be rememmberd via this Variable, and serve purpose in the contact form.
<div class="field webforms-fields-enquiryfield">
<label for="field_20">
Product in Enquiry
</label>
<div class="input-box">
<input type="text" name="field[20]" id="field[20]" class="input-text" style="" value="">
</div>
</div>
#3: Now that my area to display, & variable are set up, we use jQuery to insert the variable into the actual value of the input-text form. I am doing this because within my CMS I am not able to simply add it in. I have to use jQuery to replace the text (which is empty box anyway).
$(".webforms-fields-enquiryfield .input-text").val('<?php echo htmlentities($_GET['product']); ?>');
Hope that made more sense.
I have figured the answer to this, the problem was that the CMS Magento likes to cache certain blocks - which is why I could view it first, then my CMS would store the variable but not erase it. No matter what kind of fixes I tried to disable caching, no go.
Instead I ended up using the following code, using a # variable, and some simple JavaScript that anyone can understand. I will be using this in future projects no doubt! Very easy variable passing ...
if(window.location.hash) {
var hash_value = window.location.hash.replace('#', '');
$("my-css-input-field-or-whatever-you-want").val(hash_value);
}
The hash_value can be used in a variety of ways now I suppose, and this works well around my Magento set up, it does not get cached/stored. Grabbing the URL location & hash instead.
(And the PHP used, simplified for anyone to replace/reuse within a CMS)
<a href="[GetBaseURLfromCMS]#[MyDynamicVariableHere] ">
I am trying to submit a form using a hyperlink and it is not posting values onto the next page.Here is my code form:
<?php
$email = array('name'=>'accountno','id'=>'accountno','value'=>set_value('email'));
?>
<form method="post" id = "login_form" action="/salesrep/check" name = "login_form" class="custLogin">
<fieldset style="color: #BD1313; width: 440px;"> <input type="hidden" name="submit_type" id="submit_type" value="account_only">
<br><center><label for="customerNo"><b>Customer No:</b></label>
<? echo form_input($email);?>
Submit<? echo form_input($button);?> </center>
<p> </p>
</fieldset>
</form>
The code on the next page looks like this:
<?
print_array($_POST);
die();
?>
When i use the button here,it posts values to next page successfully.BUT I HAVE not been able to post values using the hyperlink on onclick event. Where i am making mistake??
Why i am getting empty array when i am already inserting value in the text box.?? Or is there any way i could post values using the link and retrieve them in the next page???
The real problem is that you are trying to use a link plus some JavaScript to submit a form in the first place. Don't do this. Buttons inform users that they will submit the form. They will show up in screen readers when they are in forms mode (a link with some JavaScript won't). They "just work".
If you insist on using a link and some JavaScript, then the reason that your code doesn't work is that the JavaScript runs, the form starts to submit, then the link is followed and a GET request is made to the page instead.
Normally you could call preventDefault on the event to stop this, but you are using old style intrinsic event attributes so you need to return false; from there instead.
Recommended reading: Progressive Enhancement and Unobtrusive JavaScript
Im trying to create a grid on my page in each cell there will be a simple one line form. If a person enters data into lets say FieldA I would like the php to perform actionA but if the data was entered in FieldF I would like actionF performed. Is this possible without having to create a php for each cell and upload all those php files?
Or is there a way to perform the GET method in each form to append the data to the end of the action url without the field name showing (ie sample.com/somestuff/fieldA instead of sample.com/somestuff/fieldname=fieldA) thus not needing php at all?
Did you try anything. Please try to write some code. If you get struck paste the code here, somebody will help you out..
In my opinion, why you need different forms. Just have a form which has n text boxes and perform the task that you need.
Your problem is a little ambiguous to me. I'll give it a shot though.
On the form I would set:
`method="post" action="<?php echo $PHP_SELF ?>"`
This will cause the form to submit back to itself. Then at the top of the page you could do something like the following:
<?php
if (isset($_POST["fieldA"]){
performActionA();
} else if (isset($_POST["fieldB"]){
performActionB();
}
etc...
?>
Is that what you are trying to do? Keep in mind php is executed server side before any interaction with the user.
otherwise you could use javascript to change the action field of the form. (Untested)
<script type="text/javascript">
function setAction(elt){
var page = document.getElementById(elt).value;
document.myform.action="sample.com/somestuff/"+page;
}
</script>
<form id="myform" action="sample.com/somestuff/">
<input type="text" name="text1" onchange="setAction('text1')" />
</form>
I have got a shopping cart which is build using jquery and php. and I need to generate hidden values for item id. Every time I click add, the value must be different.
I do not know how to create dynamic values which will be different on each click.
At the moment I created with php the following code.
<form method="post" action="" class="jcart">
<? $unique = md5(uniqid()); ?>
<input type="hidden" name="my-item-id" value="<?=$unique;?>" />
<input type="submit" name="my-add-button" value="add to cart" class="button" />
</form>
The problem is unless I refresh the page I'm getting same hidden value. What can I do to get different values without refreshing the page.
with the date ?
Date.getTime();
You could store a simple integer in a cookie and use that as the basis for an incrementing counter to generate that "unique" value. As long as you take care to not have multiple 'add' scripts running at the same time and make sure your cookie updating code is bulletproof, it should take care of the uniqueness problem.
if you are adding using ajax, set it in the return of the ajax call
If the value can be random, you could use a javascript time call like getTime() that will get the number of milliseconds since 1972. It's not likely you'll get a duplicate ID, but you could append a random number to it to be sure.
The best approach would be to use an Ajax call (via jquery) to your server and get the ID from the server.
I think you may need to use jQuery load() function and have a PHP page that generates the md5() id for you like this:
<script>$('input[type=hidden]').prev().load('ajax/uniqueId.php');</script>
the jQuery would be placed next to the Add button.
And your PHP page would look like this...
<?php
echo md5(uniqid());
?>
Try uniqid() http://php.net/manual/en/function.uniqid.php
I am that kind that spends more time looking for bugs in web projects and correct them, but I still have one question about the use of the GET and POST method
To summarize , I often use the GET method for queries that may be coming from links or simple buttons example :
Click me
and for forms (signup,login, or comment) I use the post method. but the question is:
sometimes (Multi-steps signup for e.g), I may need to pass the info collected from the form in page 1 to a page 2 (where the user can find a captcha for e.g). in order to send them to the database if the captcha test is Okey. But the question is , how to pass those info to a next page via a POST method without using a hidden form?
Do I need to recreate a POST method from scratch with a socket?
thank you
You can use JavaScript (jQuery):
First u need to load jQuery ( using google as host or you download it):
<script type="text/javascript" src="http://jqueryjs.googlecode.com/files/jquery-1.3.2.js"></script>
Then...
<script type="text/javascript">
$(document).ready(function() {
$('#Link').click(function() {
$.post("example.php", { n: "203000"} );
});
});
</script>
<a id="Link" href="#">Click me</a>
Edit:
after that save it in the SESSION in example.php
$ _SESSION['N'] = (int) $_POST['n'];
When this value will be stored on the server side. And tied to the client session, until he closes browser or that it set the time for that session on the server side runs out.
Edit2:
There is also another possibility to post requst, yes ..
But I do not like this method myself ...
And here is the form used, something the OP did not want.
<form name="myform" action="example.php" method="POST">
<input type="hidden" name="n" value="203000">
<a id="Link" onclick="document.myform.submit()" href="#">Click me</a>
</form>
Use sessions to store the data until you submit them:
http://de.php.net/manual/en/intro.session.php.
Using sessions has a big advantage,
once you have verified the data you can store it.
Always keep in mind that users may manipulate POST requests!
If the problem is to pass info between pages like in a multi-step form you should use session (if you are using PHP).
By the way for send a POST request without form you need to use CURL like in this example
The statement is a HTML language statement used by a browser to initiate a POST/GET data relation. The Browser is the execution environment.
You can use other languages (and their execution environment) like Java, Java Script, C#, etc. to initiate HTTP POST/GET data relations.
Sorry if I'm not understanding you correctly, but from what I'm reading, you want to access form data entered on page 1 (using a form with a post method) on page 2? If so, use the $_POST autoglobal array. For example, $nameOnPage2 = $_POST['nameFromPage1']. You don't have to create a form on the second page for this.