jquery return value by php echo command - php

I have these codes:
Contents of main.php:
Javascript
function grab()
{
$("#div_id").load("/test.php");
}
HTML & PHP
<? $original_value = 'Original content'; ?>
<div id='div_id'><?=original_value;?></div>
<form action="javascript:grab($('#div_id').val())">
<input name="submit" type="submit" value="submit">
</form>
also test.php
<?...
$update_value = "Update content";
echo $update_value;?>
the result of test.php will be written into #div_id and the result for div content is:
Original content
Update content
But i like to overwrite original div value and the result should be:
Update content
I mean echo append a new line in #div_id, but i like to overwrite existing #div_id content.

Change the following in your code.
Remove the javascript in your action attribute. It doesn't look right.
<form action="">
<input name="submit" type="submit" value="submit">
</form>
Add the following javascript.
$(document).ready(function () {
$('form').on('submit', function (e) {
e.preventDefault(); // Prevents the default submit action.
// Otherwise the page is reloaded.
grab();
});
});
The function grab will be called when the form is submitted. I'm not sure if this is what you want, but you should see the new contents in the div.
UPDATE 1:
I have removed the parameter from grab because the function doesn't need one.

You need to replace the content while the current code appends it, change code to:
$("#div_id").empty().load("/test.php");

Related

Return the url to its original state after refresh

I wrote this form using html and PHP on my webpage. This form receives a number as input. and adds the desired number to 2. And prints the output.
For example, if we put the number 5 at the input and press the submit button , The page refreshes to this URL : mysite.com/page1/?sen=5&sub=Submit
And the number 7 is printed on the output.
So far so good. But when we refresh the page in this case , The submitted information will not be deleted and the url will remain "mysite.com/page1/?sen=5&sub=Submit" .And the output is not cleared and still remains 7.
In this case, I want the page to return to its original state, (mysite.com/page1) . And the output is cleared.
what's the solution?
<form name="form1" action="" method="GET">
<input type="number" name="sen" placeholder="سن">
<input type="submit" name="sub" placeholder="ثبت">
</form>
<?php if ( isset($_GET['sub'])){
//$sen1=0;
$sen1 = $_GET['sen'];
if (empty($sen1)){
echo "ooopppss";
}
else {
echo $sen1 + 2; }
}
?>
This can easily be achieved with Javascript. Here's a very basic example.
You could make this a function. Then call it once to invoke it on a page refresh, and if you want to invoke it on button actions, you can use an html onclick attribute, or an event listener.
<script>
function clearFormAndParams() {
// Target each form input and set the value to "".
document.querySelector("input[name='sen']").value = "";
// Split the url by the "?" and then set the value to the first half.
window.location = window.location.href.split("?")[0];
}
clearFormAndParams(); // runs on refresh
var submitButton = document.querySelector("input[name='sub']");
submitButton.addEventListener("click", function() {
clearFormAndParams();
});
</script>
You could achieve your goal by modifying your code to store the results of calculation in a cookie / session variable and redirecting to the same page without the extra parameters like so:
<form name="form1" action="" method="GET">
<input type="number" name="sen" placeholder="سن">
<input type="submit" name="sub" placeholder="ثبت">
</form>
<?php
if ( isset($_GET['sub'])){
$sen1 = $_GET['sen'];
if (empty($sen1)){
echo "ooopppss";
}
setcookie("result", $sen1 + 2);
header("Location: " . $_SERVER['PHP_SELF']);
}
echo $_COOKIE['result'];
?>

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.

calling a php object method on clicking a button?

I've been working on php application and I've used a OO programming so far to develop it . I have declared a class like this
<?php
class User
{
public function Add_element()
{
//adds some element
}
public function Delete_Element($element_ID)
{
//delete the element with that ID
}
}
?>
I've created an object of user class (for example $user = new User()) in my index.php file which includes my view.index.php and the view.index file is organized as follow
<html>
<header></header>
<body>
<input type="button" id="ID" value='Delete Element' >
</body>
<html>
I know this question may seem repetitious but I want to know how can I call the $user->Delete_element($ID) method upon clicking the button .
You could do something along these lines:
First of all use a form:
<form method="POST" action="delete.php">
<input type="hidden" name="element_id" value="id">
<input type="button" name="delete" value="Delete element">
</form>
And create the following php script:
if(isset($_POST['element_id']))
{
$element_id = intval($_POST['element_id']);
$user->deleteElement($element_id);
}
OR use ajax, which is a bit more complicated.
Edit:
If you do not want to refresh the page you should use AJAX. Start off by including jQuery, which makes this a lot easier. Now you need something like this:
$("form").submit(function(e){
var data = {};
data.element_id = $(this).find("[name='element_id']").val();
$.POST("delete.php", data).done(function(response){
alert(response);
});
e.preventDefault();
});
edit your html file (change the "input" tag to an html form):
<form action="Delete_Element.php" method="POST">
<input type="button" name="ID" value='123456789' >
</form>
create a new php page called "Delete_Element.php":
<?php
if ( isset($_POST["ID"]) )
{
/* init the "user" object, assuming it is init to: $myUser */
//this line invokes your method, given the posed IP param. .
$myUser->Delete_Element($_POST["ID"]);
}

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>
";
?>

Combing JS and PHP on one button. Is it possible?

Hiya:
i know some people would be so tired of my questions, but I'm working on a uni project and need to get it done as soon as possible. This question is about using JS on a button(button) and sending a php_my_sql update on the same button. The problem is JS uses button, right? but PHP uses button(submit). How can I get these two to work on one of these buttons, cuz there has to be only one button.
this is my code for JS
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex)
}
</script>
HTML
<form method="post">
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="**submit/button**" onclick="formAction()" name="Collect" value="Collect" /></form>
PHP
<?
if (isset($_POST['Collect'])) {
mysql_query("UPDATE Player SET score = score+10
WHERE name = 'Rob Jackson' AND rank = 'Lieutenant'");
}
?>
This can be a way
Submit the form through JS after removing parameter
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect")
x.remove(x.selectedIndex);
document.forms[0].submit();
}
</script>
Input type button
<input type="button" onclick="formAction()" name="Collect" value="Collect" />
Embed jQuery and use $.post() to send an AJAX request.
JavaScript can interact with the button whilst the user is navigating the page and entering data into the form. The instant the user pushes the submit button and the request for the form submission is sent JS no longer has control. The request is sent to the form's action (most likely a PHP file) which processes the request and gives an answer back.
If you really need to combine the two, look into AJAX.
<?php print_r($_POST); ?>
<script type="text/javascript">
function formAction(){
var x=document.getElementById("collect");
x.remove(x.selectedIndex);
submit_form();
}
function submit_form() {
document.form1.submit();
}
</script>
<form method="post" name='form1'>
<input type='hidden' name='Collect'/>
<select id="collect" name="Select1" style="width: 193px">
<option>guns</option>
<option>knife</option>
</select> <input type="button" onclick="formAction()" name="Collect" value="Collect" /></form>
<?
if (isset($_POST['Collect'])) {
//do whatever update you want
}
?>
Simple Solution
Make this modification in the form tag
<form method="post" onsubmit="return formAction()">
In JavaScript function add a line "return true;" at the end of the function.
Voila ..!!! you are done..!!
Enjoy..!!

Categories