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.
Related
Before I opened this question, I searched the entire internet on a solution. Maybe it is me or my solution. Sorry for that.
The situation is, I have a web app which is build with PHP and interacting with the database through functions. Every page is a php in which html code is executed.
The problem is, when I want to implement Ajax to update data without refreshing a page, the PHP file is not being executed when the button is clicked.
The javascript has two functions:
Alert serialized data of the button (works)
Run php script with Ajax (doesn't work)
Html Header
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- JQuery -->
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous">
Im using bootstrap-table, one of the column is a button which has the following content:
<form id="form" class="favourite-form" method="post"><input style="display:none" type="hidden" id=5 name="subject_id" value=5 ><input type="submit" name="submit" value="Button"></form><div id="response"></div>
When clicked on the button the following alert is popping up:
The script file is included in the php file:
include("favorite_ajax.html");
The script file has the following content:
$(document).on('submit', '.favourite-form', function(e) {
e.preventDefault(); //prevent a normal postback and allow ajax to run instead
var data = $(this).serialize(); //"this" represents the form element in this context
alert(data); // this alert works
$.ajax({
method: "POST",
url: "process.php", // calling this php file doens't work
data: data,
success: function(data) {
alert("Data Save: " + data);
},
error: function(jqXHR, textStatus, errorThrown) //gracefully handle any errors in the UI
{
alert("An ajax error occurred: " + textStatus + " : " + errorThrown);
}
});
});
Finally the php file has one single simple function which inserts (dummy) data. The php file is tested and does not contain any errors.
<?php
insertDummyData(1, 123);
?>
In another topic I also read checking the logs. When I press the button, there is also no record being added in the logs.
Im cursious, what am I doing wrong? Spend like days to fix this, until now no results :(
put an error log in "process.php" to make sure that it's actually being called, if it's not being called, as others suggest, you may have path, permissions or script errors.
what does insertDummyData/process.php actually do? It must echo something as if it were writing to the page for the AJAX call to get a non-empty result. For example, in process.php
<?php
$new_data = my_function_which_does_stuff_to_posted_data($_POST['data']);
echo json_encode($new_data);
exit();
I have searched for this answer and it seems that it should be simple, based on DOM.
What I want to do is display a <td id="cte"> or <input id="cte"> on a page and after some action (i.e. button click OR onchange ) the getElementById('cte').value="somenewvalue" ACTUALLY changes the forementioned or element on the same page.
The technology (i.e. javascript, AJAX, DOM) says that this is doable, yet I have seen this question asked numerous ways where the answers supplied never seem to work or satisfy the question.
So my actual question is: How do I change the 'displayed' element.value on the same page without having to reload the same page?
Do you think of elements consist several values/texts? (like a table)
//emty the element really at first if the element consists several values
var forempty = document.getElementById("cte");
while( forempty.firstChild ){
forempty.removeChild(forempty.firstChild);
}
document.getElementById("cte").value = something;
//or
document.getElementById("cte").textContent = something;
You answered your own question at least in one way: "The technology (i.e. javascript, AJAX, DOM) says that this is doable. And sure enough, with AJAX, it is only a matter of replacing the DOM Node with the Data (Response) from AJAX Request...
Here is a very Basic Example. We will fetch an HTML String using AJAX from the Server and use this Contents to replace the former Contents of a DIV, which contains the HTML < strong>Hello< /strong>
The first part of this Demo is our HTML or PHP Document containing our initial Markup and this File, we'd call index.html or index.php
CONTENTS OF index.php | index.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Mini AJAX Demo</title>
</head>
<body>
<div class="swappable-content" id="swappable-content">
<strong>Hello!!!</strong>
</div>
<div class="other-dom-elements">
<Button id="action-trigger" data-ajax-url="/ajax.php">Click Me</Button>
</div>
<!-- ADD JQUERY LIBRARY & SETUP THE AJAX REQUEST CALLS -->
<!-- HERE WE ARE LOADING JQUERY FROM THE CDN.... CHANGE THE src ATTRIBUTE IF YOU HAVE A LOCAL COPY -->
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
(function($){
$(document).ready(function(e){
var actionTrigger = $("#action-trigger");
actionTrigger.on("click", function(e){
$.ajax({
url : $(this).attr('data-ajax-url'),
type : "POST",
dataType : "JSON",
data : {
// HERE YOU CAN ADD KEY VALUE PAIRS
// WHICH WILL BE SENT TO AND PROCESSED BY THE SERVER
},
success : successHandler,
error : errorHandler,
complete : completeHandler
});
});
function successHandler(data, textStatus, jqXHR){
// IF THERE IS A RESPONSE PAYLOAD FROM THE SERVER
// WE JUST REPLACE THE CONTENTS OF THE #swappable-content DIV WITH THE DATA
if(data){
if(data.html){
$("#swappable-content").html(data.html);
}
}
}
function errorHandler(jqXHR, textStatus, errorThrown){
console.log('The following error occured: ' + textStatus, errorThrown);
}
function completeHandler(jqXHR, textStatus){
}
});
})(jQuery);
</script>
</body>
</html>
CONTENTS OF AJAX PROCESSING SCRIPT: ajax.php
<?php
// YOU CAN DO PRETTY MUCH ANYTHING WITHIN THIS FILE
// HOWEVER FOR THE PURPOSES OF THIS DEMO,
// WE WOULD JUST RETURN SOME HTML STRING BUNDLED IN AN ARRAY AND SENT AS JSON DATA
$response = array(
'html' => "<div style='font-weight:900;color:#F00;'>This is the Response Data from Server!</div>",
);
die(json_encode($response));
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.
So, I've just read online about a fairly specialized HTTP method known as HEAD, which is basically supposed to only send metadata, without sending the actual document body. It seems that jQuery supports this, but when I attempted to create it for real, the body was still sent along with the headers. When I checked in the console, Chrome told me that a head request was actually sent. Huh?
Here's the code:
<!DOCTYPE html>
<html>
<head>
<meta charset = 'UTF-8'/>
<title>Headers</title>
</head>
<body>
<script language="Javascript" type="text/javascript"
src="2-jquery-1.11.0.min.js"></script>
<script language="Javascript" type="text/javascript"
src="jquery-ui-1.10.4.custom.min.js"></script>
<script language="Javascript" type="text/javascript">
$(function() {
$.ajaxSetup({ cache: false }); // not exactly necessary for head requests
// to be used for other ajax request types
//..is this interfering?
function reloader() {
$.ajax({ type: 'HEAD', url: "chatbox.txt" })
.done(function(data, status, xmlhttp) {
console.log(xmlhttp.getResponseHeader('Last-Modified')); })
.fail(function() { alert("error!"); })
.always( function() {} ); } // end reloader
var matrix = setInterval(reloader,3000);
$('#stop').click(function() { clearInterval(matrix); alert('stopped!');
}); // end click
}); // end $(document).ready()
</script>
<button id = 'stop'>Stop</button>
</body>
</html>
Everything works fine, except for the body being sent as well. What's the problem exactly? Am I accidentally sending the body along with the request? If so, where in the code is this?
P.S. I know I can do this with PHP, but I'm interested in js/jQ.
Thanks!
I have this mark up and a json.txt file which lies on the same directory as this .im unable to fetch it contents..also im not getting any errors in my firebug
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
$.get('/json.txt',
function(data) {
$('div.result').html(data);
});
});
</script>
</head>
<body>
<div class="result"></div>
</body>
</html>
"on the same page" ? Do you mean "in the same directory" ? If so use
$.get('json.txt'
If this doesn't work, I suggest using the long form to see what happens :
$.ajax({
url: 'json.txt',
success: function(data){console.log(data)},
error: function(jqXHR, textStatus, errorThrown) {console.log(jqXHR, textStatus, errorThrown)};
});
So you can see in your console (ctrl+maj+i) the error (or the data).
Another note : this can't work if you're opening the html file in file:// as the json would be considered coming from another domain. You must have an http server and open it in http://.
If you type full path, everything works?
$.get('http://localhost/json.txt', function(data) {
});
I am trying help to detect problem
If file is local (file:///), then look jQuery: read text file from file system