I've been working this problem for awhile and seen a lot of different approaches. I have code that I believe should be working, but for one reason or another is not.
Here is my JavaScript code file name - test.js:
function deleteTempTable() {
$.ajax({
url: "exit.php",
success: function(data) {
alert("Deleting Temp Table");
}
});
}
I placed the alert purely for testing purposes to make sure the AJAX call was being made, and it is.
Here is the HTML for the button that makes the AJAX call file name - form.template:
<input type="button" title="Click to close window" value="Close"
onclick="deleteTempTable();" style="width:80px" name="close">
This does work as I get the JavaScript alert just fine.
Here is an EXAMPLE of the php code I'm using (it's not exact as it has some stuff I can't share, custom classes etc, either way I've reused this same pattern else where and it works fine and drops the tables as needed) file name - exit.php :
<?php
session_start();
require $_SERVER['DOCUMENT_ROOT'] . "path/to/file.php";
$tempTableName = $_SESSION['tempTableName'];
//Not really hard coding this it's just an example
$odbcConn = odbc_connect('DataBaseName', 'UserName', 'Password');
$sqlCmd = "DROP TABLE IF EXISTS $tempTableName;";
odbc_exec($odbcConn, $sqlCmd);
?>
When I click the button the JavaScript alert pops up, but it appears as the the php is ignored since the table still exists. Elsewhere in my code use the same php pattern to drop tables when new sets of data are requested, and they drop fine. Just not when I try to do it with this button.
Any ideas or pointers would be great!
Also I saw this question, "Calling PHP function using JQuery .ajax()", but his problem was syntax, and I'm pretty sure with my IDE I'm not having a syntax error, and from what I've seen this is the solution posted.
UPDATE
Thanks to some suggestions I was able to get a test that would confirm the php code itself works, but is not actually being executed by the AJAX call. Essentially I just ran the page that created the table, ie index.php, and then directed the browser to exit.php and the table was deleted as I would have expected. So the only conclusion is that exit.php is not actually being called/executed by the AJAX call.
I don't know if this could be the problem but here is my actual url assignment (more or less): url: "/folder1/folder2/folder3/folder4/exit.php" I had tried url: "exit.php" as well, so I don't know if I need the full root path to the file or not, or if this is some how the issue. At this point I'm just brain storming since I at least now know the php is not being executed or opened properly.
UPDATE
Well thanks to Salivador walking me through some trouble shooting the problem is solved. Basically the code is correct. So feel free to use it if you need to do something like this, however don't do what I did and mess up the PATH TO THE FILE!
face palm
Your ajax call is executed, but are you sure that your PHP code is executed correctly and as intended?
Try to output the $tempTableName to see do you actually getting the right name for your table, try to see the response of odbc_exec(...) command to see what is the result of deletion.
quick reaction is that the sqlcommand is including a semi-colon, remove that
heres an alternate method, do this in your php code
html
<input type="button" title="Click to close window" value="Close"
onclick="deleteTempTable('mytable');" style="width:80px" name="close">
exit.php
if($_REQUEST['command'] == 'droptable') {
echo dropTable($_REQUEST['tablename'] ));
}
...
function dropTable($tableName){
/*your sql stuff/code here*/
$sqlCmd = 'Drop Table '.$tablename;
$rz = odbc_exec($odbcConn, $sqlCmd);
if (!$rz){
$result = true;
} else {
$result = false;
}
return $result;
}
then you could do this
function deleteTempTable(tablename) {
var params = 'command=droptable&tablename='+tablename;
$.ajax({
url: "exit.php?"+params,
success: function(data) {
if(data == true) {
alert("Deleting Temp Table");
} else {
alert("Didnt work");
}
}
});
}
Just one way of doing it , i personally wouldnt use an onclick to fire the function, i prefer selector bound events
why are you storing this table name in session data? wouldnt a form var work out better?
Related
I've been researching this for awhile and there are a lot of similar questions that have been asked. I tried researching as much as I could and came up with a code that should work in theory... but for whatever reason, it just doesn't. I can't seem to figure it out!
I am using JQuery/AJax to call a php file and update SQL records. Here is the general gist of the code. Whats left out is essentially a button click action which calls the ajax function. The Php is going to (eventually) add the StoreID value to an array, serialize it and add it into mysql.
Each piece of the code works on their own, but when put together it just doesn't work!
Java Script Code:
jQuery.ajax({
type: 'POST',
url: 'storeid.php',
data: {StoreID: IDjs[x] },
success: function(reponse) {
$('#error').html('Success! SkipID: ' + IDjs[x]);
onStateNext(); },
error : function(code, message){
$('#error').html('Error Code: ' + JSON.stringify(code) + ', Error Message: ' + JSON.stringify(message));}
});
The weird thing about this code, is that the "Success" functions get output. The success callback is displayed and the proceeding script is run.. despite the fact that it doesn't appear to actually send the StoreID variable to the php file.
The PHP Code (storeid.php):
$test=$_POST['StoreID'];
if (isset($test))
{
global $conn2;
$memberid = $_SESSION['memberID'];
$testarray = array(7,8,$test);
$serialized_data = serialize($testarray);
$insertsql = "UPDATE StoreIDs SET IDs = '$serialized_data' WHERE MemberID = $memberid";
if (mysqli_query($conn2, $insertsql))
{
echo "Updated with StoreID: " . $test;
} else {
echo "Error updating record: " . mysqli_error($conn2);
}
} else {echo "no isset value"; }
This code also works when run without the ajax. It'll properly update the record when called directly by php but not when called by the ajax script above.
Any ideas of what I could have done wrong?
Figured out thanks to #JayBlanchard. You can use the firefox developer tools to see server responses, which allowed to see the error messages and realize that it was communicating but simply not getting the credentials from the database.
Turns out you can't use global variables if the database file isn't included. I thought it didn't need it, since it works fine when running server side, but since ajax is run client side after the server has closed the connections for the database, it needs to be opened again!
I have the following code from my jQuery script that makes some changes to a div fnbtn, when the Esc key is pressed:
$(document).keypress(function(e){
if(e.keyCode==27) {
if(window.discon==0)
{
window.discon = 1;
$("#fnbtn").replaceWith("<div id=\"fnbtn\"><p id=\"fnbtnp\">The variable is one...<br>Blah blah...<\/p><\/div>");
}
else if(window.discon==1)
{
window.discon=2;
$.post(
'do.php',
{doit: 4, uid: window.uid},
function(rcvd) {
$("#fnbtn").replaceWith("<div id=\"fnbtn\"><p id=\"fnbtnp\">The variable is two...<br>Blah blah...<\/p><\/div>");
$("#disp").append("<p><span id=\"cmnt2\">"+rcvd+"</span></p>");
});
//alert("Alert something here");
}
}
});
disp is another div to which the data received from the $.post request is appended. The do.php file contains some mysql queries and the following statement :
echo "This is the data returned from the do.php file";
Here's my problem. When I put this script in my php file, the div fnbtn changes successfully on pressing Esc the first time. But when Esc is pressed a second time, the div fnbtn fails to change. I think this has something to do with the $.post() request.
But when I include the alert() statement (which is currently commented out), everything works out just fine, and I can see the changes made, before I press the OK button on the alert box.
What is the cause of this problem? Is it caused because the $.post() request completes before the $("#fnbtn").replaceWith() and $("#disp").append() statements are executed? and how does including the alert() make a difference?
Your help is appreciated. Thanks in advance. :-)
If you set window.discon = 2 doesn't that mean that if(window.discon == 0) and if(window.discon == 1) will return false and won't run a second time?
I have tried your code and for me it works fine up to the part mentioned above. Adding the alert() doesn't seem to make any difference, although it does run before $.post() is completed.
Disregard what I said there, it seems I didn't quite understood what exactly you were referring too.
After playing with the code a little I didn't find anything wrong with it so it may be because of a different script that you have.
For me it works with and without the alert()
You can try and play a little with the code and also add a .fail function
$.post('do.php', {doit: 4, uid: window.uid}, function(rcvd) {
$rcvd = rcvd;
}).done(function(){
$("#fnbtn").replaceWith("<div id=\"fnbtn\"><p id=\"fnbtnp\">The variable is two...<br>Blah blah...<\/p><\/div>");
$("#disp").append("<p><span id=\"cmnt2\">" + $rcvd + "</span></p>");
}).fail(function(){
alert('Could not reach do.php');
});
The only difference with the alert() is that the page is being stopped from being executed any further until the user clicks ok. That makes me think that there may be some other script that is colliding with this one.
Ok guys I know this question has been asked before but I am very new to PHP and JavaScript and hadn't even heard of ajax until i started looking for an answer to this question so do not understand previous answers.
I am creating a site that essentially is a bunch of videos in a SQL database, it shows one video at a time, I would like to have a next and previous video buttons.
However I cant get past this ajax thing so my question is even simpler. I have looked at this question/answer and think it pretty much sums up what im asking:
How do I run PHP code when a user clicks on a link?
I have copied that exact code,
<script type="text/javascript">
function doSomething() {
$.get("backend.php");
return false;
}
</script>
Click Me!
And in my backend.php file i have literally just got <?php echo "Hello" ?> just to test it and therefore my understanding is that when i click the link the javascript onClick event is trigged which in turn calls the backend.php file, which says to print "Hello" to the page. However when i click the link it does nothing.
Eventually obviously im going to need to get a lot more complex with my php functions and calling variables and all that stuff but i like to figure things out for myself for the most part so i learn. However im stuck on this bit. Also whilst im here i will ask another thing, I want to 'give back' to the users of the site for answering my questions but I can only really well enough in HTML and CSS to answer other peoples questions, any advice on being able to find the simpler questions on here so i can answer some.
Thanks in advance :)
It does nothing becuase you don't do anything with the result. My guess is that in the example you took, it does some work and doesn't show anything to the user. So if you just had some stuff you wanted to run on the server without returning any output to the user, you could simply do that, and it would work.
Example from jQuery's .get() documentation
What you do:
Example: Request the test.php page, but ignore the return results.
$.get("test.php");
What you want to do:
Example: Alert out the results from requesting test.php (HTML or XML, depending on what was returned).
$.get("test.php", function(data){
alert("Data Loaded: " + data);
});
Take a look at the .get() documentation. You're using it incorrectly.
You should be passing data (optional) and handling the data that gets returned, at a minimum:
$.get("backend.php",
{
// data passed to backend.php goes here in
//
// name: value
//
// format. OR you can leave it blank.
}, function(data) {
// data is the return value of backend.php
// process data here
}
);
If you pass data, you can retrieve it on backend.php using $_GET. In this case:
$_GET['name'];
$.get("test.php", { name: "John", time: "2pm" }, function(data) {
alert("Data Loaded: " + data);
});
http://api.jquery.com/jQuery.get/
This would alert the data. right now that function only returns false.
$.get('backend.php', function(data) {
alert(data);
});
Your code will not print to the page the way you have it set up; you're part of the way there, in that you have called the page, but the response needs to be handled somehow. If you open up the developer tools in Chrome, you can click on the Network tab and see the request and response to verify that what you coded is actually working, but now you need to put the response somewhere.
By passing a function as the second variable into $.get, you can make your request show up on the page. Try something like this:
$.get("backend.php", function (data) { $('body').append(data); } );
Your code is not handling with that data. So instead, you should use following code :
$.get("backend.php", function(response) {
alert(response);
})
Or, to show that data on UI, assign it to any html element.
For more understanding , please visit :jQuery.get() link
Is there any way I could get the value of a html text field without using GET or POST or REQUEST? Alternatively, is there any way to get the field value in the same form or page else where.
This works with direct value such as "james", "system" and so on. the only problem is how do i make it work with html field values
Like:
<input type = "submit" onclick = "
<?php $username = "kut";
$result = checkname($username);
if($result)
{
?> alert("success"); <?php
}
else {?> alert("failed"); <?php
}?>
">
How can i replace "kut" with the value of a text field with id = "username" ?
<?php $username = "?>document.getElementById('username').value;<?php"?>
or something like that...???
In short, I need to get the value of a html field else where in the same page inside a javascript function, using PHP... like in the above javascriptFunction(), function
You have fundamental misunderstanding of how client-server architecture works.
PHP can be executed thousands of miles away, even days apart, from place where and when JavaScript does.
First PHP generates whole page, all of HTML, all of JavaScript source code (unexecuted), and then, after PHP is done and gone, browser starts running JavaScript.
These two can't be mixed together like you wanted, even though it may seem so in the PHP source code.
Although you can communicate with the server again using AJAX or similar, you probably should first understand how client-server architecture works and try to solve the problem without AJAX (e.g. handle all of it on server side, or all on client side).
You can not directly call a PHP function in JavaScript. You could set a JavaScript value from php before the page loads via echo. PHP is executed on the server while JavaScript is executed on the client side.
1> I suggest using jQuery to handle the Ajax part.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function check_user(){
var user_el=document.getElementById('username');
if(!user_el){ return false; }
var username=user_el.value; // this could all be replaced with $('username').val()
$.getJSON('check_var.php',{"user":username},function(data){
if(data.result=='error'){ alert('something was wrong with the PHP stuff'); }
alert(data.userstatus);
});
}
</script>
2> On the PHP side, as check_var.php, you need a script that takes the username input, checks the DB, and sends back the result as JSON data.
<?php
if(!isset($_GET['user']){ exit; }
$username=preg_replace('#['^\w\d]#','',$_POST['user']);
//do your database query. I assume you have that part all set.
//since I'm not filling in all of that, you'll need to fix this next part to work with your system
//let's pretend it's like $found=check_user($username);
//be sure to use mysql_real_escape_string or prepared statements on the $username var since you're working with user input
$status=$some_db_error ? 'error' : 'success';
$results=array('result'=>$status,'userstatus'=>$found);
header('Content-Type: application/json');
echo json_encode($results);
i want to have function like delete file from database by using link instead of button. how can i do that? do i need to use href/unlink or what?
Can i do like popup confirmation wther yes or no. i know how to do that, but where should i put the code?
this is the part how where system will display all filename and do direct upload. Beside each files, there will be a function for 'Remove':
$qry = "SELECT * FROM table1 a, table2 b
WHERE b.id = '".$rs[id]."' AND a.ptkid = '".$rs[id]."' ";
$sql = get_records_sql($qry);
foreach($sql as $rs){ ?>
<?echo ''. basename($rs->faillampiran).'';
?><td><?echo ' [Remove]';?></td><?
?><br>
<? }
?>
thankz all
The elegant way of doing this would be to use both PHP and JavaScript. PHP is a server-side language, and should probably be removed as much as possible from the client side stuff. One great way to do it would be to essentially create yourself an API.
The API would be a PHP script that deletes a row. It takes a variable in via GET and returns a boolean that says "yes we deleted the row" or "something went wrong." I like to use JSON, which in JavaScript is easier to work with than XML, and jQuery's getJSON function, a package that makes it really easy to get going.
In the .php file (we call it api.php later), if your results are successful return out success boolean. We use PHP's json_encode on an array, and echo out the result:
$variable = someFunctonToSanitize($_REQUEST['idToDelete']);
$query_to_run = "delete query using $variable";
$result = mysql_query($query_to_run);
// set headers
header('Content-type: text/json');
header('Content-type: application/json');
// if the query was successful, echo true
if($result) {
echo json_encode(array("success"=>"true"));
} else { // else echo false
echo json_encode(array("success"=>"false"));
}
In your JavaScript, here using jQuery (this is discouraged, see comments below):
$('#deleteLink').click(function(event) {
// prevent link from actually going anywhere
event.preventDefault();
// Fire off API request
$.getJSON("api.php?idToDelete=whatever", function(data){
if(data.success) {
alert("Item was deleted.");
} else {
alert("There was an error");
}
});
});
With a .post() request, per #Col. Shrapnel and #josh3736's comments (note: also changed $_GET to $_REQUEST to work with both):
$.post("api.php", { "idToDelete": "whatever" },
function(data){
if(data.success) {
alert("Item was deleted.");
} else {
alert("There was an error");
}
}, "json");
In your HTML:
Delete!
No links nor buttons can be used for the database interaction. It is server-side code to do such things. You have to understand that your application has 3 layers:
an HTML form
an server-side code
a database
the first one cannot interact with the last one directly.
So, on the one hand, it doesn't matter, with link or button you do call your server side code (the code remains the same).
But, on the other hand, there is a rule:
use GET method (link) to request information and POST (form/button) to modify it.
So, you should not use links to remove files, because some too smart bot can wipe all your database in a second.
As for your question where to place the code, just write a php script, unlink.php which deletes a file by hardcoded path. Then, after you've done that, make this file an action for the HTML form. Hardcoded one. Once you've done that - you can try to generate this form from your database.
This - step-by-step way - is the only possible way to develop a wab-application
Make a link:
Delete
Then make a delete.php that handles deleting and make sure you check that the session is authorised.
In PHP you use unlink() to delete a file. If you provide a page which accepts the file name (or better yet, file Id) as a parameter you can call unlink() on the file. Obviously there are some serious security implications which you will need to account for.
For confirm Delete, use this in onclick function()
In a href tag, itself :
<a href="" onclick="return ConfirmDelete();" ></a>
In upper Page use javascript like this,
function ConfirmDelete() {
var confm = window.confirm("Are you sure want to delete this !");
if(confm == true) {
return true;
} else {
return false;
}
}
For delete option give the same page link and pass the parameter and get the parameter by get function
<a href='samepagename?deleteid='.<?php echo $id;?>
In get parameter use like this,
$deleteid = $_GET["deleteid"];