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
Related
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(){});
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.
I got a problem and I´m about to hurt the MVC-paradigm, so I rather ask you what to do.
I got a page which is refreshed every 10 seconds with jQuery .post()-method.
setInterval(function() {
$.post("http://XYZ.de<?php echo $this->webroot."Posts/index"; ?>", { liveUpdate: "true" },
function(response) {
$('#loadingContent').html(response);
}
);
}, 10000);
now, where the "Posts/index" is placed I have to call the PostsController.php of Cake which allows me to reset the variables.
But it doesn´t work that way and the response is filled with all the html of a normal page-call but I only want to have the pure PHP-variables updated without html appended to that div.
What am I doing wrong?
Thanks in advance for your patience.
Since your array is complex multilevel and you do not want to parse JSON, the only way I see doing it would be using jQuery load().
setInterval(function() {
jQuery("#RefreshMeOnPage")
.load("http://XYZ.de<?php echo $this->webroot."Posts/index"; ?> #RefreshMeInResults > *", {liveUpdate: "true"});
}, 10000);
It will make post request to server and replace contents of existing element with id RefreshMeOnPage with the contents of newly received element with id RefreshMeInResults. Docs http://api.jquery.com/load/.
NOTE: Still with refresh rate of 10 seconds, I think you should look into ajax comet solution http://cometdaily.com/maturity.html. It will receive data only when there is change, although it requires some configuration.
I'm doing Ajax get to fetch cross browser data, in this case from cnn.com:
$(function(){
var site = 'http://cnn.com/';
$.get('proxy.php', { site:site }, function(data){
$(data).find('a').attr('href', function(_, href){
return href.replace(/\/\/[^\/]+/, '//cnn.com')
});
$('#result').append(data);
}, 'html');
});
As you can see there is a piece of code which is able to replace part of the url with 'cnn.com', this is necessary because the url path is often attach to my website domain.
The problem is that the replace function doesn't seem to work. I'm not getting any errors in console, so I suspect I have to put the code somewhere else. Another possibility is that the code cannot find a because the Ajax loading data process is not complete. I tried fixing it with event ajaxComplete with no luck.
What do I have to change in the code in order for the function to find a and replace it?
ps I know there is a piece of proxy.php code but I rather do this on the browser side (javascript/jquery)
You are creating a jQuery object, manipulating the elements, but you are not appending that and finally data remains unchanged, try this:
$(data).find('a').attr('href', function(_, href){
return href.replace(/\/\/[^\/]+/, '//cnn.com')
}).end().appendTo('#result');
THIS PROBLEM IS NOW SOLVED. THANK YOU TO EVERYONE WHO REPLIED.
Hello,
I am trying to solve a problem that I may have approached from the wrong direction, so maybe someone could suggest a better solution.
I am writing a little web app for work, that has a search function. When user submits a search string, form gets posted to a CodeIgniter controller. If search returns a result, CodeIgniter loads a page with results. If there is no results, user's current page just gets reloaded, without any indication that search returned no results. So, this is not user friendly at all and i decided to re-do that with some help from $.ajax().
That was rather easy, but now I am stuck trying to figure out what to do with the data i receive back, if search is successful.
I know $.load() can replace a part of the page, but i need to redirect the user to a completely different page, while POSTing the data
my ajax search just returned. The data that comes back from PHP is in json_encode() format.
NOTE: $.jGrowl() is a jQuery plugin that displays a Growl-like message.
$("#alias_s").submit(function() {
event.preventDefault();
var term = $('input#alias_search').val();
$.post("<?=base_url()?>aliases/searchAliases", {
searchTerm: term },
function(data) {
if(!data) {
$.jGrowl("Search for '" + term + "' returned no results", { life: 5000 });;
} else {
//
// How do i post this data to another page and redirect a user there?
//
}
});
UPDATE: I managed to find a work-around to this issue.
I take the data that was returned from $.post() and use $.load() to POST it back to the same controller, that in turn takes the data and loads correct view files. The only downside is that URL it still the same, which breaks couple of small things, but I can deal with that...
$('#content').load("<?=base_url()?>aliases", { searchData: data});
UPDATE #2: I finally made it work like i wanted. What i did, is take the data that was returned from PHP in JSON format, post it back to the same controller, and let CodeIgniter take care of loading views, this way all my URL dependent stuff works too.
$('<form action="CONTROLLER" method="post"><input type="hidden" id="searchData" name="searchData" value='+data+'></form>').appendTo($("body")).submit();
There were 2 caveats though.
appendTo($("body")) was needed to make it the form submit correctly in Firefox.
POST was cutting off my JSON string after first space, so i had to use str_replace() in php do fix that.
echo str_replace(' ', '%20', json_encode($search_results));
THIS PROBLEM IS NOW SOLVED. THANK YOU TO EVERYONE WHO REPLIED.
I am writing a little web app for work, that has a search function. When user submits a search string, form gets posted to a CodeIgniter controller. If search returns a result, CodeIgniter loads a page with results. If there is no results, user's current page just gets reloaded, without any indication that search returned no results.
I think you should just fix that bad behavior, and have the "Search" action return the page with some error information. Using AJAX doesn't really do you any good if you want to completely reload the page anyway.
If you want redirect the user another page, why do you stop the execution a form in a javascript?
Maybe this work, but i not tested.
$("#alias_s").submit(function() {
var term = $('input#alias_search').val();
$.post("<?=base_url()?>aliases/searchAliases", {
searchTerm: term },
function(data) {
if(!data) {
$.jGrowl("Search for '" + term + "' returned no results", { life: 5000 });;
return false;
} else {
//
//
//
}
});
This has been solved. Solution is in my original post.