How can I integrate javascript onclick function with php? - php

I am having a problem with onclick function integrating it with php .Can someone please help
Below is my codes
<html>
<head>
<title></title>
<script language="Javascript">
function delete()
{
val del=confirm("Do you wanto delete the player?");
if(del==true)
{
alert("player Deleted");
}
else
{
alert("record not deleted");
}
return del;
}
</script>
</head>
<?php
Echo “
<a href='delete.php?player_id=$player_id' onclick='delete()'>Delete</a>”
?>

the most important thing: do not use the javascript keyword delete (JavaScript delete operator help) as function name! Your function (and thus onclick) won't work because of this!
Change it to something appropriate like deleteRecord and you could use php only to output the ID, like:
<html>
<head>
<title></title>
<script type="text/javascript">
function deleteRecord()
{
if (confirm("Do you wanto delete the player?")) {
alert("player Deleted");
}
else {
alert("Record not deleted");
}
}
</script>
</head>
<body>
<a href="delete.php?player_id=<?php echo $player_id ?>" onclick='deleteRecord();'>Delete record?</a>
</body>
</html>
kind regards,
P.

I found a pretty good solution. However, It adds a little extra to your code. I do not recommend using this method too much. I am a new PHP developer, so there are probably somethings this method can and cannot do.
also I cannot seem to prevent this method from loading a new page, so the best way is to add your php to the beginning of the file. This is also a better solution for using AJAX (my opinion)
if the current file is index.php...
make a form tag element
'<form action="index.php" method="post">'
'<input type="submit" name="helloWorld" value="hello World">'
'</form>'
here you will display the content of what you are trying for, with a click
'<article>'
'<?php echo myFunction(); ?>'
'</article>'
this next php markup can go anywhere as long as it it is in the same file... Unless you know how to work around. Best place is before the HTML.
'<?php '
'function myFunciton() {'
'if (isset($_POST[helloWorld])) {'
'echo "hello world"; ... your methods'
'}'
'}'
or you could directly access it without using a function
<body>
<form action="index.php" method="post">
<input type="submit" name="hello" value="hello">
<input type="submit" name="goodBye" value="goodBye">
</form>
<article>
<?php
if (isset($_POST[hello])) {
echo "This happens if you click hello";
}
if (isset($_POST[goodBye])) {
echo "This happens if you click goodBye";
}
?>
</article>
</body>

Related

How to create confirm yes/no in php?

I want to create a confirm yes/no box in php
my code like this:
<?php
if(isset($_REQUEST['id']))
{
?>
<script>
var cf=confirm("do you want to delete Y/N");
if(cf)
{ i want to call code edit of php
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<form name="frm" method="post" action="edit.php">
Edit <br>
Edit <br>
Edit <br>
</form>
</body>
</html>
I Want to when press Yes i call code edit in PHP
But it do not work.
Can you help me ?
Thanks you
Just use inline onclick event.
This is a simple techique, you can use it in your PHP page.
Edit
In your code, you have mentioned PHP but, have used JavaScript.
If you want to do a confirm with PHP,
Create an intermediate page for confirmation.
Post form data there.
On confirmation page, add two submit buttons:
Yes: If pressed this, redirect/post to edit page.
No: If pressed this, redirect back to form
So, your confirmation page should be:
<html>
<head>
</head>
<body>
<?php
if (isset($_POST['confirm'])) {
if ($_POST['confirm'] == 'Yes') {
header("Location:edit.php?id=1");
}
else if ($_POST['confirm'] == 'No') {
header("goBack.php");
}
}
?>
<form method="post">
<?php
if(isset($_REQUEST['id']))
{
?>
<input type="submit" name="confirm" value="Yes"><br/>
<input type="submit" name="confirm" value="No"><br/>
<?php
}
?>
</form>
Put an id on your form:
Create an event listener for the form's onsubmit event
<script>
function onFormSubmission(e){
return confirm("do you want to delete Y/N");
}
var frm = document.getElementById('frm');
frm.addEventListener("submit", onFormSubmission);
</script>
When the user submits a form they will be prompted with your message. If they click Yes the function will return true and the form will be submitted. Otherwise the function will return false and the form submission will be cancelled
I think this is what you want to do:
<?php
//YOU MUST BE SURE THAT YOUR URL CONTAINS THE $_REQUEST['id'] PARAMETER, OTHERWISE IT WON'T WORK FROM YOUR CODE... IF YOU WANT IT TO WORK REGARDLESS OF THAT, JUST COMMENT OUT THE IF(ISSET(... BLOCK...
$editURL = "edit.php"; //EDIT URL HERE
if(isset($_REQUEST['id'])) {
//ASSIGN THE ID TO A VARIABLE FOR BUILDING THE URL LATER IN JS...
//THE DEFAULT ID IS 1 BUT YOU CAN DECIDE WITH YOUR OWN LOGIC
$defaultID = ($dID = intval(trim($_REQUEST['id']))) ? $dID : 1;
?>
<script>
function confirmEdit(evt){
evt.preventDefault();
var cf=confirm("do you want to delete Y/N");
var id=<?php echo defaultID; ?>;
if(cf){
//i want to call code edit of php
//HERE'S THE CODE YOU MAY NEED TO RUN;
if(id){
//RETURN TRUE SO THAT THE SCRIPT WITH LINK TO THE APPROPRIATE URL
return true;
// OR REDIRECT WITH JAVASCRIPT TO EDIT PAGE WITH APPROPRIATE ID
//window.location = "" + <?php echo $editURL; ?> + "?id=" + id; //YOU ALREADY HAVE THE EDIT URL... JUST APPEND THE QUERY-STRING WITH ID TO USE IN THE EDIT PAGE
// You might also just (without redirecting) return true here so to that the page continues like you just clicked on the link itself...
}
}
}
</script>
<?php
}
?>
<html>
<head>
</head>
<body>
<!-- THE FORM TAG IS NOT NECESSARY IN THIS CASE SINCE YOUR ANCHOR TAGS HAVE THE EXACT URL YOU WANT ASSOCIATED WITH THEM... AND YOU DON'T EVEN NEED JAVASCRIPT IN THIS CASE... BECAUSE THE HREF OF THE LINKS ARE HARD-CODED... -->
<!-- <form name="frm" method="post" action="edit.php"> -->
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-1' href="edit.php?id=1">Edit Page 1 </a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-2' href="edit.php?id=2">Edit Page 2</a> <br>
<a class='class-4-css' onclick="confirmEdit();" id='dynamic-id-based-btn-3' href="edit.php?id=3">Edit Page 3</a> <br>
<!-- </form> -->
</body>
</html>
So, now clicking on any of the Links will Ask me to confirm if I want to delete the Resource or not. If I choose yes, then the appropriate page is loaded for the Process...
not sure if the other answers really answered your question, this was my problem too, then I experimented and here's what I came up with:
.
confirmation in php :
$Confirmation = "<script> window.confirm('Your confirmation message here');
</script>";
echo $Confirmation;
if ($Confirmation == true) {
your code goes here
}
that's all, other people might look for this, you're welcome :)
I was looking to simply have a confirmation box in php before triggering POST isset without going through javascript:
echo "<input id='send_btn' type='submit' value='previous'
name='previous' OnClick=\"return confirm('Are you sure you want to go
to previous');\" >";
This appeared for me to be the easiest solution.

Add items to array without refreshing the page?

http://alpha.ripfy.com/
As seen in the following demo, I have a YouTube video that I want to be able to play while adding items to the array in PHP. Sadly, this isn't possible from what I've tried because the page refreshes every time I add an item to the array.
Would there be any way of achieving this without the page refreshing (forcing the video to restart?)
Code:
<?php
if (isset($_POST['playlist'])) {
$playlist = $_POST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_POST['name1'])) {
$playlist[] = $_POST['name1'];
}
?>
<form method="post">
<?php
foreach($playlist as $song) {
?>
<input type="hidden" name="playlist[]" value="<?php echo $song?>">
<?php
}
?>
<input type="text" name="name1"/>
<input type="submit" name="submit1"/>
</form>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
Thanks for helping me out!
if you need that these information be storaged in database or anything on server sider don't use the convencional form post, use AJAX with JQuery.
First create a div(container)to render the list content where you need the information apears:
<div id="list_musics"></div>
Then create a page(i.e. page.ajax.php) that will treat your request. If you need you can put the information in a database or anything you want by this page. This page must return the content you want to render.
HTML:
<input type="button" id="ajaxcaller">
JQUERY:
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
$.post(page.ajax.php,text,function(data){
//Render your content in the container created on HTML
$("#list_musics").html(data);
});
});
If you just need to show what you wrote on text input instead of storage or treat the information, you may just use JQUERY to render the information in the container you created.
$('#ajaxcaller').on('click', function(){
//AJAX CALL WITH POST METHOD
var text = $('input[name=name1]').val();
// PUT THE TEXT RIGHT AFTER THE CONTENT THAT ALREADY EXISTS IN THE CONTAINER
$("#list_musics").append(text);
});
Take a look here to see the sencond option:
https://jsfiddle.net/wqLf65ox/
Here's my answer. That fully works. In this script, the server checks the presence of a name1 request (post or get). If exists, it returns the string posted (only) and if doesn't, it returns what already was there. And the post() method posts (gets) the data and appends to the container using innerHTML+= data + "<br>";
evaluate the code, it should be self explanatory.
<?php
if (isset($_REQUEST['playlist'])) {
$playlist = $_REQUEST['playlist'];
} else { // Else set my default list
$playlist = array("Be more.mp3", "Drift Away.mp3", "Panda Sneeze.mp3");
}
if (isset($_REQUEST['name1'])) {
// if exists, return plain text responce. NOT HTML
$playlist[] = $_REQUEST['name1'];
echo $_REQUEST['name1'];
}
else{
?>
<html>
<head>
<title>Demo</title>
<script src="jquery.js"></script>
</head>
<body>
<script>
text= ""
function onUpdate(){
text = document.getElementById("name1").value;
}
function handler(data){
document.getElementById('container').innerHTML += data+"<br>";
}
function post(){
onUpdate();
$.get("index.php", name1="+text, handler);
}
</script>
<input type="text" name="name1" id="name1"/>
<input type="submit" name="submit1" onclick="post()"/>
<iframe width="560" height="315" src="https://www.youtube.com/embed/pzB6CxChIQk" frameborder="0" allowfullscreen></iframe>
<br>
<div id="container">
<?php
foreach ($playlist as $value) {
echo $value."<br>";
}
?>
</div>
</body>
<?php };?>
Although, it works as intended, i don't see the point of using it. just plain js should work
You have to send your form using Ajax, eg. via jQuery.post() method.
After that you have to reload your container with list or add new item there with JavaScript.
Try using the $.post and $.get JQuery methods. One method might be to $.post back to a .php page that renders a container of html, then use $.get to retrieve just that html container and insert into the DOM.

Undefined index when passing variable from jquery to php

I'm trying to pass a variable from an html file, using jquery and ajax to a php file, where I want to process it. I have two test files:
ajax.html
<html>
<head>
<title>ajax</title>
<script type="text/javascript" src="jquery.js"></script>
<link href="ajax.css" rel="stylesheet" type="text/css" />
<script type="text/javascript">
$(document).ready(function () {
$("#call_back").click(function () {
$.post(
"ajax.php", {
value: $("#input_text").val()
},
function (data) {
$("#response_text").val(data);
}
);
});
});
</script>
</head>
<body>
<div id="wrapper">
<h3>Ajax</h3>
<div class="entry-wrapper">
<h4>Data to send to the server</h4>
<input type="text" size="50" id="input_text" />
<input type="button" value="Ajax Callback" id="call_back" />
</div>
<div id="response_wrapper">
<textarea id="response_text"></textarea>
</div>
</div>
</body>
</html>
and ajax.php
<?php
$value = $_POST['value'];
echo "Returned from the server: $value";
?>
The html works fine. If I enter a value in the text field, it's passed to the php file, processed and sent back to be displayed in the textarea.
I've looked in firebug and the post tag in the console shows the values that I enter.
The problem is that I want to be able to use the variable in the php file, for arithmetic operations or running an sql query with it, but it shows up as undefined index when I open the php file.
I've looked through multiple threads on passing variables from jquery to php but still found no answer. I have no idea what the problem is. Suggestions are much appreciated. Thanks.
If I understand you question correctly, you need to define the variable in your url.
Example:
http://yoursite.com/ajax.php?value=yourdata
This way when you open the file you are defining the value which is all you are doing with your ajax request. If this is not what you are trying to accomplish, try to rephrase your question.
Revised after 1st comment:
<?php
if(isset($_POST['value'])){
//do whatever in here
dowhatever();
}
function dowhatever() {
$value = $_POST['value'];
echo "Returned from the server: $value";
if(value == 'data') {
//run query
}//end if
}
?>
I assume that when you say you can confirm it's working, but when you directly open the .php file, it has undefined index, then I would say that makes perfect sense. If you are browsing directly to the .php file, then no POST data is being sent. But if you are able to type in some text, fire off the submit, and get text back as planned, then it's working.

how to [professionally/correct way] insert php code into javascript and/or html?

For instance,
in javascript:
1
<script>
var name = "<?php echo 'Adam'; ?>";
alert("The name is: " + name);
</script>
or
2
<script>
alert("The name is: <?php echo 'Adam'; ?>");
</script>
And in html?
1
<head>
<?php echo '<title>Page #1</title>'; ?>
</head>
or
2
<?php $page_number = "1"; ?> // on top of the script with the rest of the other X code. //
<!doctype html....
<html>
<head>
<title>Page #<?php echo $page_number; ?></title>
</head>
I'm not looking for the short, long, easy or hard method, I'm looking for the correct method to do this.
1 - In a professional way, how this should be done?
2 - What is your way/method to do this?
Thanks
Update:
Also:
<input type="button" onclick="javascript:add_friend(0,<?php echo $profile_user_id; ?>);" />
There is no correct method. Rather, there are conventions that you will find yourself using, or your team will find itself using. Further, it is at times a case by case situation where your HTML may need to be processed a bit by PHP prior to being spit out, and other times it may not.
I happen to prefer seeing as clean as separation as possible, where the limits of the PHP tags are shared by the same limits of any code we would hard-wire into place.
<title><?php echo $title; ?></title>
<script>
var strValue = <?php echo json_encode( $strValue ); ?>;
</script>
But again, that's just me.
With regards to JavaScript within HTML attributes, I would encourage you to stay as far away from that as you can. Rather than using onclick attributes, bind all of this up in your JavaScript. This, again, keeps a clean line of separation between your structure and your logic.
Which would you prefer seeing in your markup:
<input type="button" onclick="javascript:add_friend(0,288);" />
Or
<input type="button" data-action="add_friend" data-friendId="288" />
Keep your programmers out of your design, and more importantly your designers out of your code.

how to write javascript code inside php

i have a got a form, on clicking the submit button:
I want to do some task in the same file (db task) AND
I want the form data to be sent to test.php with the redirection
here is my code
<?php
if(isset($_POST['btn'])){
//do some task
?>
<script type="text/javascript">
var e = document.getElementById('testForm'); e.action='test.php'; e.submit();</script>
<?php
}
?>
<form name="testForm" id="testForm" method="POST" >
<input type="submit" name="btn" value="submit" autofocus onclick="return true;"/>
</form>
but not able to submit the form, if i call the javascript code on onClick, it works.what is the problem in this code, Is there any work around for this
Just echo the javascript out inside the if function
<form name="testForm" id="testForm" method="POST" >
<input type="submit" name="btn" value="submit" autofocus onclick="return true;"/>
</form>
<?php
if(isset($_POST['btn'])){
echo "
<script type=\"text/javascript\">
var e = document.getElementById('testForm'); e.action='test.php'; e.submit();
</script>
";
}
?>
Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.
<?php
$script = <<< JS
$(function() {
// js code goes here
});
JS;
?>
After closing the heredoc construction the $script variable contains your JS code that can be used like this:
<script><?= $script ?></script>
The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.
You can put up all your JS like this, so it doesn't execute before your HTML is ready
$(document).ready(function() {
// some code here
});
Remember this is jQuery so include it in the head section. Also see Why you should use jQuery and not onload
At the time the script is executed, the button does not exist because the DOM is not fully loaded. The easiest solution would be to put the script block after the form.
Another solution would be to capture the window.onload event or use the jQuery library (overkill if you only have this one JavaScript).
You can use PHP echo and then put your JavaScript code:
<?php
echo "
<script>
alert('Hellow World');
</script>
";
?>

Categories