Ajax load page + JQuery click doesn't work [duplicate] - javascript

This question already has answers here:
Why does jQuery or a DOM method such as getElementById not find the element?
(6 answers)
Closed 5 years ago.
Why does my ajax not work?
These are my pages.
I'm using JQuery to check click event and using ajax to load the responder page.
What is wrong in this code?
index.php
<html>
<head>
<title>Test</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#clicket').click(function() {
$.ajax({
url: 'res.php?rand=' + Math.random(),
type: 'GET'
success: function(results) {
alert(results);
}
});
});
});
</script>
</head>
<body>
<button id="clicket">Hi</button>
</body>
</html>
Responder page:
res.php:
<?php
echo "Worked!";
?>
UPDATE:
I changed my javascript code above.

Put your logic in a document ready. Since your script is in your head, the markup in the body hasn't been loaded into the DOM yet. In order to make your script wait until the DOM has been built, put the logic in a document ready to delay it until that time.
$(document).ready(function() {
$('#clicket').click(function() {
$.ajax({
url: 'res.php?rand=' + Math.random(),
type: 'GET',
success: function(results) {
alert(results);
}
});
});
});

Try using full URL for your ajax call. If you are on live server then write your full domain name, like www.your_domain.com/res.php?rand=.

Related

Jquery Variable with ajax

I am working on a project and I am trying to use jquery to send a variable to php. This a file called test2.php that I have been using to test out the code, can anyone tell me what I am doing wrong because it should be printing out the variable when you click on the button but nothing is happening.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
var something="hello";
$("button").click(function(){
$.ajax({ url: 'test2.php',type: "GET", data: { q : something }});
});
});
</script>
</head>
<body>
<button>Get External Content</button>
</body>
</html>
<?php
if(isset($_GET['q']))
{
$q = $_GET["q"];
echo $q;
}
?>
Your code looks generally correct but you have to remember that an AJAX call sends the data "Asynchronously", which means when you click on the button this data is being sent to a separate instance of "test2.php" for processing. It is not reloading the current page with this new data.
The "test2.php" code you are viewing in browser is only run on the server side once when you first start up the page, and there is no 'q' in the '$_GET' variable at that time. The AJAX request is sending data to a separate instance of the same "test2.php" file and it is receiving some data back, but it is not using that information to load anything into your browser.
Depending on what you are trying to achieve there are many different solutions. You could use what you receive from your AJAX request to update information on the page like so:
$.ajax({
url: "test2.php",
type: "GET",
data: { q: something},
success: function (response) {
// do something with 'response' here
}
});
Or you could have the button instead be a simple <a> tag that reloads the current page in browser with information stored in '$_GET' like so:
Button
Then when your PHP code looks for 'q' it would actually find it in the $_GET variable because you reloaded the page.

Can't get php POST sent by AJAX

I know there's a lot of similar questions here, but I looked up over 20 of them, and no solutions worked for me.
Here's the problem: I'm sendind an ajax post value to my index.php. When I look at Firebug, the value is there, but when I try to echo it on the page, the POST is empty. I'm really stucked on this.
Here's my full code:
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<!-- JQUERY LIBRARY AND SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Test
<script type="text/javascript">
$(document).ready(function()
{
$('a').on('click', function()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: {action: 'clicked'},
success: function(data)
{
console.log(data);
alert('Done!');
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
return false;
});
});
</script>
</body>
</html>
This code does not try to print that to the page, but simply prepends the whole HTML document with a "clicked" string, in the ajax response. If you want to show this in the browser, you need print that data to the page. If you inspect the console in FireBug, you will see that the response for the Ajax call is exactly what I described above.
Now if you want to print that value back to your page, here is my suggestion, you create a separate file, ajax.php:
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
And fix your index.php to include some element where you are going to print that value to. I.e. add <div id="response-results"></div> just after your element. Then change your Ajax call to go to ajax.php, not index.php.
Now you need to populate that Ajax response to the rendered page, and this can be done simply with jQuery like:
$("#response-results").html(data);
Ofcourse, this goes into the success handler of the ajax call.
As Jay Blanchard said
You're using AJAX to send a a variable to a page which is already rendered on your browser. This will never work because the PHP your're getting the variable from has been run server-side and returned via AJAX, not in the page you're currently viewing.
Try this it will work :
index.php :
<?php
if(isset($_POST['action']))
{
echo $_POST['action'];
}
?>
main.html :
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta charset="utf-8">
<!-- JQUERY LIBRARY AND SCRIPTS -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
Test
<div id="result"></div>
<script type="text/javascript">
$(document).ready(function()
{
$('a').on('click', function()
{
$.ajax({
url: 'index.php',
type: 'POST',
data: {action: 'clicked'},
success: function(data)
{
// console.log(data);
$("#result").html(data);
},
error: function(jqXHR, textStatus, errorThrown)
{
alert(errorThrown);
}
});
return false;
});
});
</script>
</body>
</html>
As R J commented, it's impossible to do what I was trying to.
That happens because once my page is loaded, the top PHP script is proccessed, but there's nothing on my POST.
After my call to Ajax, the page is rendered again but the top PHP script will get nothing cause it's SERVER SIDE. Turns out that I even could print out my Ajax data on the page, but the PHP $_POST would never get its value.
Thank you guys.

Load Javascript after AJAX-fetched HTML is fully loaded

I have a situation where the HTML part is loaded with AJAX into a DIV with ID="dynamic content" using main.js script. This script is situated inside the HEAD part of main.php and it goes like this:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
}
});
The Javascript file responsible for controlling that content is situated in another JS file named secondary.js. This file is placed just before the closing of BODY again inside main.php.
main.php Document Structure:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
</head>
<body>
....
<div id="dynamic-content"></div>
....
....
<script type="text/javascript" src="js/secondary.js"></script>
</body>
</html>
Sometimes the content of content.php is too large, and secondary.js file loads before the content is fully loaded. Hence some elements are not targeted and i have problems.
Is there a way for me to delay for 1-2 seconds the execution of secondary.js, just to make sure that the content is fully loaded?
ps: all above files are hosted on the same server
Thanks in advance.
What you're trying to achieve is async behaviour. Whatever secondary.js does, put it inside a function and call it inside the ajax callback. If you do so, you won't even need two JavaScript files.
Don't try to manage this by timeouts or loading order. This will not be failsafe. You cannot know the exact time the browser needs to load your content. For example, what if you are on very slow internet connection? Don't try to predict those things, that's what the callback is for :-)
Your code could look sth like this:
function doSthWithLoadedContent() {
// whatever secondary.js tries to do
}
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
doSthWithLoadedContent();
}
});
You could possibly load the script using $.getScript once the output has been applied to the html tag:
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
$.getScript('js/secondary.js');
}
});
https://api.jquery.com/jquery.getscript/
The best way to do this would actually be to hand a callback to the function that does your ajax call. I probably wouldn't put this in html but it demonstrates the method:
<html>
<head>
<script type="text/javascript" src="js/main.js"></script>
<script lang="javascript>
function doWhenLoaded(someCallback)
{
$.ajax({
url: 'content.php',
success: function(output){
$('#dynamic-content').html(output);
someCallback();
}
});
}
$(document).ready(function(){
doWhenLoaded(function(){
$.getScript('js/secondary.js');
});
})
</script>
</head>
...
</html>
Instead of using $.getScript you could also load in secondary.js with main.js and wrap it in a function call (i.e. doStuff = function() { /* your code here */ }). Then you could call doWhenLoaded(doStuff) in $(document).ready.
You have to add script after ajax call.
$.ajax({
url: 'url of ajax',
type: "POST",
data: data,
dataType: "html",
success: function (data) {
$('#instructions').html('<div>' + data + '</div>');
$.getScript("js/html5lightbox/html5lightbox.js", function() {
$('body').find('.html5lightbox').html5lightbox();
});
}
});

Call a php function in a javascript with params

I need to call a PHP function with params from JavaScript when I click on some text in a html file; yeah, I know, it sounds like $##!$##
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() { /// Wait till page is loaded
$('#detailed').click(function(){
$('#main').load('parse.php?file=gz.xml', function() {
/// can add another function here
});
});
}); //// End of Wait till page is loaded
</script>
<a><div id="detailed">Stuff1</div></a>
<a><div id="detailed">Stuff2</div></a>
<div id="main">Hello - This is my main Div that will be reloaded using jQuery.</div>
What I want to make, is when I click Stuff1 on page, to call function parseLog('Stuff1'), and when I click Stuff2, to call function parseLog('Stuff2').
function parseLog(), is a PHP function, in functions.php
Anybody know a solution?
Thanks!
Javascript is client side script and PHP is server side script. So if you think, you need a call to that function over the network and get the response over the network. you should try using a coding method called AJAX. To make life easier and cross browser compatible use jQuery library and its ajax functionality.
Look at this post for a quick intro to jQuery and AJAX.
It helped me , hope this helps you too.
You should try something like this :
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
function myFunc (myData) {
$.ajax( {
type: "POST",
url: "parse.php?file=gz.xml",
dataType: 'json',
data: { param: myData},
success: function( result ) {
$("#main").append(result);
}
}
}
Stuff1</div>
Stuff2</div>
<div id="main"></div>

How do I load a page using ajax, query, json? [duplicate]

This question already has answers here:
Loading cross-domain endpoint with AJAX
(9 answers)
Closed 8 years ago.
How can I load a page using jQuery, AJAX, and JSON? I've tried something like this, but it is not working.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
<div id="wsww">content.<div>
<script type="text/javascript">
$.get('https://www.google.com/')
.success(function(data) {
$('#wsww').html(data);
});
</script>
You don't need the .success function, instead use a callback function... try this
$.get("<url>", function(data){
$('#www').html(data);
});
Cross Domain Access
HTML
<div id="Content">
</div>
Jquery
$.getJSON('http://whateverorigin.org/get?url=' +
encodeURIComponent('http://google.com') + '&callback=?',
function(data){
$("#Content").html(data.contents);
});
Reference
Whateverorigin.org/

Categories

Resources