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

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

Related

get ajax output from filled var and print out while loading the page

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();
})

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.

Run php script from html form with Ajax request

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>

Pass id to php using JQuery

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.

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