jQuery .ajax call with javascript onclick event not working - php

I have this piece of code and it works fine while isolated into the 2 small scripts I have below. Basically I push a button which makes a call to the database to delete a row.
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"></script>
<script>
function removeNo(){
$.ajax({url: "removeno.php",
type: "post",
});
};
</script>
</head>
<body>
<input class='mybutton' type='submit' onclick='removeNo()' value='Remove' />
</body>
</html>
removeno.php
<?php
include 'config.php';
$sql = "DELETE FROM comments WHERE id='24453305255'";
$query = mysql_query($sql);
?>
Now when I take the HTML button part and put it into a larger PHP script it does not work. The entry that I would like to delete is still in the database. I'm still calling the same PHP file 'removeno.php'. The Javascript is in the header just the same as it is above. All files are in the same directory, and I've made sure to include the 'config.php' connection file in the PHP script.
I've not posted my full PHP scripts as it's several hundred lines, however the whole page evaluates to this piece, and evaluates through the "if" maze I have below. It even displays the button as it should with the value of "remove". It would display "submit" if it didnt evaluate correctly. Am I calling this function correctly within this PHP script?
echo "<td>"; //Main Button
if($isleadership == 2) {
if($reviewed == "Yes") {
echo "<input class='mybutton' type='submit' onclick='removeNo()' value='Remove' />";
} else if ($reviewed == "No") {
echo "<input class='mybutton' type='submit' name='".$a."' value='Submit' />";
}
}

Related

PHP - onClick doesn't seem to be working

I have series of dropdown boxes which can be selected by the user. I then want to have two different submit buttons that will do two different actions with the selected data. I am trying to code the submit button to run the selected php, but when I click the button does nothing. Any help is appreciated, my code is below. AFAIK the only relevant bits are my formSubmit function and the input tag near the bottom of the code.
edit: I have edited out a bulk of the code and left the pieces that I think are relevant. Please let me know if more info is needed.
<!DOCTYPE html>
<?php
require 'config.php'; // Database connection
//////// End of connecting to database ////////
?>
<html>
<head>
<SCRIPT language="JavaScript">
//Scripts
function submitForm(action)
{
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}
</script>
</head>
<body>
<div>
<?Php
//Beginning of Form
echo "<form method=post name='f1' action =''>";
//Dropdown boxes are here
//This line is what is not working:
echo "<input type='submit' value='Careers' onclick=\"submitForm('rt.php')\">";
echo "</form>";
?>
</div>
</body>
</html>
Not quite sure what is wrong with the function, xe4me may have the correct answer. However, I just changed my onClick to this and it worked:
onClick=\"document.f1.action='rt.php'; document.f1.submit(); return true;\"
You're using document.getElementById('f1') in submitForm function
function submitForm(action)
{
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}
But your form doesn't have id attribute because of this line of code
echo "<form method=post name='f1' action =''>";
so the form won't be submitted when you click the Careers button. You need to add id='f1' attribute to the form by changing the above line of code to below
echo "<form id='f1' method='post' name='f1' action =''>";
Try the jQuery method :
http://api.jquery.com/jquery.post/
with
How to get ID of clicked element with jQuery
Whenever any button is clicked, find its id and based on that, use $.post to post data to the location you want.
you must add a class to your button and call the onclick based on that class name :
<?Php
....
echo "<input type='submit' class='submitter' data-action='rt.php' value='Careers' >";
echo "</form>";
?>
// In Javascript :
document.getElementByClassName('submitter').onclick = function(){
var action = this.data('action');
document.getElementById('f1').action = action;
document.getElementById('f1').submit();
}

Change Page Content via jQuery after Uploading File - PHP

I don't know if something like this has already been asked and answered, but since no matter what search query I make, nothing seems to be close to what I am looking to do. I am working on a project where the user will upload a file. Once the file has been uploaded it will show the user a success message as well as some file info. I am trying to keep this all within one page, if possible, but can't seem to get it to work. File gets uploaded, but the info does not show.
Here is something like what I am working with:
<?php
if(isset($_POST['uploadFile']) && isset($_FILES['file'])) {
move_uploaded_file($_FILES['file']['tmp_name'], "files/" . $_FILES['file']['name']);
$message = "\"" . $_FILES['file']['name'] . "\" uploaded successfully...";
}
?>
<html>
<head>
<title>Upload File</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function() {
$(".uploaded-file-info").hide();
$(".uploadForm").submit(function() {
$(".upload-form").hide();
$(".uploaded-file-info").show();
});
});
</script>
</head>
<body>
<div class="upload-form">
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>" enctype="multipart/form-data" class="uploadForm" >
<input type="file" name="file" /><br />
<input type="submit" name="uploadFile" value="Upload File" />
</form>
</div>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
</body>
</html>
Like I said, the file gets uploaded, but the form doesn't hide and the file info ($message) doesn't show. Any suggestions?
The problem is the JQuery part :
$(".uploadForm").submit(function() {
$(".upload-form").show();
$(".uploaded-file-info").show();
});
coupled with this line :
<form method="post"
The JQuery part is saying : As soon as the form on the page is submitted, Show the information DIV.
The "Form" part just say : Submit the form.
So, when you click the button, the form is submitted and at the same time, the JQuery is executed. But then the form that you just posted needs to "refresh" the page to get the response back from the server. Basically, the JQuery you wrote display your div while you submit it. Meaning that it will work for a fraction of a second but will display an empty div because the response of the server is not there yet.
What you probably want to do is something like :
When the page loads
And there is content in the uploaded-file-info
Show the info and hide the form.
Add a Style tag with the following :
<style>
.uploaded-file-info {
display: none;
}
</style>
It will always hide the uploaded-file-info when the page loads.
Then, change your JavaScript code with :
<script>
$(document).ready(function() {
if ($('.uploaded-file-info > p').html() != "") {
$(".uploaded-file-info").show();
}
});
</script>
It says that when the page loads, if something is present inside the children of the element "uploaded-file-info", then show it. Otherwise, do nothing.
An easier solution would be to display the block, with php (so on the server side), only if a file was uploaded. No need for JQuery (client side) code.
Remove all the JQuery code and code within "<style>" tags and replace surround your "div class="uploaded-file-info" with an IF like this :
<?php if ($message != '') { ?>
<div class="uploaded-file-info">
<p><?php echo $message; ?></p>
</div>
<?php } ?>
Here's what will happen then:
you post (from your browser) the form
the server receives your post
if there is a file uploaded, it will initiate your "message" variable
and if the message variable exists, the server will put the "div uploaded-file-info" into the response. If not, everything surrounded by the "if" won't be put into the response.
your browser will receive the response and display it on screen.

PHP Page load/refresh to exact position

What I'm trying to do is to pass a user to a php script via a href link, then have them passed back to exactly the same position that they were at before they clicked the link, like the page hasn't been refreshed. Does anyone know if or how this could be possible possible? Thank you.
Using HTML you can have the following
<p id='open_here'><a href='script.php'> Send to script </a> </p>
And then you can link back to that exact position with
Send Back to page
So essentially, instead of using a regular link as in the previuos code snippet, you could redirect back to the page using
//php redirect
<?php header('Location: mypage.html#open_here'); ?>
//Javascript redirect
<script type='text/javascript'>
window.location = "mypage.html#open_here";
</script>
If you don't mind adding some Javascript to make it work, here is a solution that will make it possible to redirect back to the exact same scrollbar position as when the user clicked the link.
index.php (the file where the link is)
<script>
window.addEventListener('load', function() {
// Do we have a #scroll in the URL hash?
if(window.location.hash && /#scroll/.test(window.location.hash)) {
// Scroll to the #scroll value
window.scrollTo(0, window.location.hash.replace('#scroll=', ''));
}
// Get all <a> elements with data-remember-position attribute
var links = document.querySelectorAll('a[data-remember-position]');
if(links.length) {
// Loop through the found links
for(var i = 0; i < links.length; i++) {
// Listen for clicks
links[i].addEventListener('click', function(e) {
// Prevent normal redirection
e.preventDefault();
// Redirect manually but put the current scroll value at the end
window.location = this.href + '?scroll=' + window.scrollY;
});
}
}
});
</script>
page.php (the PHP script that redirects back)
<?php
// Get the provided scroll position if it exists, otherwise put 0
$scrollPos = (array_key_exists('scroll', $_GET)) ? $_GET['scroll'] : 0;
// Redirect back to index.php and provide the scroll position as a hash value
header('Location: index.php#scroll='.$scrollPos);
Hope it helps! :)
I am just spilling ideas here, but I would use javascript to intercept user's click on the href, and .preventDefault first. Then figure out where the user is on the page. Maybe by splitting the page into sections, indentified by IDs. Your html markup would be something like
<div id="section-1"></div>
<div id="section-2"></div>
<div id="section-3"></div>
so when javascript prevents the link from executing, it would figure out in which section the user currently is. Let's say we know each section's height. Then we need to find out the scrollbar position. I haven't done that, but have a look here
http://api.jquery.com/scrollTop/
Once we know the height of each section and once we can detect where the scroll bar is, we can determine in which section the user is residing. Then, we fetch the url of the href link and add a query string to it like, http://something.com/script.php?section=2 and redirect user to it with whatever data you want . Then once the script has done it's job append the query string to the redirect-uri and redirect the user back with something like http://something.com#section-2 and the user will immediatly pop to section-2
I know this isn't a very specific answer, but hopefully I've given you some leads and ideas how to accomplish this. Let me know how it works!
I'd had to remember the scroll position for a <select>. Example below. Three
submit buttons to illustrate why there's three getElementById. To see
it work you must move the scroll bar first
<?php
$scrollusObscura=$_GET["imgbtn"];
$header = <<<EOD
<!DOCTYPE html>
<html>
<head>
<title>snk_db</title>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" >
<head>
<script>
function gety(){
var y=document.getElementById('myUlID').scrollTop;
document.getElementById('imgbtn1').value=y;
document.getElementById('imgbtn2').value=y;
document.getElementById('imgbtn3').value=y;
}
function itemRelevatur(scrollum){
document.getElementById('myUlID').scrollTo(0, scrollum);
}
</script>
</head>
<body onload="itemRelevatur({$scrollusObscura})" >
EOD;
$html= <<<EOD
<div >
<select size="6" id="myUlID" name="myUlName" onscroll="myTimer = setInterval(gety, 300)">
<option>'1'</option>
<option>'2'</option>
<option>'3'</option>
<option>'4'</option>
<option>'5'</option>
<option>'6'</option>
<option>'7'</option>
<option>'8'</option>
<option>'9'</option>
<option>'10'</option>
<option>'11'</option>
<option>'12'</option>
<option>'13'</option>
<option>'14'</option>
<option>'15'</option>
<option>'16'</option>
<option>'17'</option>
<option>'18'</option>
<option>'19'</option>
</select>
</div>
EOD;
$html1= <<<EOD
<div><form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn1' value=''></input>
<input type='submit' value='Submit' ></input>
</form>
EOD;
$html2= <<<EOD
<form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn2' value=''></input>
<input type='submit' value='Submit' ></input>
</form>
EOD;
$html3= <<<EOD
<form method='GET' action'myscript.php'>
<input type='hidden' name='imgbtn' id='imgbtn3' value=''></input>
<input type='submit' value='Submit' ></input>
</form></div>
EOD;
echo $header;
echo $html;
echo $html1;
echo $html2;
echo $html3."</body></html>";
I had major problems with cookie javascript libraries, most cookie libraries could not load fast enough before i needed to scroll in the onload event. so I went for the modern html5 browser way of handling this. it stores the last scroll position in the client web browser itself, and then on reload of the page reads the setting from the browser back to the last scroll position.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
if (localStorage.getItem("my_app_name_here-quote-scroll") != null) {
$(window).scrollTop(localStorage.getItem("my_app_name_here-quote-scroll"));
}
$(window).on("scroll", function() {
localStorage.setItem("my_app_name_here-quote-scroll", $(window).scrollTop());
});
});
</script>

How can I integrate javascript onclick function with 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>

How to pass a variable with in jquery

I just started using jQuery in the past few days. I love how it makes functions simple. However because I am very new to using Javascript, I keep hitting a road block with one function.
I am trying to bind a couple functions together, but I'm not sure if I am doing it in the right order. What I want it to do is get a variable from a selector href='#from=xxxxx&to=xxxxx', with the xxxxx being a value printed out from a DB using PHP.
Then create a DOM window to display a form and insert those values into the hidden input fields. I have been stuck trying to figure out a way to pass those variables from the link to the form.
Here is my script:
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://swip.codylindley.com/jquery.DOMWindow.js"></script>
</head>
<body>
<div id="msgBox" style="display:none"></div>
<?php $from="0"; $to="0";
for ($x=1; $x<=4; $x++){ $from++; $to++; ?>
user<?php echo $x;?><br>
<?php } ?>
<script type="text/javascript">
$("#msgBox").append("<form id='myForm' method='post' action='index.php'><div style='border:1px solid #cc0; width:300px;'><input type='hidden' value='<?php echo $from;?>'><input type='hidden' value='<?php echo $to;?>'>subject:<input type='text' name='subject'><br>message:<textarea class='mbox' name='msg'></textarea><br><input type='submit' value='submit'></div></form>");
$('.foo').click(function(){
$.openDOMWindow({
windowSourceID:'#msgBox',
height:135,
width:300,
overlay:0,
positionType:'anchoredSingleWindow',
windowBGColor:'#f9f5f5',
anchoredSelector:'.foo',
positionLeft:200,
positionTop:150
});
$("#msgBox").trigger();
return false;
});
</script></body></html>
In the handler for the click event on each link you can get a reference to the target link and extract the values from the href attribute and then set the values of the hidden fields in the form.
$('.foo').click(function() {
var href = $(this).attr('href'); // will contain the string "#from=0&to=0"
var from,to = ... // extarct from string by splitting by & or using url parse library
$('#msgBox').find("input[name='from']").val(from);
$('#msgBox').find("input[name='to']").val(to);
// rest of code...
});

Categories