Ajax request for PHP to return HTML [closed] - php

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
I have an element on a page that when clicked will make an ajax request to a receiver.php file:
<script>
function send(id){
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id}
});
}
</script>
<img src="foo.bar" onclick="send(id)"/> <!-- simplified -->
My idea is that this receiver.php file will receive the id, then output a whole page of HTML based on that id
However, when I click on the element, the new HTML page that I expect doesn't show up. When I go to the Chrome inspector, Network tab I can see the request and the response is exactly the HTML content I need, but why doesn't it change to that new page and stay on the old page instead?
EDIT: This is my receiver.php, for testing purpose:
<html>
<head></head>
<body>
<?php
echo "<p>".$_POST['comid']."</p>";
echo "<p> foo foo </p>";
?>
</body>
</html>
this is the response:
<html>
<head></head>
<body>
<p>3</p><p> foo foo </p> </body>
</html>

Perhaps in your receiver.php script you're doing something like this, where you determine which HTML page to output depending on the id that it is receiving.
switch ($_POST['id']) {
case 'foo':
$filepath = 'bar';
break;
...
}
readfile($filepath);
You would have to reflect that in your AJAX query, using the success function of $.ajax.
function send(id) {
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id},
success: function (data) {
// Replace the whole body with the new HTML page
var newDoc = document.open('text/html', 'replace');
newDoc.write(data);
newDoc.close();
}
});
}

You have to do something with the result that comes back from you AJAX call:
function send(id){
$.ajax({
type: 'POST',
dataType: 'html',
url: 'receiver.php',
data: {id: id},
success: function(data){
console.log(data);
}
});
}

Related

Getting JSON data with jquery ajax not working [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I'm trying to understand how to fetch and display data with jquery ajax. I have a php page (data.php)that successfully retrieves data from a mysql database and encodes that data into a json array. Client side I have a page called get.php. I just can't figure out why my script will not fetch any data from data.php I get nothing in the firebug console.
data.php
echo json_encode($mydata);
which outputs:
[
{
"id":"236",
"title":"The Jungle Book"
},
{
"id":"235",
"title":"The Shallows"
},
{
"id":"232",
"title":"For Your Eyes Only"
},
{
"id":"231",
"title":"Ice Giants"
}
]
get.php
<script>
("button").click(function(){
{
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var title = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
</script>
<h3>Output: </h3>
<button>Get Data</button>
<div id="output"></div>
You have few mistake like: you didn't specify jquery($) for button
selector, you use multiple bracket { inside click function, inside
ajax success you have assigned full object against id and title it
should be id=data[0]['id'] and title=data[0]['title] and another
mistake there no defined variable vname. php better json output you should use header('Content-Type: application/json'); in data.php.
Try this:
index.php
<h3>Output: </h3>
<button>Get Data</button>
<div id="output"></div>
<script src="https://code.jquery.com/jquery-2.2.4.min.js" integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44=" crossorigin="anonymous"></script>
<script>
$("button").click(function(){
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data){
//console.log(data);
var id = data[0].id;
var title = data[1].title;
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+title);
}
});
});
</script>
data.php
<?php
header('Content-Type: application/json'); //use header to specify data type
//echo json_encode($mydata); // un-comment this line
echo '[{"id":"236", "title":"The Jungle Book"}, {"id":"235", "title":"The Shallows"}, {"id":"232", "title":"For Your Eyes Only"}, {"id":"231", "title":"Ice Giants"} ]'; // comment this line
?>
<script>
$("button").click(function()
{
$.ajax({
url: 'data.php',
data: "",
dataType: 'json',
success: function(data)
{
var id = data[0];
var title = data[1];
$('#output').html("<b>id: </b>"+id+"<b> name: </b>"+vname);
}
});
});
try like this

Load contents of alexa php results with parameters into html page - Maybe using jquery or ajax

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>

Data doesn't transfer to PHP from Ajax [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm trying to pass data that comes from a prompt, but the PHP doesn't receive the data.
<script>
function test(){
var r=prompt("blaksasda");
if(r){
$.ajax({
type: "POST",
url: "file.php",
data: {
param:r,
}
});} };
</script>
PHP file:
<?php
echo "$_POST['param']";
?>
Are you sure PHP doesn't receive the data? Probably Ajax call works correctly. The problem is that you don't handle the echoed result.
Try the following:
$.ajax({
type: "POST",
url: "file.php",
data: {param: r}
}).done(function(result) {
alert(result);
});
Ok, let me add the whole thing.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
function test(){
var r=prompt("blaksasda");
if(r){
$.ajax({
type: "POST",
url: "test.php",
data: { param: r }
}).done(function(result){
alert(result);
}).fail(function(result){
alert('failed: ' + result);
});
}
}
</script>
</head>
<body>
<button onclick="test()">Click me!</button>
</body>
</html>
test.php looks like this
<?php
if (isset($_POST['param'])) {
echo $_POST['param'];
} else {
echo 'Whoops';
}
So when I click on the button 'Click Me', it's going to call the test function and give you a prompt and you type the text in and when you submit, you get the result back from test.php. I tried it and it worked fine.
UPDATE:
Instead of doing an alert in the success handler, just set the result like this:
.done(function(result){
$('#result').html(result);
});
Your page will look something like this. Whatever you get from your page, your span will have that. Hope it makes sense.
<body>
<button onclick="test()">Click me!</button>
<br/>
Prompt result: <span id="result"></span>
</body>

refreshing php content inside div when input onchange [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have a simple <input> and when user writes there something I need to refresh php inside div so it will look like some.php?key=thevaluefrominput. How would I do that? I guess I need to use query but I'm not sure how.
I want something like this when you write something to Type to find tags it changes the the tags bellow.
Thanks for the answers.
This sounds like a job for AngularJS :)
However this is jQuery solution:
$(function () {
$('form').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape($.trim($('#myinputfield').val())),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
});
});
If you mean that while user types (before submission), div content changes? Then remove
$('form').submit(function (e) {
e.preventDefault();
and instead put
$('#myinputfield').keydown(function () {
There is a setInterval method that I mentioned in comment, so the first chunk of code I posted, replace it with this one:
$(function () {
var old_val = '';
var curr_val = '';
setInterval(function () {
curr_val = $.trim($('#myinputfield').val());
if (old_val != curr_val) {
old_val = curr_val;
$.ajax({
type: 'POST',
url: 'some.php',
data: 'key=' + escape(curr_val),
dataType: 'html'
}).done(function (data) {
if (data) {
$('#divtopresent').html(data);
}
});
}
}, 2000);
});
It checks if value of the field changed every 2s, please replace amount in ms (2000) if you like.

Executing a php file onClick

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

Categories