I am trying to load the output of a PHP script into a using JavaScript and JQuery. The JavaScript function I am using uses the $.get function in JQuery to call a php script, which I want to display in another division. The script I wrote is:
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
});
});
}
</script>
The PHP script (dbtest.php) uses a simple echo statement:
echo "hello, world!!!";
I am getting the first alert here, but not the second. What Can I be doing wrong here?
I suppose uname is a ID, in that case you should use:
$("#uname").html(data);
You can add this to your php for debugging:
error_reporting(E_ALL ^ E_NOTICE);
ini_set("display_errors", 1);
Try also to remove http:// from your ajax call and use relative path instead.
The guys below pointed out that the selector is wrong. Indeed that's a problem, but I think that the real issue is that you don't get the second alert. Probably your php file localhost/dbtest.php is not accessible. What happen if you open localhost/dbtest.php in a new tab?
I think the problem is the path to your dbtest.php file. You are saying you seecond alert will not be displayed so your request must be wrong.
Try to copy your page into the same folder like dbtest.php open the page in your browser with http://localhost/yourfile.php
If this does not display both alert-boxes try the same with an open developer console (Chrome/IE = F12) and look if there are errors.
You say you are trying to make ajax requests to your localhost from a Phonegap application. Phonegap prevents making ajax requests to other domains by default. You must add localhost to whitelist. Here is more detail: http://docs.phonegap.com/en/1.9.0/guide_whitelist_index.md.html
Here you have a working example:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<div id="uname"></div>
<script>
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("#uname").html(data);
});
});
}
on_load();
</script>
Beware of the same-origin-policy. The page loading dbtest.php must be from the same origin, unless you grant other origins by adding a header from dbtest.php.
Try add some error handling to your code to better see what´s happening.
<script type="text/javascript">
function on_load() {
$(document).ready(function() {
alert('here');
$.get("http://localhost/dbtest.php", function(data){
alert('here too too');
$("uname").html(data);
}).fail(function () {
alert("failed");
});
});
}
</script>
Related
I can see that the $.getScript bit of jquery would be handy once it's working, but it's the last little bit I'm having problems with. I'm suspecting the problem is caused by the way I'm loading JS files. How do I get this to work? My index.html is actually index.php and has very little between the body tags. I'm using jquery 1.7.1
<body id="btLive">
<script>
buildInterfaces();
</script>
</body>
buildInterfaces() resides inside a document named layoutLoader.js. In that file, I have the following:
$(document).ready(function() {
$('#hToggle').click(function() {
aaa = "Not working.";
$.getScript('test.js', function() {
alert(aaa);
});
toggleHoverPanel();
});
});
As my test, test.js is in the same folder as layoutLoader.js and contains only the following:
aaa = "Successful Load."
When I click on the button hToggle, toggleHoverPanel takes place and I get no alert. If I place an alert after aaa="Not working."; I get the alert I expect, telling me it's not working. I have a number of items that I need to use this for, but for the life of me, I cannot get it to work. Help?
With high probability test.js file could not by found.
Add this piece to your code and try again:
$(document).ajaxError(function(event, request, settings){
alert('error loading: ' + request.status);
});
I read this question, and I'm pretty sure it's 90% of what I need, but I'm after something more than just this, and my success formulating my query in Google has been less than stellar.
What I'd like to do
I have a form on a site that, when submitted, needs to connect with a database, and then the user needs to be apprised of the result. I'm trying to get the result page to load in a modal jQuery dialog instead of forcing a full page reload. At present, I'm just trying to create a jQuery dialog that replaces the contents of a <div> with the product of a PHP file. I know I will get the PHP file's execution result this way. That's what I'm after, but it currently is not working.
My code currently looks like this:
$(document).ready(function() {
$("#dialog").get('include.php', function(data) {
$("div#dialog").html(data);
});
});
And include.php is simply:
<?
echo "<h1>Loaded</h1>";
?>
When I load the page, the original contents of #dialog are still there. I have a strong suspicion that what I'm failing to grasp isn't major, but I've had bad luck finding the fix. I'm a web dev newbie. How do I wwebsite as on the internet?
You are calling get on a jQuery result. That'a a different method than $.get, the one you should be using:
$(document).ready(function() {
$.get('include.php', function(data) {
$("div#dialog").html(data);
});
});
i have been using Ajax call for the same purpose. So try this :
$(document).ready(function() {
$.ajax('include.php',
success : function(data) {
$("#dialog").html(data);
});
});
If you want to replace the entire contents of the #dialog DOM object with the HTML you load, then you probably want to use .load():
$(document).ready(function() {
$("#dialog").load('include.php', function(data) {
// no need to set the html here as .load() already does that
});
});
Trying to load an external php file into another onClick. Iframes will not work as the size of the content changes with collapsible panels. That leaves AJAX. I was given a piece of code
HTML
Get data
<div id="myContainer"></div>
JS
$('#getData').click(function(){
$.get('data.php', { section: 'mySection' }, function(data){
$('#myContainer').html(data);
});
});
PHP:
<?php
if($_GET['section'] === 'mySection') echo '<span style="font-weigth:bold;">Hello World</span>';
?>
I have tested it here http://www.divethegap.com/scuba-diving-programmes-dive-the-gap/programme-pages/dahab-divemaster/divemaster-trainingA.php and get the most unexpected results. It certainly loads the right amount of items as it says in the lower bar on safari but I see three small calendars and that is it. Can anyone see where I have made a mistake?
First things first, you want to have the jQuery bit inside the ready function $(document).ready(function(){..}. In your test page, there is already a ready function at the top which contains the line $('a[rel*=facebox]').facebox(), so you might want to put the code there.
Secondly, you want to prevent the link from going to the default action, which is to load the url '#'. You do that with the preventDefault() method.
I tested and confirmed that the following code should work for you:
<script type="text/javascript">
$(document).ready(function(){
$('#getData').click(function(event){
event.preventDefault();
$.get('test.php', { cat: 16 }, function(data){
$('#myContainer p').html(data);
});
});
});</script>
You can find more details and examples of jQuery's get function here.
http://net.tutsplus.com/tutorials/javascript-ajax/how-to-load-in-and-animate-content-with-jquery/ this tutorial may helps you
echo "<a href=#> Delete </a>";
Whenever a user hits Delete, a javascript function should be called for confirmation. Somewhere in the Javascript function, php code should be used for delete operation. How do I do that? Use something like "some php code goes here" and "some javascript function();" for me to know where to put what. Thanks.
This assumes that you are using jQuery...
<a href='javascript:delete();'>Delete</a>
<script type="text/javascript">
function delete()
{
$.post("/your_script.php", {}, function(result) {
});
}
</script>
JavaScript functions execute on the client (in the browser) and PHP executes on a server. So, the JavaScript must send a message - via HTTP - to the server to be handled by PHP. The PHP would perform the delete. Make sense?
The message sent to the server might be sent via AJAX.
Maybe you should use Ajax: http://en.wikipedia.org/wiki/Ajax_%28programming%29
PHP is a server-side technology, while JS is a client-side. They cannot interact with each other - in other words: they're completely independent.
PHP can only output code that is a JS code:
echo 'document.getElementById("test").appendChild(document.createTextNode("' . $myVar . '");';
It's all PHP can do. JavaScript cannot direct interact with PHP as well. You'll have to use AJAX to send a new HTTP request and process returned data.
PHP is a server-side language, thus you can not output PHP script to the browser and expect that it will parse it with the PHP engine.
What you're looking for is probably AJAX, or simply redirecting the user to another page (with different URL parameters) or submitting a form.
AJAX doesn't require from the browser to reload the page, while the two other methods does.
Anyway, you can execute a JS script with the "onclick" method, that's executed when the user clicks on the element: Delete
But the following approach looks better and considered as an ideal one:
Delete
<script type="text/javascript">
document.getElementById("myId").onclick = myFunc;
</script>
Since this involves Ajax, let's assume you can use jQuery to handle the XHR an so on.
<script>
$('#del').click(function(ev){
ev.preventDefault();
var del_conf=confirm('Are you sure you want to delete this item?');
if(del_conf){ $.post('delete.php',{'del':1,'id':123123},function(data){
alert(data.result);},'json');
}
});
</script>
<a id='del'>Delete</a>
Okay, so that's some JS and HTML. Now, you need a separate PHP script to handle the post. To go with the example, this would be saved in the same directory, named 'delete.php'.
<?php
$del=(int)$_POST['del'];
$id=(int)$_POST['id']
if($del<1 || $id<1){ exit; }
else{
//do your DB stuff
}
if($db_success){
echo json_encode(array('result'=>'success'));
}
else{
echo json_encode(array('result'=>'error'));
}
here is another example using jQuery:
<div id="message"></div>
<a class="action" type="delete" rel="1234567">delete</a>
<script type="text/javascript">
$('a.action').click(function(){
var $this = $(this);
var processResponse = function(data){
//optionaly we can display server response
$('#message').html(data);
return;
};
var postPparams = {
module:'my_module_name',
action:$this.attr('type'),
record_id: $this.attr('rel')
};
$.post('/server.php',postPparams, processResponse);
});
</script>
There's a great tutorial on IBM's website which walked me through a simple search/results list using jQuery,PHP and Ajax.
I was able to make it work and it's really cool.
One problem. I want the results to be hyperlinks and I can't get any java script to run on the results.
Here is the script I have (includes what was in the tutorial plus the additional script necessary to ovverride the hyperlink, click behavior):
<script type='text/javascript'>
$(document).ready(function(){
$("#search_results").slideUp();
$("#search_button").click(function(e){
e.preventDefault();
ajax_search();
});
$("#search_term").keyup(function(e){
e.preventDefault();
ajax_search();
});
$("a").click(ClickInterceptor);
});
function ajax_search(){
$("#search_results").show();
var search_val=$("#search_term").val();
$.post("./find.php", {search_term : search_val}, function(data){
if (data.length>0){
$("#search_results").html(data);
}
})
}
function ClickInterceptor(e)
{
window.alert("Hellow World!");
return false;
}
</script>
If i put the following html under the <body> tag:
this will work
That will display the alert window.
However, if I change the results to hyperlinks (found in find.php, listing 7 from the tutorial):
$string .= "".$row->name." - ";
It does not work.
Any idea on how to fix this?
The click function binds when it is run. You need to change it to a live binding.
$("a").live("click", ClickInterceptor);
Or you can just bind it when you update the search results by putting the following after $("#search_results").html(data):
$("#search_results a").click(ClickInterceptor);
The problem is pretty simple actually, $("a").click(ClickInterceptor); will only look for items that currently exist in the DOM. All you need to do is change that line to this:
$("a").live("click", ClickInterceptor);
I'd also advise taking the time to read more about jQuery's Events/live.