Related
In this script, using php's return will not work, whereas echo will. Thing is, if I use echo, and someone where to access the page directly, they would be able to see the output without the formatting.
<script type="text/javascript">
$(function() {
$('.callAppend').click(function() {
$.ajax({
type: 'GET',
url: 'recent.php',
dataType:'HTML',
cache:false,
success: function(data){
console.log(data);
//}
},
});
return false;
});
});
</script>
This the php script
<?php
$feedback = 'Hello this is the php page';
return $feedback; //Use echo, and all works fine.
?>
return is used for returning a value from a function to another piece of PHP code.
jQuery is not part of the execution of the PHP code on the server, so it has no idea what is really going on server side. jQuery is waiting for the rendered server response, which is what echo provides.
This SO answer provides a solution to only allow an AJAX script to be called by that type of request:
Prevent Direct Access To File Called By ajax Function
Even though it is checking for 'XMLHttpRequest', someone could make this type of request from something else other than you weboage.
When you use AJAX to load a URL, you're loading the raw output of that URL. Echo produces output but return doesn't. You'll need to do some reason on the subject of OOP to understand what the purpose of return is.
Echo is the correct way to send output.
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 have been searching all over the internet tonight, saw a lot of "solutions" but not working for me unfortunately. So I will try to get different answer of what I am seeing here on stack and elsewhere and hoping I will find one which will work...
My page has the following javascript bit:
logbook = setInterval(function () {
$.getJSON("php/log.php", function(data) {
$.each(data.posts, function(i,data) {
$('#logspan').replaceWith(data.logupdate);
});
});
}, 5000);
When I run the page, it works, but only ONE time and then it stops the interval completely (this is in Chrome and Firefox) and basically gives up.
This is weird, because there is yet another script which is running as follows and is doing its job perfectly:
var timer;
function startCount() {
timer = setInterval(count,1000);
}
function count() {
var el = document.getElementById('counter');
var currentNumber = parseFloat(el.innerHTML);
el.innerHTML = currentNumber+1;
}
I already tried to see if the first script works if I turned the second one off, but it is still no go. So, how can I ever make the first (JSON) script work? It is way past my bedtime thanks to this problem and I haven't gotten any step further!! pulls hair
Any suggestions / hints / tips are appreciated...
EDIT: Ok, I found something peculiar, when I replace the "replaceWith" and use "appendTo" it seems to update the #logspan just fine, but obviously I do not want to spam my own webpage. Maybe the problem lies somewhere else?
Agreed.
Use a different variable name than data in your $.each() function body, as you may be inadvertently referring to the data in the $.getJSON() function body
Since you're iterating over the posts returned in the JSON call, empty out the body of #logspan only once, then append the content of each post sequentially to #logspan.
var logbookTimer = setInterval(function () {
$.getJSON("php/log.php", function(data) {
// Empty out the body of the log
$('#logspan').empty();
// Add some content for each retrieved post
$.each(data.posts, function(i,d) {
$('<div>').html(d.logupdate).appendTo($('#logspan'));
});
});
},5000);
try this way
var logbook = function () {
$.getJSON("php/log.php", function(data) {
$.each(data.posts, function(i,data) {
$('#logspan').replaceWith(data.logupdate);
});
});
};
setInterval(logbook, 1000);
I have an issue when trying to get Javascript to execute functions in my desired order. I'm trying to get a jQuery modal form to load information based on a certain selection. I have two SELECT boxes that need to be loaded, but the contents of the second SELECT box depend entirely on the selected value of the first SELECT box.
I made the following functions to request the information I need:
function get_Subjects(varID, callback){
$.post("../vars/get_SID.php", { vid : varID },
function(result){
getInfo('tbsubjectdiv', '../vars/findSubjectlist.php?sid='+result);
});
callback();
}
function get_Selectedfields(varID, callback){
$.post("../vars/requestTblock.php", { vid : varID },
function(result){
populateForm('tbWiz', result);
document.form_tbWiz.varname.disabled = true;
$('.trSearch').hide();
$('.trValueset').hide();
});
callback();
}
function get_TextblockType(varID, callback){
$.post("../vars/requestVtype.php", { vid : varID },
function(result){
if(result == 0){ //Opzoeken
$('.trSearch').show();
}else if(result == 1){ //Datum vergelijken
$('.trSearch').show();
$('.trValueset').show();
}else if(result == 2){ //Percentage
//
}
});
callback();
}
The first function checks the MySQL database for the selected value
of the FIRST SELECT field, and loads the results into the second
SELECT field.
The second function requests the rest of the rest of the form data, and populates the form using populateForm(). It also hides
certain parts of my form in preparation for function three.
The third function basically requests which parts of the form have to be displayed, because that's not always the same.
The whole idea behind this is that I want to use populateForm() to populate all of the form fields. In order for populateForm() to properly set the selected SELECT option, the particular SELECT field must first contain the OPTION it needs to select. Makes sense. I try to make sure of this with my first function, which will load all of the OPTIONs. THEN I try to use the get_Selectedfields() to populate all the proper values. This is not what happens though. No matter what I try to do, getInfo() in the first function is ALWAYS being called LAST. This makes it impossible for populateForm() to select the proper option, which is driving me mad.
I'm trying to "force" the execution-order by doing this:
function getTextblock(var_ID){
get_Subjects(var_ID, function() {
get_Selectedfields(var_ID, function() {
get_Textblocktype(var_ID, function() {
// Done
});
});
});
}
When I realised it still did not work the way I wanted, I decided to use Chrome's Developer Tools to check the order in which everything is executed. It all works as expected, but at the very end it jumps straight back to getInfo(), which is part of the FIRST function I called. I'm absolutely clueless as to why getInfo() gets executed last. If this just gets executed at the very beginning, where I want it to execute, it would all work fine.
You have to call the callback in the callback function of the post request:
function get_Subjects(varID, callback){
$.post("../vars/get_SID.php", { vid : varID },
function(result){
getInfo('tbsubjectdiv', '../vars/findSubjectlist.php?sid='+result);
callback();
});
}
function get_Selectedfields(varID, callback){
$.post("../vars/requestTblock.php", { vid : varID },
function(result){
populateForm('tbWiz', result);
document.form_tbWiz.varname.disabled = true;
$('.trSearch').hide();
$('.trValueset').hide();
callback();
});
}
function get_TextblockType(varID, callback){
$.post("../vars/requestVtype.php", { vid : varID },
function(result){
if(result == 0){ //Opzoeken
$('.trSearch').show();
}else if(result == 1){ //Datum vergelijken
$('.trSearch').show();
$('.trValueset').show();
}else if(result == 2){ //Percentage
//
}
callback();
});
}
The POST is being handled asynchronously in your functions so your "callback" is really just being executed almost immediately after your initial call, whereas the callback of $.post is being executed after the post has occurred. Does that help you sort things out? You will probably need to kick off the rest of the process in the callback of $.post("../vars/get_SID.php", { vid : varID }...
$.post is shorthand for $.ajax so you can read up a bit more in the jQuery docs, but I would not suggest switching to synchronous requests. If you absolutely must have one request finished before the next can execute then kicking off that next step from the callback is the way to go.
You're using ajax. The first a is for asynchronous. If you called the functions from the function(result) blocks then they would occur in order.
Alternatively (and this isn't a great idea but you can do it) use the $.ajax() object and set async to false.
As you don't know how long long an ajax request will actually take, you can only chain events within the ajax response:
function getTextblock(var_ID){
$.post(YOUR_TARGET, YOUR_DATA, function(result){
YOUR_CODE
// CHAIN HERE, call new function or sub ajax request
});
}
Wesley,
The javascript will execute always on the predefined order. If you put a bunch of "alerts()" in the middle of your code, you can taste that.
But this is not true for callbacks, because they will be moved to the bottom of execution stack on javascript where we can't determine the order, since they are called by a AJAX return which by definition is asynchronous.
Even though your ajax executes in a millisecond, the callback will not be executed until all methods in your script block have finished.
You have, actually three options:
Chain all the methods sequence in callbacks. Please, don't call a callback!! It inst supposed to be you, but the "system" that will call those.
// The data you need first
function myStartPoint() {
$.post(url, function(result) {
// do what you need with this result (this is your callback, but anonymous)
// then, call the next step
secondPoint();
});
}
function secondPoint() {
$.post(url, function(result) {
// again, the callback is anonymous... your hardly need to declare something named callback
// chain how many points as you need
nextPoint();
}
}
"Force" the ajax to be synchronous with async:false option. This can cause performance issues.
The ugliest of all is to use the damned setTimeout which is very, very wrong, but will work in your case because, the setTimeout will put the method on the bottom of execution stack even after those callbacks which are expected to be fast. Seriously, I just put this option because eventually someone would say it... Do not take this path.
i make a Jquery function that (for the moment) call a function dinamically and print it with an alert. with firefox, chrome : it works! when i try on IE7 (the first time), it fails. If i reload the page (F5) and retry , it works! o_O
I FINALLY understand why that's happen. In my old website i used the jquery-1.3.2.min.js library. On this i use the jquery-1.4.2.js and in fact it doesnt work. So what's up? A bug in this new version?
cheers
EDIT
actual functions (with Bryan Waters suggestions):
// html page
prova
// javascript page
function pmNew(mexid) {
var time = new Date;
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php' + '?dummy=' + time.getTime(),
data: 'mexid='+escape(mexid)+'&id=pmnew',
success: function(msg) {
alert(msg);
}
});
return false;
}
// ajax.php
if($_POST['id']=="pmnew") {
echo "please, i will just print this";
}
Fiddler result : if i use http://localhost/website fiddler doesnt capture the stream. if i use http://ipv4.fiddler/website it capture the stream, but at the ajax request doesnt appair. if i refresh the page, yes it works. mah...i really don't know how resolve this problem...
Best way to debug is to download Fiddler and see what the HTML traffic is going on and if the browser is even making the ajax request and what the result is 200 or 404 or whatever.
I've had problems with IE cacheing even on posts. And not even sending out the requests. I usually create a date object in javascript and add a dummy timestamp just to make the url unique so it won't be cached.
ok, I'm not exactly sure what the issue is here but I think you could probably fix this by simply letting jquery handle the click instead of the inline attribute on the tag.
first change your link like this to get rid of the inline event
<a class="lblueb" href="./asynch/asynchf.php?mexid=<?$value?>"><?=value?></a>
then in your javascript in the head of your page add a document.ready event function like this if you don't already have one:
$(function(){
});
then bind a click event to your link inside the ready function using the class and have it pull the mexid from the href attribute, then call your pmNew function like so:
$(".lblueb").click(function(e){
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
Your final code should look like this:
<script type="text/javascript">
function pmNew(mexid) {
$.ajax({
type: "POST",
url: "./asynch/asynchf.php",
data: "mexid="+mexid+"&id=pmnew",
success: function(msg){
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
//document.ready function
$(function(){
$(".lblueb").click(function(e){
//prefent the default action from occuring
e.preventDefault();
//your query string will be in parts[1];
parts = $(this).attr("href").split("?");
//your mexid will be in mexid[1]
mexid = $parts[1].split("=");
//call your function with mexid[1] as the parameter
pmNew(mexid[1]);
});
});
</script>
I believe you have an error in your SQL code. Is userd supposed to be userid?
Gaby is absolutely right that your SQL code is wide open for injection. Please consider learning PDO, which will reduce the likelihood of SQL injection significantly, particularly when using placeholders. This way you will have query($sql) and execute($sql), rather than the code going directly into your DB.
As a matter of habit you should deal with your request variables early in your script, and sanitize them to death -- then assign the cleaned results to new variables and be strict in only using them throughout the rest of the script. As such you should have alarm bells ringing whenever you have a request variable in or near an sql query.
For example at the very least you should be stripping any html tags out of anything that will get printed back to the page.
That is in addition to escaping the quotes as part of the sql string when inserting into the database.
I'm all for coding things up quickly -- sure, neaten up your code later... but get security of request vars right before doing anything. You can't tack on security later.
Anyway sorry for harping on.... as for your actual problem, have you tried what Gaby suggested: change your html to:
<a class="lblueb" href="#" onclick="return pmNew('<?php echo $value; ?>')"><?php echo $value; ?></a>
And then update your JS function to:
function pmNew(mexid) {
$.ajax({
type: 'POST',
cache: false,
url: './asynch/asynchf.php',
data: 'mexid=' + escape(mexid) + '&id=pmnew',
success: function(msg) {
$('#pmuser').html('<a class="bmenu" href="./index.php?status=usermain">PANEL (' + msg + ')</a>');
}
});
return false;
}
Also, with IE -- check the obvious. Clear the browser cache/history
I didn't understood the "fail", but here's another example..
function pmNew(mexid) {
$.post("./asynch/asynchf.php", {mexid: mexid, id: "pmnew"},
function(msg) {
$("#pmuser").html('<a class="bmenu" href="./index.php?status=usermain">PANEL ('+msg+')</a>');
}
});
}
It appears that this issue is faced by several people.
One of them had luck with clean installation of browser:
http://www.geekstogo.com/forum/topic/22695-errorpermission-denied-code0/
Check to make sure the content returned to the DOM is valid for the DOCTYPE specified.
I've had a similiar problem with Chrome, FF and Safari all working just fine, but finding the ajax result broken in IE. Check to make sure you don't have any extra divs or spans in the ajax result breaking your markup.