jquery, ajax returning weird data? - php

i've been doing a lot of ajax scripts and every time something seems to be different.
in this case i have a form that i want to post
<form id="sss">
<input id="qqq"/>
<input type="submit" id="s" href="Search!"/>
</form>
<div id="rrr"></div>
and
$('#s').click(function(){
$.ajax({
url: 'foo.php',
data: {
query: $('#q').val()
},
success: function(data) {
$('#rrr').html(data);
}
});
return false;
});
and
if(isset($_REQUEST['query'])){
print_r($_REQUEST['query']);
}
what happens is that in <div id="rrr"></div> gets loaded the print_r($_REQUEST['query']); and all the rest of the html page.
i only want to return $_REQUEST['query']
weird!?
any ideas? What this success: function(data){} actually means?
Thanks

If you are requesting the same page that you are current displaying, then your if statement doesn't stop processing, so the rest of the page is returned as well. You either need to die() afterward, or (recommended) create a separate page entirely dedicated to handling AJAX requests. Here's an example of how to properly stop processing:
if (isset($_REQUEST['query'])) {
print_r($_REQUEST['query']);
die(); // stop processing.
}
In regards to your second point, I think you might be misunderstanding the technical details of what's actually happening here:
Client requests foo.php from server. Server executes foo.php according to the logic in the page, and sends response output to browser. Browser renders the page.
Client sends AJAX request (which is nothing more than a request that happens asynchronously, i.e., separately from the browser loading a page) to foo.php?query=...
Server executes foo.php?query=... (just like it did in step (1)!), which causes the first if to trigger before returning the rest of the html in response, so the same page is returned except with the query output at the top (Try going directly to foo.php?query=... in your browser and I think you'll see what I mean).
However, instead of the response being rendered in the browser, since it was an AJAX request, the response is captured into a variable, data.
The callback function success(data) is executed, passing the exact output returned from the server as-is from the AJAX request (i.e., the variable contains the same as viewing the source of foo.php?query=... in your browser), which is then processed according to your logic. In this case, you are dumping the contents into a div, so you see the output correctly.
Please take a moment to install and run Fiddler, so you can see the exact data that is flowing back and forth as you load the page in your browser, and then watch what happens as you make an AJAX call. Perhaps it will make the data flow and results you are getting much clearer.
Hope this helps!

Related

PHP: Page 404 Not Found on Ajax Request

So, I'm sending a form with ajaxForm which will send data, open spinner.gif, then on success close spinner and reload the page:
$('#form').ajaxForm({
beforeSubmit:function(){
spinnerLoad();},
success: function(data){
spinnerDone();
window.location.href ="sample.php";
}
});
Then the form is handled like this:
if (isset($_POST['save'])){
exec("/directory/script.php $args");
}
So this page, 'script.php' executes another script on DB, so it may take a long time. When there is not many data, it works fine, but whenever I have much, after a time 'script.php' wents 404, and the spinner.gif never stops.
I need to find a way to extend timeout somehow (ajax timeout option seems not suitable) or another way.
Sending the script.php page or the DB script to background is not ok - it must be finished in order to continue working.
I'll be glad to any comments/directions to look.

Set $_SESSION in ajax request

I have this Jquery Ajax function to login in a web page.
url="<?php echo Yii::app()->createUrl("security/login") ?>"
$.ajax({
type:"POST",
url:url,
data:{},
success: function (jsonResponse) {
var json=JSON.parse(jsonResponse);
if(json.result == "SUCCESS")
{
<?php $_SESSION['LOGGED_USER']="USER"; ?>
}
},
error: function (jqXHR, textStatus, errorThrown) {
console.log(errorThrown);
}
});
And in my views layout I have this
session_start();
if( isset($_SESSION['LOGGED_USER']) )
{
print_r("LOGGED");
}
else
{
print_r("NOT LOGGED");
}
When I enter for the first time to the page It prints "NOT LOGGED" but it seems that it sets automatically the session so that when I reload the page It prints "LOGGED".
How can I set my session correctly in my ajax request?
Thank you very much :)
It seems a lot of people are confused about client vs server when it comes to Ajax. Let me see if i can clear that up:
Your JS runs in the browser (client). PHP runs on the server. The two are different languages that run on entirely different machines; they don't share the same variables or anything. They do not talk directly to each other, or really even know anything about each other. Their sole means of communication is via HTTP requests. (Well, there's WebSockets too...but that's a bit advanced yet.)
JS and PHP typically do not even run at the same time. Depending on your setup and where this script lives, one of two things is happening, and in this case, neither one is what you want.
The JS is in a file of some type the server doesn't feed to PHP. The PHP code is still in the file when the browser sees it -- and being invalid JS, causes a syntax error when you try to run it. Probably before you even get to do the Ajax post.
The JS is in a file of some type the server does feed to PHP. The PHP interpreter dutifully goes through the file, finds all the PHP code in it, and parses and runs it. The PHP code in it runs on the server, possibly before the page is even sent to the browser. (And since PHP doesn't speak JS, and doesn't even care if what it generates is valid HTML or JS...any non-PHP code in the page is irrelevant.) Anyway, by the time the browser runs your script above, it looks like this:
...
success: function (jsonResponse) {
var json=JSON.parse(jsonResponse);
if(json.result == "SUCCESS")
{
}
},
...
because PHP has already gone through the file and interpreted the bit about setting $_SESSION['LOGGED_USER']. If the user has an active session at all, logged in or not, that LOGGED_USER variable is set the second his browser requests that page.
The PHP script that's handling requests for security/login needs to set the session variable. Your JS won't be able to do it, as the session data is entirely server-side, and you can't let the browser just up and tell the server to run arbitrary PHP code without opening up a massive security hole. (Picture what could happen if the browser could say "hey, PHP, run this". All i'd have to do is pop up a JS console, see how you're doing it...and at the very least, i could write a line of JS in the console to set that variable whether i'm logged in or not.)
Or, if you really wanted, you could create another page that the JS posts to, that sets the session data. That seems a waste, though...and it might be quite difficult to do securely. (If PHP doesn't already know you're logged in, you'd have to re-authenticate and all that.) I wouldn't consider it unless for some reason security/login can't be modified.

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.

jQuery Ajax only executing once, but appears to call every time it should

Currently, I have set up an ajax call, that on change of a particular field it should execute a php script. The script first executes on page load.
AJAX Call
$j.ajax({url: prod_json_url, dataType: 'json', cache: true,
beforeSend: function( xhr ) {
xhr.overrideMimeType( 'text/plain; charset=x-user-defined' );
},
success: function(data) {
//things to do on success with JSON
}
});
Everything works great in my virtual environment for testing, but when I deploy this to a different server the following happens.
1) On page load, I can view the URL in FireBug being executed and returning the correct JSON Response. Logging shows that it did go to the script to be executed and returns the correct data. Everything acts as it should.
2) I then click to update the field. By viewing Firebug in the Console again, the correct URL is being executed, however, the JSON response is incorrect. It keeps the same one that occurred on page load. When I added logging, it appears that it never actually reaches the updated URL. (Which is the same URL as page load with updated arguments).
3) If I wait some time, and try again, it sometimes behaves as it should again, but only for the one execution.
This behavior makes me believe it is a cacheing issue. Does anyone have an idea of how I can resolve this or what variable I should be looking for or checking? The database is exactly the same and I'm not sure what else might be causing this. Any help is greatly appreciated! Please let me know if more information would be helpful as well.
Try adding the current time to the url you're loading data :
prod_json_url + '?ts=' + $.now()'
Cache control HTML headers apparently are ignore on Ajax requests in IE, therefore cache:false isn't enought. This should work though.
$.now() is a shortcut to new Date().getTime();
Set cache to false. Seems like theres client caching
$(document).ready(function() {
$.ajaxSetup({ cache: false });
});
try this copied from limk

ajax request with prototype returns 200 success with blank html page (intermittent)

i have a page performing the following ajax request when a button is pressed.
normally i get a json object back and it works fine, i have noticed on intermittent requests (usually only the first request from that page), i get back a 200 success code with a blank page.
if i reload the html page, then press the button again it works fine straight afterwards.
by intermittent i mean i can't replicate the issue at will, but it is happening regularly enough that i need to do something about it
i am just wondering if it is most likely an ajax or in particular a prototype problem or a server side issue (i am using debian/apahce/php)
what can i try to track down the problem ?
new Ajax.Request( url,
{
method:'post',
parameters: $('TeamForm').serialize(true),
onSuccess: function(transport) {
// do stuff
},
onFailure: function(transport) {
// display error
}
});
This isn't a solution to your problem but a workaround -- in the meantime, you could detect if the response's responseJSON property is NULL, and if so, log the error and resubmit the request. That way at least the second request should go through. The easiest way to handle this might be to throw a custom object from your onSuccess handler allowing your onFailure handler to catch it and resubmit.
Based on the example you provided, the only source of concern I can see with the javascript is the $('TeamForm').serialize(true); statement. Are you sure that the TeamForm has well formed data, and your PHP backend is handling this appropriately?
Check your PHP code for any trailing whitespace. You should not end your PHP files with a closing tag.
e.g.
<?php
class Foo {
}
?> //There is a space after this closing tag!
Would result in the hidden space being sent to your browser. It is valid syntax (and recommended) to leave the closing tag off of a pure PHP file:
<?php
class Foo {
}
Also check your code for any echo's or print's that may send output to the browser. Also check your display_errors setting, as an error message could result in data being sent to the browser as well.
I'd put 99:1 odds on the problem being server-side.

Categories