The general problem:
I want to pass an id of a div element to php using the ajax function from jQuery. The whole code is in one file so the ajax function should pass the id to the same file.
What I did:
1. I took the id of the clicked element (#iamaid) and saved it
2. I tried to send it to the php code in the same file using the ajax function from jQuery
3. I tried to echo it with the post method.
What happend:
The developer console gave me an output and said that the data has been sent successfully but php said it hasn't been sent and said it is an undefined index.
I also used two different ajax functions from jQuery to pass the code but both didn't seem to work.
Here is my full code (it's all in one file):
<html>
<head>
<title>Check POST/GET-Method to same file</title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<h1>Page to check the POST/GET-Method to same file</h1>
<div id="iamaid">Click me</div>
<h1>The output</h1>
<?php
if (isset($_POST["id"])) {
echo "<p>The id is: " . $_POST["id"] . "</p>";
}
else {
echo "<p>No id found, edit code</p>";
};
?>
</body>
<script type="text/javascript">
// try it with post function
$("#iamaid").on("click", function() {
var the_id = $(this).attr("id");
$.post("", {id:the_id})
});
// try it with ajax function
$("#iamaid").on("click", function() {
var the_ajax = $(this).attr("id");
$.ajax({
url:"",
method: "POST",
data: {id:the_ajax}
});
});
</script>
<style>
body {
font-family:Verdana;
}
#iamaid {
width:100px;
height:50px;
background:black;
color:white;
}
#iamaid:hover {
cursor:pointer;
}
</style>
</html>
If any more information is needed than feel free to comment I will give you all informations you need to help me.
I looked for hours in the internet but I couldn't find any solution.
Please help me.
EDIT
I got myself an answer. It was a general misunderstanding of how php works.
Passing an id with ajax to the same file results in the same output because the file gets called again.
The solution is very simple:
Just put the output code or php code in another file then pass the id with an ajax call to the file and echo the wanted html code back and then paste it to an container
Here an example of what I mean:
HTML CODE WITH SCRIPT
<html>
<head>
<title>Check POST/GET-Method to same file</title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
</head>
<body>
<h1>Page to check the POST/GET-Method to same file</h1>
<div id="iamaid">Click me</div>
<h1>The output</h1>
<p id="output"></p>
</body>
<script type="text/javascript">
/* the id gets posted to the php file
the php file echos one line and the
echo output gets pasted into the #output container
this also works when you echo html code you just need
one main container to paste it in
*/
$("#iamaid").on("click", function() {
$.post("output.php", {id:$(this).attr("id")}, function(output) {
$("#output").html(output);
});
});
</script>
<style>
body {
font-family:Verdana;
}
#iamaid {
width:100px;
height:50px;
background:black;
color:white;
}
#iamaid:hover {
cursor:pointer;
}
</style>
</html>
PHP CODE (output.php)
<?php
echo "The id is: " . $_POST["id"];
?>
As you can see moving the php code to another file makes it much more simple and you don't need to load the whole page again because the output container is the only object that gets new content.
I hope it helped some people who got stuck with ajax and the problem to use the same page and not changing it.
this will fix your issue
$.post("", {"id":"the_id"})
As per the jQuery documentation for .post(), if you want to send a data payload then you should be using promises. In your case you can use the .done() promise to handle the response, but you should look into .always() and .fail() as well if you're interested in handling errors.
$.post(
"output.php",
{ id: $(this).attr("id") }
).done(function( data ) {
$("#output").html(output);
});
Edit: I guess I should pay attention to timestamps. This question is pretty stale.
Related
I am learning about JSON and I am having trouble displaying data from an endpoint. This first segment of code works just fine for me.
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
</head>
<body>
<div class="mypanel"></div>
<script>
$.getJSON('http://time.jsontest.com', function(data) {
var text = `Date: ${data.date}<br>
Time: ${data.time}<br>
Unix time: ${data.milliseconds_since_epoch}`
$(".mypanel").html(text);
});
</script>
</body>
</html>
Changing the script to this endpoint does not display any data. How can I show this data?
<script>
$.getJSON('https://www.halowaypoint.com/en-us/games/halo-the-master-chief-collection/xbox-one/game-history?gamertags=ice%20cold%20bepsi&gameVariant=all&view=DataOnly', function(data) {
var text = `Gamertag: ${data[0].Gamertag}`
$(".mypanel").html(text);
});
</script>
Looking into it, it seems like you need to authenticate to get this data. If no json is returned, then the callback will not run. That's why if you put anything in the callback, even console.log("HERE"), it will not reach it.
If you want to authenticate, you will need to do an ajax request. $.getJSON is just a wrapper around $.ajax anyway.
I created this ajax file. I just want to know if there is a way to load the ajax file before i type in something. This file is only to test the ajax. When u run it the html display only the search bar. if i type something it print the typed stuff of the search bar and the var second. But i want that the html file displays it from beginning and the var will change later in the final file. is there a way to run the ajax once when I open up the page and not when i start typing?
I want to print the saved var(in this case second) when i open up the page or press f5. So when i open up the page it should print out: abcd
because the variable already exist(again it is var second)
I want that the function 'keyup(function()' run on beginning to show the results of the hardcoded string
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery-3.5.1.min.js"></script>
<title></title>
</head>
<body>
<input type="text" id="search_text">
<div id="result"></div>
<div style="clear:both"></div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
$("#search_text").keyup(function(){
var search = $(this).val();
var second = "abcd";
$.ajax({
url:'checkvalues.php',
method:'post',
data:{query:search, second:second},
success: function(resonse){
$("#result").html(resonse);
}
})
})
})
</script>
<?php
if(isset($_POST['query'])){
echo $_POST['query'];
}
if(isset($_POST['second'])){
echo $_POST['second'];
}
?>
If you want to run something "immediately" in your case you can just run it in a function passed as an argument of ready function.
$(document).ready(function(){
//everything here is ran just after the event fired
//so you can just call AJAX
$.ajax({});
//or create separated function doing it and then call it
myFuncCallingAJAX();
})
I want to create a real-time log for my website.
A PHP script gets the content from data/log.txt and echoes it. Then the same process gets repeated every second via JavaScript.
I use this code to test it but have a few problems:
<html>
<head>
<title></title>
<script type="text/javascript">
window.onload = startInterval();
function startInterval()
{
setInterval("loadLog();",1000);
}
function loadLog()
{
document.getElementById('log').innerHTML = "<?php
$datei=fopen("data/log.txt","r");
while(!feof($datei))
{
$zeile = fgets($datei,1000);
echo $zeile."<br>";
}
fclose($datei);
?>";
}
</script>
</head>
<body>
Javascript refresh:<br>
<div id="log"></div>
</body>
</html>
Testing PHP seperatly:<br>
<?php
$datei=fopen("data/log.txt","r");
while(!feof($datei))
{
$zeile = fgets($datei,1000);
echo $zeile."<br>";
}
fclose($datei);
?>
The PHP snippet by itself works great. But I can't seem to get the JavaScript part to work...
Problem 1:
When I change the content of log.txt the JavaScript part does not refresh itself as I would expect. I'm a beginner with JavaScript so I might have made some obvious mistakes or have a wrong idea how I should do it.
Problem 2:
As long as log.txt consist of only one line the output works:
Javascript refresh: test1
Testing PHP separately: test1
But as soon as I add an even empty line the JavaScript part doesn't load anything.
With the help of the comments on my initial question I came up with the following code wich works great:
<html>
<head>
<title></title>
<script src="resources/javascript/jquery-3.3.1.min.js"></script>
<script type="text/javascript">
setInterval(function(){
$('#log').load('loadlog.php');
}, 2000) /* time in milliseconds (ie 2 seconds)*/
</script>
</head>
<body>
Javascript refresh:<br>
<div id="log"></div>
</body>
</html>
Testing PHP seperatly:<br>
<?php
$datei=fopen("data/log.txt","r");
while(!feof($datei))
{
$zeile = fgets($datei,1000);
echo $zeile."<br>";
}
fclose($datei);
?>
I'm new to JavaScript and AJAX, and am trying to to create a simple web app consisting of a server and a JavaScript/JQuery client. It has an input field and a button. After pushing the button, a POST request consisting of the text in the field should be sent to the server, and the page should be changed to the response from the server. If there is an error, the page should be changed to an error message.
Here's my partial solution:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
.input {
width: 600px;
height: 100px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#send").click(function(){
$.post("http://localhost:8080/Web/", $("#text").val(), function(result, status){
$( "#content" ).html(result);
});
});
});
</script>
</head>
<body>
<div id="content">
<textarea class="input" id="text" placeholder="Write text to send to server" textarea rows="4" cols="50"></textarea>
<p>
<button id ="send">Send request</button>
</div>
</body>
</html>
This does not change the content of the page to the response from the server (which I've tested works). Putting in an alert except of changing the content of the page also doesn't work. I've read up a bit on AJAX JQuery, but didn't seem to manage to get it right.
Thank you
You can read the API Docs
The AJAX post method must have key valued object, e.g:
{ text : $("#text").val() }
or Form Data object in the second parameter.
I hope this helped.
I'm totally new to AJAX, so I'm sorry if the question turned out to be too stupid or anything.
Alright then, here goes...
assuming that http://example.com/index.php file have the following content:
<HTML>
<HEAD>
<title>Ajax Test</title>
</HEAD>
<BODY>
<!-- Other contents which don't need to change -->
<a class="puke" href="#">Button</a>
<div class="rainbow"><?php echo mt_rand(0,100); ?></div>
<!-- Other contents which don't need to change -->
</BODY>
</HTML>
I want to make it so that whenever a.puke is clicked, only the content of div.rainbow will get refreshed.
How can I achieve such result?
thank you.
Since your are new to AJAX, here is the code example for ajax and php- ajax php . Refer this link
$.ajax({
url: "http://example.com/index.php",
type: "GET",
cache: false,
success: function(data){
$("div.rainbow").html(data);
}
});
you can use .responseText
document.getElementsByClassName("puke").onclick = updateDiv();
function updateDiv() {
upd=new XMLHttpRequest();
upd.open("GET","test.php?action=something" , false);
upd.send();
console.log(upd.responseText);
document.getElementsByClassName("rainbow").innerHTML=upd.responseText;
}
this is how you get contents of test.php?action=something and put it to
div.rainbow