Run php script from html form with Ajax request - javascript

I've been trying to make a small php script run through an ajax request. The bigger picture is that I want to store the data in an html form to my database on the click of a button, without actually submitting that form on the same click. However, since I'm new to programming, I'm trying to get the basic principles to work first.
For testing, I made a minimal example. In ajaxtest.hml, I made a button that should execute the function click(). That function is supposed to execute an ajax request to execute testing.php (located in the same folder). testing.php should just return 'Hello World'. However, the button does nothing, and I can't figure out what's wrong.
My code for ajaxtest.html:
<html>
<meta charset="UTF-8">
<body>
<button type="button" onclick="click()">Click Me</button>
<p id="p"></p>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
function click(){
$.ajax({
type: 'POST',
url: 'testing.php',
success: function(data) {
alert(data);
}
});
}
</script>
</body>
</html>
and for testing.php:
<?php
echo "Hello World"; ?>
It is probably a typical rookie mistake I'm making here, but the jungle of different posts on this and similar topics hasn't helped me so far... Any help is greatly appreciated!

There are a few things wrong with your code:
First of all, it is not a proper HTML file. Every HTML file should have a <head></head> tag and <body></body> tag within the <html></html> tag.
Secondly, you want to load your scripts in the <head> section. Where you can also define a title, meta tags, stylesheets, etc.
Thirdly, your <script>tag is wrong. You load a script and at the same time, you define a function. This should be two actions.
I think your script then will look something like:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Title of the document</title>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js">
</head>
<body>
<button type="button" onclick="click()">Click Me</button>
<p id="p"></p>
</body>
<script>
function click(){
$.ajax({
type: 'POST',
url: 'testing.php',
success: function(data) {
alert(data);
}
});
}
</script>
</html>
For information about HTML see W3schools

You should delete the parenthesis in the attribute "onclick=click()", otherwise the function will be immediately executed on page load, and this is why you are not able to see the action of the button.

I suggest this way: (replace it instead of your code into Body tag.)
<button type="button" id="ajaxBtn">Click Me</button>
<p id="p"></p>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
const btn=document.getElementById('ajaxBtn');
btn.addEventListener('click',click);
function click(){
$.ajax({
type: 'POST',
url: 'testing.php',
success: function(data) {
alert(data);
}
});
}
</script>

It seems to me that you have 3 things you need to fix:
You are missing the opening <script> tag for your function since the opening script tag you have at the moment is for the jquery library you are referencing.
Also, don't use the reserved word "click" for your function name. I have changed it below to "myfunction"
Move the function definition to an appropriate place within your page.
If you try the code below it should work. I hope this helps.
<html>
<meta charset="UTF-8">
<body>
<script>
function myclick(){
alert('posting!');
$.ajax({
type: 'POST',
url: 'testing.php',
success: function(data) {
alert(data);
}
});
}
</script>
<button type="button" onclick="myclick()">Click Me</button>
<p id="p"></p>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"/>
</body>
</html>

You can try calling the function implicitly
<html>
<meta charset="UTF-8">
<body>
<button id="testbutton" type="button">
Click Me
</button>
<p id="p"></p>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('body').on('click', '#testbutton', function(){
$.ajax({
type : 'POST',
url : 'testing.php',
success : function(data) {
alert(data);
}
});
});
</script>
</body>

Related

Handling script loading when loading page through Ajax

Is there a way to handle scripts loading through Ajax page calls? I would like to not load those already loaded in the first place by the base page as they are in conflict.
Is the solution to create multiple pages one for the normal call (with the scripts) one for the ajax ones (without the scripts that are duplicates)?
Example:
base_page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
</head>
<body>
<div id="ajax_page"> </div>
<div id="other_ajax_call"> </div>
<div id="second_result"> </div>
</script>
$(document).ready(function(){
$.ajax({
url: '/ajax_page',
type: 'GET',
success: function (result) {
$('#ajax_page').html(result)
}
});
});
$( "#other_ajax_call" ).on( 'click', function() {
$.ajax({
url: '/another_page',
type: 'GET',
success: function (result) {
$('#second_result').html(result)
}
});
});
</script>
</body>
</html>
ajax_page:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://code.jquery.com/jquery-3.4.1.slim.min.js"></script>
</head>
<body>
<div id="ajax_second_page"> </div>
</script>
$(document).ready(function(){
$.ajax({
url: '/a_third_page',
type: 'GET',
success: function (result) {
$('#ajax_second_page').html(result)
}
});
});
</script>
</body>
</html>
In this example, on the 'base_page' I load through Ajax 'ajax_page' that itself is using Ajax (this page is usually called without Ajax and therefore will need to keep the script).
The problem is that when this is done, the jquery scripts are in conflict and the second ajax call of the 'base_page' (for "#other_ajax_call") is not working and I receive the following exception :
Uncaught TypeError: $.ajax is not a function
This is a repost of Ajax call - Loading page script only if not there in the base page that was closed as I first didn't put enough details and my question was not clear enough and I have no way to reopen it.
Since you are getting the full pages anyway it doesn't make sense to do that with ajax, especially when it breaks proper HTML. What you could do is to use an iframe to display your pages, and then manage them with some simple javascript in the parent document.
For example:
<!-- iframe for one of your pages -->
<iframe id="page-foo-iframe"
title="page foo"
width="100%"
height="100%"
src="/a_third_page">
</iframe>
<script>
/*
* You can have a button, or something else, call these functions
* whenever you need to show/hide a page.
*/
function showIframePage(id) {
let page = document.getElementById(id);
page.style.display = "block";
}
function hideIframePage(id) {
let page = document.getElementById(id);
page.style.display = "none";
}
</script>
I would also suggest that you look into using a framework, in particular the JS ones like Vue/React/Angular, because they will make handling things like this a lot simpler and easier to maintain. If you have to load full documents though, iframes are the best way to do that.

Ajax: Load content to a div from another div

I am trying to use ajax to change the content of a div (as html), when a link is clicked in that same div. I am not very skilled in ajax, so I am pretty sure that this is a noob question. I have tried searching the web for solutions, but I didn't manage to make anything work.
I have a div with the id "main" and inside it I am trying to make a link with the id "link01". When "link01" is clicked, I want "main" to load content from another div in another page ("txt2"-div in site2.html). But I can't get it to work.
Firstly, this is my index.html page:
<head>
<title>site1</title>
<meta charset="UTF-8">
</head>
<body>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$('#link01').click(function() {
$('#main').load('site2.html #txt2', function() {});
});
});
</script>
<div id="main">
<a>
<div id="link01">link</div>
</a>
Main div where the content will change</div>
<br>
<br>
</body>
</html>
And this is my site2.html page:
<!DOCTYPE html>
<html>
<head>
<title>Site2</title>
<meta charset="UTF-8">
</head>
<body>
<div id="txt2">Text that will go into the main div at the index-page when link01 is clicked (contains links, images, etc)</div>
</body>
</html>
I have probably misunderstood something completeley.
There is a very bad practice way that may work... But you should really have a server side code that listens you your ajax call, and returns just the desired HTML fragment as a response. Having said that, try this, it MIGHT work (didn't check):
$(function() {
$('#link01').click(function(){
$.ajax({
url: 'site2.html',
type: 'GET',
success: function(data){
data = $(data);
var $div = $('#txt2', data);
$('#main').html($div);
}
});
});
});

jQuery trigger only occurs first time

Clicking #input multiple times will upload a file each time.
Clicking #button which in turn triggers #input will only upload a file the first time (and not at all if #input was first clicked). I will, however, open the file selector browser, just not upload the file.
Why is this, and how do I change it to allow it to be clicked multiple times?
PS. Why I wish to do so instead of just using an #input? I am using jQueryUI Dialog and wish one of the buttons to initiate the input.
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>My profile</title>
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery-ui.min.js"></script>
<script type="text/javascript" src="js/jquery.fileupload.js"></script>
<script type="text/javascript">
$(function(){
$('#button').click(function(){uploader.trigger('click');});
var uploader=$('#input').fileupload( {
url: 'upload.php',
formData: {user_id:50},
dataType: 'json',
}
);
});
</script>
</head>
<body>
<button id="button">Click</button>
<input id="input" type="file" name="name">
</body>
</html>
As far as I think, there should be a change in the order where you first initialize the variable uploader and where you register the click event on the #button.
Update
Meanwhile, initiating the uploader variable upon clicking #button each time should solve the problem:
$(function(){
$('#button').click(function(){
var uploader=$('#input').fileupload( {
url: 'upload.php',
formData: {user_id:50},
dataType: 'json',
});
uploader.trigger('click');
});
});

jQuery $.get() and $.ajax() doesn't get data from PHP

I have a script that is supposed to alert a message taken from a PHP file after a click event. I've tried both jQuery $.get() and $.ajax(), but both didn't worked.
$.ajax() works but alerts an empty message, $.get() alerts "null".
load.php
<?php
$string = "prova";
echo json_encode($string);
?>
jquery_save.js
$(document).ready(function(){
$("#carica").click(function(){
loadPHP();
});
});
function loadPHP() {
$.get( "load.php", function( data ) {
alert(data)
}, "json" );
};
index.html
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>This is just a test for Stackoverflow</title>
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery_save.js"></script>
</head>
<body>
<form>
<input style="background-image:url(img/lc-load.png);" type="submit" value="Carica" name="carica" id="carica">
</form>
</body>
</html>
In this way I get the alert but with a "null" output.
I've tried this too:
load.php
<?php
$string = "prova";
echo $string;
?>
jquery_save.js
$(document).ready(function(){
$("#carica").click(function(){
loadPHP();
});
});
function loadPHP() {
$.ajax({
type: 'GET',
url: 'load.php',
success: function(data) {
alert(data);
}
});
};
This gives me an alert with noting inside. Both ways makes the page refresh after closing the alert message (and I don't want this happens).
I used another function with $.ajax() to give variables to another PHP file without problem, but I'm not able to take variables from PHP files.
You have to prevent the default click action -
$("#carica").click(function(event){
event.preventDefault();
loadPHP();
});
Your alert does not occur because of the page redirection.
You are using a submit button which causes a submit event which isnt being handled.
try changing it like this
<input style="background-image:url(img/lc-load.png);"
type="button" value="Carica" name="carica" id="carica" />
Are you using a submit button to provide a fallback for browsers with javascript disabled? if that's the case you need to prevent the submit event

refreshing specific div using AJAX

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

Categories