I am trying to use jQuery's ajax to call a php script onload. This script will return xml from a url web service, parse through it, and then display bits and pieces of it into a div tag when the page loads (onload). I'm okay with php when it comes to using forms, but getting php scripts to run onload is not working for me. Could someone please look through my code and give me your advice? Thanks in advance.
HTML:
<!doctype html>
<html>
<head>
<title>Word of the Day</title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="code.js"></script>
</head>
<body>
<h3>Word of the Day: </h3>
<div id="word_day"></div>
</body>
</html>
JavaScript:
$(document).ready(function() {
$(window).load(function() {
$.ajax({
post: "GET",
url: "word_day.php"
}).done(function() {
alert(this.responseText);
}).fail(function() {
alert(this.responseText);
});
});
});
I did not add my PHP code since I was pretty sure that it wasn't the cause of my frustration.
You don't need those two handlers, just one:
$(document).ready(function()
{
$.ajax(
{
post: "GET",
url: "word_day.php"
}).done(function()
{
alert(this.responseText);
}).fail(function()
{
alert(this.responseText);
});
});
As you had it you were trying to create one handler when the handler fired which was never going to work.
Edit:
Your done/fail part should look like:
}).done(function(data)
{
alert(data);
}).fail(function(jqXHR, textStatus, errorThrown)
{
alert(textStatus);
});
Related
I've been struggling with this for two hours now and I've narrowed down the issue to a simple test case. I've done plenty of research and finally settled on trying to reproduce the first answer from this question: Set session var with ajax.
When I push this button (lazy html, but that's not where the issue lies):
<html>
<head>
...
<script src="jquery.js"></script>
...
<head>
<body>
....
<?php
var_dump($_SESSION);
?>
<input type="button" class="update">
....
</body>
</html>
This ajax request in jquery.js gets called:
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function() {
console.log("Successful request sent");
}
});
And finally the setSession.php file:
<?php
session_start();
$_SESSION["foo"] = $_POST["bar"];
?>
The success message is printed to the console so I know I'm hitting the right file. Why isn't the session variable getting set? I have php 5.5.2 if that matters at all. Thanks for you help!
Like I suggested on the comments, do this to fix your code:
Reload the page on your success:
success: function() {
console.log("Successful request sent");
location.reload();
}
Make sure you have session_start() in all the pages that uses sessions:
session_start(); //this must be at the top, before you print anything
Might this can help you.
In setSession.php write echo $_SESSION["foo"] = $_POST["bar"];
In your ajax script do
$.(".update").click(function() {
$.ajax({
type: "POST",
url:"setSession.php",
data: {bar: "foobar"},
success: function(e) {
console.log(e);
}
});
now open browser console (F12). click on your button.update. Check if is there written bar in console.
i want to pass a variable from jquery to php but my code doesnt work .I tried very hard but no luck . When i click the button nothing happens.plz help thank you
one more thing i tried this without passing variable and i use only echo command then it works but when i pass variable nothing happens
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$("button").click(function(){
var var_data = 5;
$.ajax({
url: "myscript.php",
data: { var_php_data: var_data },
success: function(data) {
// do something;
alert(data);
}
});
});
</script>
</head>
<body>
<button>Change Content</button>
</body>
</html>
myscript.php contains the following code
<?php
echo $_GET['var_php_data'];
?>
Try wrapping your script in a document ready handler. Also you have a trailing comma (,) after the success callback that you should remove. Also you should use a , instead of ; after the data parameter. Specifying the HTTP verb for your AJAX request might also be useful:
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('button').click(function() {
var var_data = 5;
$.ajax({
url: 'myscript.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
alert(data);
}
});
});
});
</script>
</head>
<body>
<button>Change Content</button>
</body>
</html>
The reason you need to wrap your click registration in a document ready handler is because you put your script inside the <head> section of your markup and the button hasn't yet been loaded by the browser when you attempt to subscribe to its click handler.
You can install Firebug (Firexox plugin), or user something similar for your browser to see real HTTP request and response. If you will post them here it will be more simple to find the problem.
Track request in FireBug. You can find by FB did request success (200) as well as date send by request.
Also, try http://{your_host}>/myscript.php?var_PHP_data=echoText
Addition:
Darin Dimitrov described the problem right way
This jQuery ajax request is not working. The form submit just reloads the page, there are no alerts, nothing. Where am I going wrong?
$("#newfolder").submit(function() {
alert("1")
$.ajax({
type : "POST",
url : "<?php echo $cfg->wwwroot ?>/pages/media/async/newfolder.php",
data : $(this).serializeArray(),
success: function(data) {
alert(data)
//$.fancybox(data);
}
});
return false;
});
This can have several causes.
Ensure that you've included jQuery as one of first <script>s in HTML <head>.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
Ensure that you're calling this function when the document is ready loading.
<script>
$(document).ready(function() {
// Here.
});
</script>
Ensure that the element with id="newFolder" is present in HTML DOM tree and supports the submit event.
<form id="newFolder">
I currently have a php file executing:
test
I would rather not have to load a new page and do it onClick.
Does anyone know a simple way to do this?
I added a more complete example, including the suggested ajax. I still am having trouble getting it it to work though.
<script type="text/javascript">
$('li').click(function() {
$.ajax({ type: "GET", url: "test.php", data: { foo: 'boo' }, success: function(data){
// use this if you want to process the returned data
alert('complete, returned:' + data);
}});
});
</script>
</head>
<body>
<div id="header">
<h1>Title</h1>
</div>
<ul>
<li>Test</li>
</ul>
</body>
</html>
you could use jquery and do something like this:
$.ajax({ url: "test.php", data: { foo: 'boo' }, success: function(data){
// use this if you want to process the returned data
// alert('complete, returned:' + data);
}});
for more information, take a look at the jquery-documentation
Yes, as your tags say. You will need to use AJAX.
For example:
$.ajax({
type: "GET",
url: "test.php",
data: "foo=boo"
});
Then you just have to stick that within a click function.
$('a').click(function() {
// The previous function here...
});
EDIT: Changed the method to GET.
In your firl say e.g try.html write this code
<meta http-equiv="refresh" content="2;url=test.php?foo=boo">
it will redirect u to test.php?foo=boo in 2 seconds
OR Other way ===========================================
create one php file
<?php
header('Location: test.php?foo=boo');
exit;
?>
Hope this help
I need to get all statistics from a Youtube channel so that I can create a document using PHP containing all of the data.
I want information such as the dates the video was viewed, if it has been liked, if it has been blogged and so on.
Is it possible to do this?
Thanks
Please see the sample code below for how you can do some of this. You can find a basic demo here. As seen, you do not necessarily need to write any PHP code to do this. More details are available in developer documents.
<html>
<head>
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("body").append("<div id = 'data'><ul>jffnfjnkj</ul></div>");
var dataContainer = $("#data ul");
$.ajax({
url:'http://gdata.youtube.com/feeds/api/standardfeeds/top_rated?alt=jsonc&v=2&callback=?',
dataType: "jsonp",
timeout: 5000,
success: function(data){
$.each(data.data.items,
function(i, val) {
if (typeof(val.player) !== 'undefined' && typeof(val.title) !== 'undefined') {
dataContainer.append('<li>'+val.title+'</li>');
}
});
}
});
});
});
</script>
</head>
<body>
<h2>Header</h2>
<p>Paragraph</p>
<p>Paragraph.</p>
<button>Click me</button>
</body>
</html>