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

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>

Related

basic question regarding $_GET with AJAX and PHP

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.

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

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.

Ajax request for PHP to return HTML [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 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);
}
});
}

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