Javascript: Need to proceed to another page - javascript

I'm using Javascript for deleting a record. But my problem is, when I click the image button its not redirecting to the page I want instead it will remain on the page...
Here's my code:
echo "<button type='submit' name='deletePlaylist[]' value='" . $row['id']."' onClick='myFunction()' style='border: 0; background: transparent; cursor: pointer;'><img src='image/delete.png' /></button> ";
I'm using the button because I'm using an image if I used the input its not working... So I decided to use button
Here's my code in my javascript:
function myFunction()
{
var Xcancel;
var Rokay=confirm("Are you sure you want to delete?");
if (Rokay==true)
{
window.location = 'delete.php';
}
else
{
Xcancel="You pressed Cancel!";
}
}
</script>
I already tried the window.navigate("delete.php"); or the window.location.href='delete.php' also not working...
The confirmation message is displaying already but my main problem its not going to the delete.php where in that form is my deleting function...
NOTE:
The button is under of the <form name='form' method='post' action="">, the delete.php is in the same folder... Before there is no confirmation message and its going to the delete.php but now I tried to insert a confirmation message then its not going to the delete.php... The form action is empty because I have a click able dropdown list where it will proceed to the result.php
Here's the code for my dropdown list:
<select id="year"name="year"onChange="this.form.action='booking_delete_two.php'; this.form.submit()">
<option value="2013" <?php if($get_year=='2013') echo "selected"?>>2013</option>
<option value="2014" <?php if($get_year=='2014') echo "selected"?>>2014</option>
</select>
<select name="id" onChange="this.form.action='booking_delete_three.php'this.form.submit()">
<option value="<?php echo $get_ID; ?>"><?php echo $get_ID; ?></option>
<?php
$q = mysql_query("select * from tblnetwork");
while ($row1 = mysql_fetch_array($q))
{
if($get_ID != $row1[fldNetname])
{
echo "<option value='".$row1[fldNetname]."'>".$row1[fldNetname]."</option>";$get_netname = $row1[fldNetname];
}
}
?>
</select>
As you can see I empty the action because I have a three different pages where it will proceed....
a. booking_delete_two
b. booking_delete_three.
c. delete...
Thank you in advance,!

Make these changes to your script:
function myFunction(evt)
{
evt.preventDefault(); // this will keep the page from submitting and aloow the rest of the script to run
var Xcancel;
var Rokay=confirm("Are you sure you want to delete?");
if (Rokay==true)
{
window.location = 'delete.php';
}
else
{
Xcancel="You pressed Cancel!";
}
}

The form is being submitted to its default action. You need to prevent this submission. Just append onsubmit = "return false" to your form. This will prevent the form from submission.
<form name='form' method='post' action="" onsubmit="return false;">

I would be correcting how forms are meant to be validated instead of making work arounds.You best bet is to follow the same practice as what W3schools sets out below:
http://www.w3schools.com/js/js_form_validation.asp
So it should look like:
<form name="form" action="" onsubmit="return myFunction()">
<button type="submit" name="deletePlaylist[]" value="' . $row['id'].'" style="border: 0; background: transparent; cursor: pointer;">
<img src="image/delete.png" />
</button>
</form>
EDIT:
myFunction() could then look like below:
function myFunction()
{
var Xcancel;
var Rokay=confirm("Are you sure you want to delete?");
if(Rokay == false){
Xcancel="You pressed Cancel!";
}
return Rokay;
}
EDIT2: Added to 'myFunction()' a dynamic way of assigning the form action :p You can leave the original action attribute blank or have it as a default.
EDIT3: Seeing your drop down code I returned my answer to something like it was originally. Test it out.

Related

return method for form submission in javascript

developers i create one page where it fetches data from the registration page. Each data row I put add and unfriend button (disabled). Once the user clicks add, the prompt box appears to ask the user to enter a subject and click ok. After click ok,it insert in another database table.while the unfriend button will be able to click. Here my problem is once click add button the prompt appears and after click ok, the data does not insert into the database. If I click unfriend button it inserts into the database. I want the data submitted whenever the user clicks the add button. I think it's because this form has two submit buttons but I don't know how to distinguish between the buttons.Moreover,in javascript i put return false and true follow some tutorials.may i know when i should use return false and true?. Here is the code:
<?php
session_start();
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID";
$result= mysqli_query($mysqli,$sql);
?>
<html>
<script>
function myFunction(form){
var subject = prompt("Please enter Subject that want to study");
form['add'].value="request sent";
if (subject != null){
form['subject'].value= subject;
form['btn'].disabled=false;
form['add'].disabled=true;
return false;
form.submit();
}
return true;
form['add'].submit();
}
function unfriend(form){
form["add"].disabled=false;
form["btn"].disabled=true;
form["add"].value="Add friend";
return true;
form.submit();
}
</script>
<body>
<?php
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID=$row["register_ID"];
?>
<form method="post" id="form" enctype="multipart/form-data" autocomplete="off">
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="hidden" id="subject" name="subject" data-uid=<?php echo $_SESSION['sid'] ;?>/>
<td><input type="submit" onclick="return myFunction(this.form);" name="addfriend" data-type='addfriend' id="add" class="btn" value="add" />
<input type="submit" value="unfriend" id="btn" onclick="return unfriend(this.form);" disabled /> </td> </form>
<?php
}
}
?>
<?php
if(isset($_POST['subject']) and $_POST['id']) {
$user_id = $_SESSION['sid'];
$friend_id = $_POST['id'];
$status = "yes";
$subject=$_POST['subject'];
$sql="INSERT INTO friends(user_id,status,subject,friend_id)" ."VALUES('$user_id','yes','$subject','$friend_id') ";
if($mysqli->query($sql)=== true) {
$_SESSION['status']="yes";
$_SESSION['friend_id']=$friend_id;
$_SESSION['user_id'] = $user_id;
} else {
}
}?>
</body>
</html>
Your return statements terminate the function; no code after the return will execute, so your form.submit() calls never happen. In your friend function, because you're returning false and your onclick has return friend(...), you're cancelling form submission, and the form is never submitted (not by your code, and not by the browser), In unfriend, though, you're returning true, so although your code doesn't submit the form, the browser does.
If you want to submit the form programatically, put those form.submit calls before the return, and return false so the browser doesn't also submit the form.

How to reload user defined tag in CMS Made Simple

I have a html file which loads a list from my database and allows the front end user to remove a particular entry.
The HTML Code looks like this:
<script type="text/javascript">// <![CDATA[
function sendForm() {
var dataSend=$("#clientid").val();
$("#responseDiv").html("<h2>Removing from Database...</h2>");
$.post("RemoveClient.php",{
ClientId: dataSend
},function(data) {
$("#responseDiv").html(data);
$("#clientlist").empty();
$("#clientlist").html("{client_list nocache}");
});
return false;
}
// ]]></script>
</p>
<div id="MainForm"><form class="form" onsubmit="return sendForm()">
<h2 class="formstyle">Client Wizard</h2>
<p>Please fill all the required fields.</p>
<div id="clientlist">{client_list nocache}</div>
<p><input style="font-size: 1.5em; font-color: #000000;" onclick="sendForm()" type="submit" value="Delete" /></p>
</form>
<div id="responseDiv"> </div>
</div>
The UDT called for {client_list} is given below.
$dbhost='127.0.0.1';
$dbuser='user';
$dbpass='pass';
$dbname='dbname';
$conn=mysqli_connect($dbhost,$dbuser,$dbpass,$dbname);
if(!$conn)
{
die('Could not connect:'.mysqli_connect_error());
}
$sql="SELECT clientid,clientname FROM client order by clientid";
echo "<label> Select Client: </label>";
echo "<select id=clientid name=clientid>";
$result=mysqli_query($conn,$sql);
while($row=mysqli_fetch_assoc($result))
{
echo "<option value=".$row['clientid'].">".$row['clientname']."</option>";
}
echo "</select>";
Now, once I click on delete, I want the drop down list to refresh with the new list not having the deleted client. I tried doing that by emptying the div and then reloading the UDT. Unfortunately this does not seem to be working, the way I want it to, as the list does not get refreshed until and unless I refresh the page. Is there anyway I can make this work?
The quick/easiest option would be to assign it an id and to remove the entry via javascript.
Second, would be to have RemoveClient.php return it as part of the response from the AJAX.
var response = data.split('|');
$("#responseDiv").html(response[0]);
$("#clientlist").html(response[1]);
Third, I would strongly advise against this way but it is the question you ask, put the UDT alone on new page then load the page with the ?showtemplate=false parameter.
$("#clientlist").load("//www.mydomain.com/myudt.html?showtemplate=false");

Opening a new link using submit button not anchor tag

I need to be able to when the submit button is clicked a new tab must be open
based on the anchor link coming from the database. I have been struggling for hours.
this is my form
<form action="" method="POST">
<select name="name">
<option value="">Select Names</option>
<option value="1">Names</option>
</select>
<input type ="submit" name="submit" value="find random name">
</form>
Here is the php
<?php
$query="SELECT * FROM names_table ORDER BY RAND() LIMIT 1 ";
$result=mysqli_query($connection,$query);
if(!$result){echo "no results";}
while($selected=mysqli_fetch_assoc($result)){
$link=$selected['name'];
echo $ran_name= "Click here";
?>
// this code works but i dont want to be able to use Click here i want to be able to
generate the results once the submit button is clicked , the submit button must open the new tab.I think javascript must be used but i dont know how.
May be, something like this?
<?php
..
echo $ran_name= "<script> document.location.href='".$link."';</script>";
..
?>
More about location object http://www.w3schools.com/jsref/obj_location.asp.
Way 1
< input type="button" value="Open Window"
onclick="window.open('< ?php echo $link;?>')">
OR:
onclick="window.location.href='< ?php echo $link;?>','_blank'";
Way 2:
< form action="< ?php echo $link;?>" method="post" target="_blank">
...
< /form>
p/s: I don't know how to show code with format. (same you);
maybe you try this one? that's should do what you want
<?php
$query="SELECT * FROM names_table ORDER BY RAND() LIMIT 1 ";
$result=mysqli_query($connection,$query);
if(!$result) {
exit("no results");
}
while($selected=mysqli_fetch_assoc($result)){
$link=$selected['name'];
}
// Redirect to page
if (defined($link) && !empty($link))
header("Location: /$link");
?>

dropdown on change submit not executing php code

I have a form
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
the form has multipe input type text and 1 dropdown menu.
I also have a submit button called (submit1)
<input class="submit-button" type="submit" name="submit1" value="UPDATE MY INFORMATION" />
My PHP read like this :
if (isset($_POST['submit1']))
{ .... }
If I press the button, it works, no problem.
BUT I also want to submit the form from the dropdown menu change... so it can be executed by both the press of the button OR the change in dropdown... so I have the following for my dropdown
<select name="country" onchange="this.form.submit()">
when I select my dropdown, the page refreshed, but the code in my PHP is not executed... I figured it has to do with the name of $_POST['submit1']...
How can I change onchange="this.form.submit() for it to execute the code in if(isset($_POST['submit1']))...
Thank you
You should avoid inline javascript like that. It's ugly, and reduces readability. The easier way would be to give your elements IDs, like so:
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" id="myForm">
But if you don't want to, you can use QuerySelector and grab the name attribute of your input.
var x = document.querySelector("[name='country']");
x.addEventListener("change",function() {
this.parentNode.submit(); //get form parent and submit
});
I'm a bit confused why you're checking the submit button for a value as well, wouldn't you want:
if (isset($_POST['country'])) { ... }
Instead?
You could just document.getElementById('submit1').click() after setting the id on your submit button the same as its name. Of course, you would also do this onchange. I would separate my JavaScript from HTML, so it's cached into your Browser memory. Give your inputs, selects and the like the same id as their name, with the exception of radio buttons, and possibly checkboxes.
Let's start with some common.js:
//<![CDATA[
var doc = document, bod = doc.body;
var IE = parseFloat(navigator.appVersion.split('MSIE')[1]);
bod.className = 'js';
function gteIE(version, className){
if(IE >= version)bod.className = className;
}
function E(e){
return doc.getElementById(e);
}
//]]>
Now for your otherpage.php:
//<![CDATA[
var cntry = E('country'), sub1 = E('submit1');
cntry.onchange = function(){
sub1.click();
}
// note that the format E('submit1').click(); would also work
//]]>
Of course, you should have:
<script type='text/javascript' src='common.js'></script>
<script type='text/javascript' src='otherpage.js'></script>
</body>
</html>
Check for isset($_POST['country'])
And onchange add this to the drop-down,
onchange= 'document.getElementsByName("submit1")[0].click();'

form with 2 buttons need to call different functions based on value

I have a page which has lot of post data in the url.
For example,
www.test.com/test.php?userid='tester'&name=test&so on
The above page has a form that has something like this:
<?
$set=get_value_set;
if($set ==1) {
$set_value="SET";
} else {
$set_value="UNSET";
}
?>
<form name="test">
<input type="text" readonly="READONLY" value="<? echo $user_id; ?>">
<input type="submit" value="Email" name="submit_user">
<input type="submit" value="<? echo $set_value; ?>" name="submit_user">
<?
function setuser()
{
//sets the value
}
function email_user()
{
//sets the value
}
?>
there are two buttons above, when I click on email, i want the value of email button to be passed to the email_user function and do some proceesing there. Similar thing when I click on the set button.
NOTE:But in both cases above, I want the form to remain in the same page with the same post data in the url, but I also want the page to be refreshed so that the set button can have a value of Set or Unset depending on the database update.
Is this possible?
I would start to remove the submit action of each button and change them to
<input type="button" class="btn-Email" value="Email" name="submit_user" />
<input type="button" class="btn-Other" value="<? echo $set_value; ?>" name="submit_user" />
and then, using jQuery, you can easily process each click and submit the form
$(function() {
$(".btn-Email").click(function() {
// append anything you want
var but_email_value = $(this).val(), // or $(".btn-Email").val()
btn_other_value = $(".btn-Other").val();
$("form").submit();
});
$(".btn-Other").click(function() {
// append anything you want
var but_other_value = $(this).val(), // or $(".btn-Other").val();
btn_email_value = $(".btn-Email").val();
$("form").submit();
});
});
change your HTML
<form id="test" name="test">
...
<button onclick="email_user();">Email</button>
<button onclick="setuser();"><? echo $set_value; ?></button>
</form>
your functions should submit the form for you:
document.getElementById("test").submit();

Categories

Resources