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
Related
Just playing around with ajax and php and I have a simple question.
These are the following relevant files.
file.php
<?php
$bla = $_GET['pid'];
echo $bla;
?>
HTML
HTML Code of example site URL: somesite.com/blabla.php?pid=3
(It contains a single button which when you click it is supposed to get the $_GET value from the URL which is 3)
<!DOCTYPE html>
<html>
<head>
<title>Some Page</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<button class="fa fa-icon" onclick="someFunction()"></button>
</body>
</html>
JS:
<script>
function someFunction(){
$.ajax({
method: 'POST', //I've tried 'GET' here too. doesnt make a difference
url: "file.php",
success: function(result)
{
alert(result);}
});
}
</script>
As noted by the commenters below: I've also tried the following
<script>
function someFunction(){
$.ajax({
method: 'POST', //I've tried 'GET' here too. doesnt make a difference
url: "file.php",
data: {pid: 3}, // added this line
success: function(result)
{
alert(result);}
});
}
</script>
The alert is blank there is no 3 on it when the php file has echo $bla which is $_GET['pid'] and the pid in the url is = 3.
Can someone please explain why that is the case? I dont think I understand what is happening behind the scenes of the above codes to figure out why.
Please note that I'm not trying to solve a particular problem or anything just trying to understand why $_GET is not working in this very specific case.
You're not sending any data in the AJAX request, hence there's nothing for the PHP to read and send back. To fix this include a data property in the request which contains the pid key and the required value, for example:
function someFunction(){
$.ajax({
method: 'GET',
url: "file.php",
data: {
pid: 3
},
success: function(result) {
console.log(result);
}
});
}
Note that I'm using method: 'GET' here, which is important as you're using $_GET in your PHP, so a POST request won't work. Also note that I'm using console.log() to debug the value. alert() shouldn't be used for debugging as it coerces data types.
I'm trying to load the alexa rank of a website as a piece of text into a standard html file. I want to avoid setting up the whole page as php so I've created a php file called rank.php which works
<?php
$url=$_GET["url"];
$xml = simplexml_load_file('http://data.alexa.com/data?cli=10&dat=snbamz&url='.$url);
$rank=isset($xml->SD[1]->POPULARITY)?$xml->SD[1]->POPULARITY->attributes()->TEXT:0;
echo $rank;
?>
I can load this to my server and call it with something like rank.php?url=google.com
This returns a number on the screen (in this case 1). So how do I get that number into a normal <p> tag in a html document.
Ie <p>Alex rank: </p>
I'm looking into jquery and using the get method but I'm getting lost.
eg putting this in the <head></head> tags
<script>
$(document).ready(function(){
$("#div1").load("code/rank.php?url=google.com");
});
</script>
Then in my html page adding
<p>Alex rank: <div id="div1"></div></p>
doesn't work for me.
I've also tried adding the following script within the <p></p> tag.
<script type="text/javascript">
function showGetResult( name )
{
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
}
showGetResult('test');
</script>
I just want a simple solution to pull that number across.
Any help greatly appreciated.
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
I made some tests - and it seems that this is a culprit:
dataType: 'text/html'
Why:
in documentation of jQuery - at http://api.jquery.com/jQuery.ajax/
dataType allowed values:
"xml"
"html"
"json"
"jsonp"
"text"
multiple, space-separated values
I tried
dataType: 'text'
Worked for me.
Be sure to put your script tag after if you are executing it inline of your page
<p>Alexa rank: <span id="div-1"></span></p>
<script>
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
</script>
But cleaner way to do it:
<html>
<head>
<script>
// comment:
// in jQuery
// $( yourFunction )
// is a shortcut for
// $(document).ready( yourFunction )
$(function(){
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
});
</script>
</head>
<body>
<p>Alexa rank: <span id="div-1"></span></p>
</body>
</html>
In this last code I am using cache: false because I feel it is good for this case. I am using dataType: 'text' because you are expecting just a number - so why not? It just fells more KISS for me. Perhaps it will work with 'html'.
By the way - there can be another place where another mistake can be hidden:
code/rank.php?url=google.com
If you current URL is
www.example.com/somefolder/
then it will be interpreted as
www.example.com**/somefolder/**code/rank.php?url=google.com
If your current URL is www.example.com/somefolder/another/
then it will be interpreted as
www.example.com**/somefolder/another/**code/rank.php?url=google.com
My advise - you can always use Firefox or Google Chrome Developer Tools > Network to see what is returning your ajax request - a '1' or 'PAGE 404 NOT FOUND' ^_^
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text/html',
success:function(data)
{
alert(data);
document.write(data);
}
});
I made some tests - and it seems that this is a culprit:
dataType: 'text/html'
Why:
in documentation of jQuery - at http://api.jquery.com/jQuery.ajax/
dataType allowed values:
"xml"
"html"
"json"
"jsonp"
"text"
multiple, space-separated values
I tried
dataType: 'text'
Worked for me.
Be sure to put your script tag after if you are executing it inline of your page
<p>Alexa rank: <span id="div-1"></span></p>
<script>
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
</script>
But cleaner way to do it:
<html>
<head>
<script>
// comment:
// in jQuery
// $( yourFunction )
// is a shortcut for
// $(document).ready( yourFunction )
$(function(){
jQuery.ajax({
url: 'code/rank.php?url=google.com',
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
// comment: $('#div-1').html(data)
// inserts data inside $('#div-1')
$('#div-1').html(data);
}
});
});
</script>
</head>
<body>
<p>Alexa rank: <span id="div-1"></span></p>
</body>
</html>
In this last code I am using cache: false because I feel it is good for this case. I am using dataType: 'text' because you are expecting just a number - so why not? It just fells more KISS for me. Perhaps it will work with 'html'.
By the way - there can be another place where another mistake can be hidden:
code/rank.php?url=google.com
If you current URL is
www.example.com/somefolder/
then it will be interpreted as
www.example.com**/somefolder/**code/rank.php?url=google.com
If your current URL is www.example.com/somefolder/another/
then it will be interpreted as
www.example.com**/somefolder/another/**code/rank.php?url=google.com
My advise - you can always use Firefox or Google Chrome Developer Tools > Network to see what is returning your ajax request - a '1' or 'PAGE 404 NOT FOUND' ^_^
Answering comment:
Yes, you've got the gist of it right.
Here is one way how you could implement it
(it would be comfortable for my way of thinking and organizing code):
<html>
<head>
<script>
// defining tool:
function updateRankForSite( inUrl, $inInsertTo ) {
$.ajax({
url: 'code/rank.php?url=' + inUrl,
type: 'get',
dataType: 'text',
cache: false,
success: function(data)
{
alert(data);
$inInsertTo.html(data);
}
});
}
</script>
<script>
// using tool:
$(function(){
outputRankForSite( 'google.com', $('#rank-google') );
outputRankForSite( 'yandex.com', $('#rank-yandex') );
// and here is example how to interact with user
$('button-1').click( function( event ) {
// comment
// event.preventDefault() blocks default behavior
// for clicking on ... tag
// that means you wouldn'd be redirected to href
event.preventDefault();
outputRankForSite(
'stackoverflow.com',
$('#rank-stackoverflow')
);
// comment:
// and you can leverage not just 'stackoverflow.com'
// but anything that user wants - he can
// put his request to <input="text" id="example-input" ...>
// and you could collect his input by using command like
// $('#example-input').val()
});
});
</script>
</head>
<body>
<p>Alexa rank for google.com: <span id="rank-google"></span></p>
<p>Alexa rank for yandex.com: <span id="rank-yandex"></span></p>
<p>
Alexa rank for stackoverflow.com (press button to get rank):
<span id="rank-stackoverflow"></span>
</p>
Press this button to update rank
</body>
</html>
I have a complex website setup so I'll just make an example a simple one.
Current Setup
I have two buttons.
<a id="one" href="#">Link 1</a>
<a id="two" href="#">Link 2</a>
And I have two divs
<div id="showOne" style="display:none">1</div>
<div id="showTwo" style="display:none">2</div>
This is my JQuery code
$('#one').click(function (e) {
$('#showOne').show();
});
$('#two').click(function (e) {
$('#showTwo').show();
});
What I'm Trying to Accomplish
Basically, I have a database table setup that has a row to count how many times was div(showOne) and div(showTwo) shown.
How would I work with AJAX to add one to the database row aka counter if display = block?
My Attempt
$('#one').is(":visible")
{
$.ajax({
type:"POST"
url: update.php
data: {type:link_one_shown}
success: function(data){
alert("Test");
}
})
When I do this, the rest of my JQuery code crashes. Not sure if this doesn't make sense or I just wrote something wrong.
Thank you in advance!
Three problems that I can see:
As Akam notes, you've mangled the if statement.
The data isn't correct -- link_one_shown should be either a variable (which you haven't defined?) or a string literal.
You're missing commas between the ajax function parameters.
Here's the modified code:
if ($('#showOne').is(":visible")) {
$.ajax({
type:"POST",
url: update.php,
data: { type: "link_one_shown" },
success: function(data){
alert("Test");
}
});
}
why not just move ajax call to function and invoke it when show the div, this avoids code repetition and makes it simpler.
$('#one').click(function (e) {
$('#showOne').show();
updateDB('link_one');
});
$('#two').click(function (e) {
$('#showTwo').show();
updateDB('link_two');
});
function updateDB(link)
{
$.ajax({
type:"POST"
url: update.php
data: {type:link}
success: function(data){
alert("Test");
}
});
}
Am a noob so hope you can help!
I've got the following jquery code:
$("#single-home-container").html(post_id);
It then displays the value I want within the HTML on the page:
<div id="single-home-container"></div>
What I would like is to pass the value into a PHP variable to I can use the info in a MySQL query.
How do I do so? It's in WordPress so no separate files
Thanks
You can use jQuery.post() or jQuery.ajax().
Here some examples:
<script>
$.post("test.php", { "func": "getNameAndTime" },
function(data){
console.log(data.name); // John
console.log(data.time); // 2pm
}, "json");
</script>
<script>
$.ajax({
url: "test.html",
context: document.body,
success: function(){
$(this).addClass("done");
}
});
</script>
You'd need to use ajax. Something like this:
JQuery:
$('.locationID').click(function(){
var post_id = $(this).attr('rel'),
$container = $("#single-home-container");
old_html = $container.html();
$container.html('loading...');
$.ajax({
url : '/path/to/php/file.php',
data:{"post_id":post_id},
type: 'post',
dataType: 'json',
success: function(data){
$container.html(data.postBody);
},
error: function(data){
// possibly notify the user of the error
$container.html(old_html);
}
});
});
That assumes you have a field in your posts table called postBody
PHP
<?php
header('Content-type: application/json');
// $query_result = do mysql query with $_POST['post_id']
echo json_encode($query_result);
exit();
?>
That assumes that you want all the fields and you're returning all the fields, including postBody - and of course you have PHP 5.2.6+ or whatever version they added json_encode().
I want to post the PHP variables $uid and $submissionid to the file fblike.php. Is the Ajax below formatted correctly to do this?
<?php
ob_start();
session_start();
$uid = $_SESSION['loginid'];
$submissionid = mysql_real_escape_string($_GET['submissionid']);
$_SESSION['submissionid'] = $submissionid;
?>
<head>
<script type='text/javascript' src='jquery.pack.js'></script>
<script type='text/javascript'>
$(function(){
$("a.connect_widget_like_button").live(function(){
$.ajax({
type: "POST",
data: "action=vote_up&uid="+$(this).attr("uid")"&submissionid="+$(this).attr("submissionid"),
url: "fblike.php",
});
});
});
</script>
</head>
You dont really want to use expando attributes if you dont have to, especially since thise are links... i would jsut do:
Like
then you can do a simple:
$("a.connect_widget_like_button").live('click', function(e){
e.preventDefault();
$.post($(this).attr('href'));
});
Now on the php side you need to be aware of where the values will be. If you pass the values as i have done in my example they will be in $_GET (even if its a POST request). If you pass them like you did in your original post then they will be in $_POST.
You need to send the data as an array/object. Something like this should do the trick.
$(function(){
$("a.connect_widget_like_button").live(function(){
$.ajax({
type: "POST",
data: {
action: "vote_up",
uid: $(this).attr('uid'),
submissionid: $(this).attr('submissionid')
},
url: "fblike.php"
});
});
});