I have a simple PHP code:
<?php
$numbers = range(1,100);
while(count($numbers)>3){
unset($numbers[array_rand($numbers)]);
}
print "Numbers: ".implode(', ',$numbers)
?>
I want to create a HTML file that will use ajax to get the numbers my php code prints and show them on the HTML file.
This is my HTML so far:
<!DOCTYPE html>
<html>
<body>
<script language = "javascript" type = "text/javascript">
function ajaxFunction(){
var ajaxRequest;
ajaxRequest.open("GET", "index.php", true);
ajaxRequest.responseText;
ajaxRequest.send();
}
</script>
</body>
</html>
What do I have to change to make it work? Thanks!
$.ajax({
type: "GET",
url: 'index.php',
beforeSend: function () {
},
success: function (data)
{
$('body').html(data); // show data whereever you want - this case: on body
}
});
W3Schools PHP Ajax Link
And also see to that If you are using IE browser you should be using ActiveXObjects.
Related
I tried all the stackoverflow posts about this, I spend two days and still no success 😔, I am trying to pass a JavaScript variable to a PHP variable, I tried this for example and still not succeed, it does not print noting on the screen, here is a full code:
here cc.html:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//treehouse code
var $my_variable = "something";
$.ajax({
url: 'cc.php',
data: {x: $my_variable},
type: 'POST'
});
});
</script>
</body>
</html>
and here cc.php:
<?php
if(isset($_POST['x'])){
echo $_POST['x'];
}
?>
What should I do?
You don't do anything with the result of the AJAX call. Add a callback function:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<script>
$(document).ready(function(){
//treehouse code
var $my_variable = "something";
$.ajax({
url: 'cc.php',
data: {x: $my_variable},
type: 'POST'
}).done(function (result) {
alert(result); // <--- do something with the result
});
});
</script>
</body>
</html>
And your PHP code remains unchanged:
<?php
if(isset($_POST['x'])){
echo $_POST['x'];
}
?>
What you do in that callback function is up to you. You can alert() the value, log it to the console, write it somewhere on the page, etc.
If you want to print it on the screen you should use success: function(data)$('#result').html(data)} here is code example:
$(document).ready(function() {
$('#sub').click(function() {
var $my_variable = "something";
$.ajax({
url: 'cc.php',
type: 'POST',
data: { x: $my_variable },
success: function(data) {
$('#result').html(data)
}
});
});
});
You can try $.post too
$.post( "cc.php", { x: $my_variable} );
I want to increment count field in database when a link is clicked in php file.
So, I've added the following jquery part to my .php file. But still, it doesn't work. Please help!
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
You made a several mistakes in your code.
Update
You can send your SID input type text from ajax with data and you can get the value in your php file with the $sid = $_POST['sid'].
<body>
click here
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
After the ajax success response you can make redirect to your desire location.
Code.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
in code.php in mysqli_close you should use $conn not $connection.
Go with this code. It might help you. I have just tested all the things in localhost. This is working perfect.
use preventDefault() when click event is called.check jquery :
<body>
click here
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
Redirect your link on ajax success. Like this -
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>
On my website I am trying to basically generate a random code (which I will set up later) and then pass that code into a PHP file to later retrieve it when the client needs it. But my code just isn't working.
Here is the code:
Javascript/HTML:
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
PHP:
<?php
$code = $_POST['code'];
echo $code
?>
So what I understand that is supposed to happen is that the code is uploaded or 'posted' to the php file and then the #result is the echo $code. None of that happens and I have no idea.
Your code working perfect with some basic changes.
You need a html element with id 'result'.
And then you need to call your init() as per requirement.
<div id="result"></div>
<script>
function init() {
var code = "12345";
$.ajax({
type: 'POST',
url: 'codes.php',
data: { code: code},
success: function(response) {
$('#result').html(response);
}
});
}
init();
</script>
I tried this on my server in the head of my document, and it worked :)
I used on complete instead of on success.
<script type="text/javascript" src="https://code.jquery.com/jquery.min.js"></script>
<script>
function init() {
$.ajax({
type: "POST",
url: "codes.php",
data: {
'code': '12345'
},
complete: function(data){
document.getElementById("result").innerHTML = data.responseText
},
});
}
init();
</script>
with codes.php the same as you have :)
just a few notes:
Make sure you point your url to the correct file. You can check it by using the console network. Or you can simply print anything out, not just the $_POST data. e.g:
echo 'Test info';
Open browser developer panel, to see if is there any client code issue. For example, document with id 'result' existed, or you have not included jquery in. The developer console will tell you everything on the client side. For Chrome, check it out here https://developer.chrome.com/devtools
Have you actually called init() ?
I currently have a problem with php and javascript. Here is the thing : I'm trying to edit every few second a text file stored on the server, with the text the client wrote in a textarea (which id is 'area1')
The PHP :
<span id="write">
<?php
if(isset($_POST['text']))
{
file_put_contents('file.txt', $_POST['text']);
}
?>
</span>
The Javascript :
window.onload = function(){
t = setInterval(load, 2000);
function load()
{
$.ajax({
type: "POST",
url: "test.php",
data: {
text: $('#area1').val()
},
dataType: "text",
success: function(data) {
$('#write').load('test.php #write');
}
});
}
}
Nevertheless, nothing is ever written in file.txt, even if we enter the isset condition (that I tested).
Why isn't it working ? Can't we use jquery load with file_put_contents ? Or maybe it is a silly mistake that I can't see...
Thank you !
Have you tried using $.post? It is simpler and clearer.
Below is the full working code.
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<form>
<textarea id="area1"></textarea>
<textarea id="write"></textarea>
</form>
<script>
$(document).ready(function(){
t = setInterval(load, 2000);
function load()
{
$.post( "test.php", { text: $('#area1').val() })
.done(function( data ) {
$('#write').load('test.php #write');
});
}
});
</script>
</body>
</html>
And also make sure your php script has a privilege to add files.
Use (sudo) chown apache *folder* or similar.
Good luck!
I'm trying to write a short ajax code to echo the word 'hello' to the screen, but so far I'm not having any luck. If anyone know what I'm doing wrong, please correct me, and let me know. Thank you.
test6.html
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax() {
$.ajax({
type: "POST",
url: 'testing.php',
data:{action:'call_this'},
error: function(xhr,status,error){alert(error);},
success:function(html) {
alert(html);
}
});
}
</script>
echo hello
testing.php
<?php
if($_POST['action'] == 'call_this') {
echo "hello";
}
?>
I made some little changes to your code, like adding quotes for 'action', and creating a button because <A HREF has some issues with click event (buttons don't have those issues), here it is, now it works to me, let me know if it works to you too :
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript">
function myAjax () {
$.ajax( { type : 'POST',
data : {'action':'call_this'},
url : 'testing.php',
success: function ( data ) {
document.getElementById( "my_div" ).innerHTML = data;
},
error: function ( xhr ) {
alert( "error" );
}
});
}
</script>
</head>
<body>
echo hello
<br/><br/>
<button onclick="myAjax()">echo hello</button>
<br/><br/>
<div id="my_div"></div>
</body>
</html>
You have two problems. First, you have a syntax error. You need a comma after error:
function myAjax() {
$.ajax({
type: "POST",
url: 'testing.php',
data:{action:'call_this'},
error: function(xhr,status,error){alert(error);} /* this comma --> */ ,
success:function(html) {
alert(html);
}
});
}
Second, since you are using an anchor (<a>) tag, when you click on the tag it follows the link. You have to prevent that from happening. You can:
Not use an <a> tag
Put a href to something like # or javascript:void(0)
Make the function it calls return false
Use event.preventDefault
See it on JSFiddle
Edit:
On a side note, you may prefer to just use JavaScript to bind the event handler. This way you get a further separation of JS and HTML, which is typically preferred. Something like this should work:
$("#sendAjax").click(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: '/echo/html/',
data:{html:'call_this'},
error: function(xhr,status,error){alert(error);},
success:function(html) {
console.log(html);
$("#result").text(html);
}
});
});
Then in your HTML you don't need the onclick handler:
echo hello
See it on JSFiddle