jQuery statements inside $.post() not working properly - php

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.

Related

ajax data passing to php not working

Okay so, I've scoured stackoverflow for this answer and have come across several threads talking about how to do this, and well, they just haven't helped me yet.
This is all on one page, so that's probably the big problem. I really don't wanna send the post data to some other page and then redirect back to the one in order to get this to work, but I will if you guys cannot assist me in this endeavor.
Anyway, I have this page and I'm trying to pass data to the php via ajax, and I know that php is a server-side language, so the page would have to be reloaded once the data is passed.
php:
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
}
jquery:
var whateva = "hello";
$.post('index.php', {'location': whateva}, function(){
//alert(data);
//window.location.reload(true);
});
alert(data); does get it to work and echo out given the isset (and also prints out all of the other html), but that is an alert which isn't practical, especially from a user standpoint. But that means that this ajax function is working. The problem here is that I want the same page to load, just with the $_POST['location'] variable set, so I had the bright idea of just reloading the page as the function in this case, which doesn't work. The isset never succeeds
Any help will be appreciated, besides telling me that combining php and javascript is a horrible idea as I already know that
Edit:
I was told to try making another page to post the data back which still didn't work, here's the code for that (with the main page ajax adjusted to direct it there instead):
window.onload = function(){
var inter = <?php echo json_encode($_POST['location']); ?>;
$.post('index.php', {location: inter});
}
I have tried it with and without quotes around location in the .post. Also I have tried to just have the plain javascript there, without the onload, still nothing. The response on the main page when changed to this
$.post('intermediary.php', {location: whateva}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
it prints out the html of the hidden page, with the variable filled in (var inter = "hello" instead of having the php there, as it should), so the passing to that page works
Ok, here's the breakdown.
File one: index.html
This file is HTML and Javascript only, and is the page seen by the user. This could be a php page, but it does not need to be. Notice the quotes around the string 'whateva'.
<html><head></head><body>
<script>
$.post('intermediary.php', {location: 'whateva'}, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
</script>
</body></html>
File two: intermediary.php
This file is PHP only. It receives data silently through POST and returns data by echoing it.
<?php
if (isset($_POST['location'])) {
echo $_POST['location'];
echo "hey";
} else {
echo 'No data received!';
}
?>
Oh.... It's a simple mistake. your ajax syntax is wrong... Remove the quotes of ajax parameter inside the curly brackets. Just like
var whateva = "hello";
$.post('index.php', {location: whateva}, function(){
//alert(data);
//window.location.reload(true);
});
It will working fine.... But you might use variable to ajax paramete then, you should use variable name for ajax location parameter value. But you might use string for location parameter value, then you should use it value inside the quotes like this, $.post('yourfile.php',{location:'your_name'},function(){});. But you might use some value of location parameter use should type this code.$.post('yourfile.php',{location:30},function(){});

Execute php from javascript

I'm having some trouble getting some php code working in my app.
The setup is rather easy: 1 button, 1 function and 1 php file.
script.js
$(document).ready(function ()
{
$("#btnTestConnectie").click(testConnectie);
});
function testConnectie()
{
$.get("script/SQL/testConnection.php");
}
testConnection.php
<?php
echo "It works!";
php?>
According to this post, it should work (How do I run PHP code when a user clicks on a link?)
Some sources claim that it is impossible to execute php via javascript, so I don't know what to believe.
If I'm wrong, can somebody point me to a method that does work (to connect from a javascript/jQuery script to a mySQL database)?
Thanks!
$.get('script/SQL/testConnection.php', function(data) {
alert(data)
});
You need to process Ajax result
You need to do something with the response that your php script is echoing out.
$.get("script/SQL/testConnection.php", function(data){
alert(data);
});
If you are using chrome of firefox you can bring up the console, enable xhr request logging and view the raw headers and responses.
Javascript is run by the browser (client) and php is run on the remote server so you cannot just run php code from js. However, you can call server to run it for you and give the result back without reloading of the page. Such approach is called AJAX - read about it for a while.
I see you are using jQuery - it has pretty nice API for such calls. It is documented: here
In your case the js should be rather like:
$(document).ready(function ()
{
$("#btnTestConnectie").click($.ajax({
url: '/testConnection.php',
success: function(data) {
//do something
}
}));
});
[EDIT]
Let's say you have simple script on the server that serves data from database based on id given in GET (like www.example.com/userInfo.php?id=1). In the easiest approach server will run userInfo.php script and pass superglobal array $_GET with key id ($_GET['id']=1 to be exact). In a normal call you would prepare some query, render some html and echo it so that the browser could display a new page.
In AJAX call it's pretty much the same: server gets some call, runs a script and return it's result. All the difference is that the browser does not reload page but pass this response to the javascript function and let you do whatever you want with it. Usually you'll probably send only a data encoded (I prefer JSON) and render some proper html on the client side.
You may have a look on the load() of jQuery http://api.jquery.com/load/
You should place all of your functions in the document ready handler:
$(document).ready(function(){
function testConnectie() {
$.get("script/SQL/testConnection.php");
}
$("#btnTestConnectie").click(function(e) {
e.preventDefault();
testConnectie();
});
});
You will have to have your browser's console open to see the result as a response from the server. Please make sure that you change the closing PHP bracket to ?> in testConnection.php.
One other note, if you're testing AJAX functions you must test them on a webserver. Otherwise you may not get any result or the results may not be what you expect.

PHP function on close with jQuery AJAX

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?

Calling a php function using ajax/javascript

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

I am receiving output if i "ALERT" some text else i didn't receive any o/p while using ajax with javascript and jquery

I am receiving a different type of error in my application.
In my project most of the functionality are in ajax. Now my prob is if i "ALERT" something i am receiving the output. Else i am not. I am totally confused with this issue and don't have any idea to solve it.
What will be the solution?
Any answers will be helpful and grateful..
thanks in advance
Thr A in AJAX is shorthand for "asynchronous", which means the call does not follow the ordinary time flow.
I mean, say you have this code
alert(1);
some_function();
alert(2);
In javascript, you expect the system alert 1, then run some_function() and wait it to return something and only after it finishes, you see alert 2.
But if some_function() is ajax, you get alert 1, then alert 2, and you can get the result of some_function() in between those two alerts as well as after the second alert, because the ajax call works asynchrously, js wont wait for its response.
With that in mind, lets return to your problem.
You say, you dont get a result unless you alert something. If you alert something, javascript stops until the user clicks "ok", but ajax wont. So this will create a time delay, and during this time delay, ajax probably finishes running and returns result.
Your mistake is, i'm just guessing since you did dont provide any code, you run two ajax calls succesively and the latter one depends on the former one.
var x = some_ajax_function();
var y = some_other_function(x);
this wont work (probably), because second function is called before the value of x is assigned. But if you put an alert in between, you get the result, because the ajax call returns a result and assigns x in the time delay.
So, what you need is, you can redesign your logic, or you can call the second function in the success phase of the first ajax call.
Something like
function some_ajax_function()
{
....
//ajax success state
var x = ajax_result;
some_other_function(x);
}
I hope this helps

Categories