Echoing to the screen using AJAX PHP - javascript

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

Related

how to update a value in database using jquery when a link is clicked in php

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>

How to make ajaxRequest with PHP and Javascript

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.

JQuery AJAX call to php function

I am trying to replace page reloading PHP scripts in a web page with AJAX calls.
I am using JQuery to run the AJAX scripts but it doesn't seem to be doing anything so I attempted to write an incredibly basic script just to test it.
My directory is as follows
public_html/index.php
/scripts/phpfunctions.php
/jqueryfunctions.js
index.php contains
<!DOCTYPE html>
<html>
<head>
<!-- jquery functions -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="scripts/jqueryfunctions.js"></script>
<!-- php functions -->
<?php include 'scripts/phpfunctions.php' ?>
</head>
<body>
<button type="button" id="testButt">TEST</button>
</body>
</html>
Then the phpfunctions.php page which I am trying to call contains just an echo if an argument is set
<?php
if(isset($_GET["action"])) {
echo "test has been run";
}
?>
The jqueryfunctions.js script I am trying to run is
$(document).read(function () {
$('#testButt').on('click', function () {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test',
type: 'GET',
success: function (data) {
$('#ajaxdata').html(data);
},
error: function (log) {
console.log(log.message);
}
});
});
});
I see that the jqueryfunctions.js function is being called by the first console.log but it doesn't seem to be calling my phpfunctions.php function.
I was expecting to see the php echo "test has been run" but this doesn't happen.
Did I miss something?
You should use isset() method:
<?php
if(isset($_GET["action"])) {
if($_GET["action"] == "run_test") {
echo "test has been run";
}
}
?>
and if you are using ajax then why do you need to include it on index page:
<?php include 'scripts/phpfunctions.php' ?>
and i can't find this element $('#ajaxdata') on your index page.
Also you can check the network tab of your inspector tool to see the xhr request to the phpfunctions.php and see if this gets successfull or there is any error.
I think problem is here:
$(document).read(function() {
$('#testButt').on('click', function() {
console.log("jquery call worked"); // this bit does run when button is clicked
$.ajax({ // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php',
type: 'GET',
data: {action:'run_test'}, // <------ Here
success: function(data) {
$('#ajaxdata').html(data);
},
error: function(log) {
console.log(log.message);
}
});
});
});
jQuery says:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting.
So you should set data: {key:'value'}
Most things look fine, but your data attribute is designed for "POST" requests, try to add the data to the url as follows:
$( document ).read( function ()
{
$( '#testButt' ).on( 'click', function ()
{
console.log( "jquery call worked" ); // this bit does run when button is clicked
$.ajax( { // this bit doesn't seem to do anything
url: 'scripts/phpfunctions.php?action=run_test', // Add the GET request to the end of the URL
type: 'GET',
//data: 'action=run_test', Unrequired noise :P (this is for post requests...)
success: function ( data )
{
$( '#ajaxdata' ).html( data );
},
error: function ( log )
{
console.log( log.message );
}
} );
} );
} );
And also (as mentioned in my comments), you need to finish your bodys closing tag:
</body> <!-- Add the closing > in :P -->
</html>
I hope this helps :)
Where do you load ajaxfunctions.js? It look like in your code you never load the resource
And change
<button id="xxx">
In
<button type="button" id="xxx">
So the page isn't reloaded

file_put_contents with jquery reload?

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!

Not entering into click function

The control is not passing into click event so can anyone please suggest whats wrong with the code below and any tutorial on this wil be of great help.
Code:
<html>
<head>
<script src="jquery-1.9.1.js"></script>
<script type="text/javascript">
$("#submit").click(function(event)
{
alert("hi");
$.ajax({
type : "POST",
url : "https://xxxxx/xxx.php",
data : {"email": "jason.charity#icloud.com", "password": "people4455!", "application":"rex"},
success : function(response) {
data = jQuery.parseJSON(response);
console.log(data);
}
});
</script>
</head>
<body>
<form id="myForm">
<input type="submit" id="submit" value="submit">
</form>
</body>
</html>
Two issues:
You're missing }); from the end of your code, so it has a syntax error. (I didn't realize that until I went to run your code through http://jsbeautifier.org/ so I wasn't posting a mess below. Which shows the value of making sure you use reasonable, consistent code formatting!)
(If you fix that.) When you do your $("#submit"), the element doesn't exist yet, and so that doesn't match any elements. Just move the script block below the element in the HTML (this is generally the recommendation, put your script just before the closing </body> tag).
Fixing both:
<html>
<body>
<form id="myForm">
<input type="submit" id="submit" value="submit">
</form>
<script src="jquery-1.9.1.js"></script>
<script type="text/javascript">
$("#submit").click(function (event) {
alert("hi");
$.ajax({
type: "POST",
url: "https://xxxxx/xxx.php",
data: {
"email": "jason.charity#icloud.com",
"password": "people4455!",
"application": "rex"
},
success: function (response) {
data = jQuery.parseJSON(response);
console.log(data);
}
});
}); // <== This was the missing bit
</script>
</body>
</html>
Side notes:
If your server responds with the correct content type, you don't need parseJSON in your success handler; jQuery will automatically parse the JSON if the server says that's what it is.
Using a doctype is a really, really, really, really good idea. Put <!doctype html> at the top of the document.
Wrap your function within document.ready function:
$(document).ready(function(){
//your code here
});
Or,
$(function(){
//your code here
});
And also you are missing }); at last line of code which would throw an error as mentioned by #T.J. Crowder
you can also use recommended approach, i.e. event delegation on document
$(document).on("click","#submit",function(event)
{
alert("hi");
$.ajax({
type : "POST",
url : "https://xxxxx/xxx.php",
data : {"email": "jason.charity#icloud.com", "password": "people4455!", "application":"rex"},
success : function(response) {
data = jQuery.parseJSON(response);
console.log(data);
}
});
});
Put your click into
$(document).ready(function(){
$("#submit").click(function(event)
{
alert("hi");
$.ajax({
type : "POST",
url : "https://xxxxx/xxx.php",
data : {"email": "jason.charity#icloud.com", "password": "people4455!", "application":"rex"},
success : function(response) {
data = jQuery.parseJSON(response);
console.log(data);
}
});
});
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(event){
alert("hi");
$.ajax({
type : "POST",
url : "https://xxxxx/xxx.php",
data : {"email": "jason.charity#icloud.com",
"password": "people4455!", "application":"rex"},
success : function(response) {
data = jQuery.parseJSON(response);
console.log(data);
}
});
});
});
</script>
you missed closing "});", Try this script.

Categories