How to run simple php code with jquery/ajax? - javascript

Because my actual example is way too big I made a very short example:
test1.php
<!DOCTYPE html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script> <!--jQuery-->
<body>
<p> What is the first letter of the alphabet?</p>
<button type="button" id="button">Tell me!</button>
<div id="div"></div>
<script>
$(document).ready(function(){
$('#button').click(function(){
$.ajax({
url: 'test2.php',
success: function() {
$('#div').html();
}
});
});
});
</script>
</body>
</html>
test2.php
<?php
echo "It's the letter A!";
?>
I want to this to print out "It's the letter A!" when I hit the button, which does not seem to work. Could somebody help end tell me why this doesn't work and how to fix it?
Thanks

1st : Should be enclosed by quotes $('#button')
2nd : Get the response in success function like this.
success: function(res) {
$('#div').html(res);
}
3rd : Set data type to text .
dataType:'text'
Update 1:
$(document).ready(function(){
$('#button').click(function(){
$.ajax({
url: 'test2.php',
dataType:'text',
success: function(res) {
$('#div').html(res);
}
});
});
});

Its because you haven't output the result you got from ajax.
<script>
$(document).ready(function(){
$("#button").click(function(){
$.ajax({
url: 'test2.php',
success: function(data) { //<---result from ajax
$('#div').html(data); //<----add result to div element
}
});
});
});
</script>

If your script is only a call of a page without GET/POST arguments, the simpliest way with jQuery is $.load() :
<script>
$(document).ready(function() {
$('#button').click(function() {
$.load("test2.php #div");
});
});
</script>
doc here : http://api.jquery.com/load/

Related

Passing variables to a page with AJAX and returning those variables in PHP

I'm trying to do something I would think would be really simple: Pass form data to a PHP page with AJAX, and get the result of the PHP back.
Edited to Add: As written right now, it only returns successfully sporadically, rather than every time it's run, for some reason.
Edited to Add (05/30/2020):
I was able to get it working such as it is by changing the ajax like this:
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("#Manager_Review").val();
var dataTosend='?DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review;
$.ajax({
type: "GET",
url:'showme.php' + dataTosend,
data:dataTosend,
async: false,
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = data;
},
error: function(data){
document.getElementById('txtresponse').innerHTML = "failure.";
}
});
});
});
</script>
Now I have to work on serializing the form, because it's actually multiple rows I have to pass. I don't know if I need that as a second question, though.
This is my main page:
<html>
<head>
<script src="Scripts/jquery.min.js"></script>
<script src="Scripts/jquery-2.1.3.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.plugin.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.datepick.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
var DDD_Number=$("#DDD_Number").val();
var Manager_Review=$("Manager_Review").val();
var dataTosend='DDD_Number='+DDD_Number+'&Manager_Review='+Manager_Review;
$.ajax({
type: "POST",
url:'showme.php',
data:dataTosend,
async: true,
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = "Successful.";
},
error: function(data){
console.log(data);
document.getElementById('txtresponse').innerHTML = "failure.";
console.log(data);
}
});
});
});
</script>
</head>
<body>
<form id="dddform" method="post">
<input type="text" id="DDD_Number" name="DDD_Number"><br>
<input type="text" id="Manager_Review" name="Manager_Review"><br>
<button id="button" name="Submit">Click Me</button>
</form>
<div id="txtresponse"></div>
<div id="thisworks"><?php if(!isset($_POST['Submit'])){echo $Manager_Review;} ?></div>
</div>
</body>
</html>
This is showme.php:
<?php
$Manager_Review_Date = $_POST['Manager_Review'];
echo $Manager_Review_Date;
?>
<script language = 'Javascript'>
document.getElementById('thisworks').innerHTML = '<?php echo $Manager_Review_Date; ?>';
</script>
The call is made successfully. (The "Success"and "Successful" messages appear), but I can't get the value of $Manager_Review_Date to appear in the "thisworks" DIV.
Any pointers? I'm fairly new to AJAX (if you couldn't tell from my code).
Your php should be:
<?php
$Manager_Review_Date = $_POST['Manager_Review'];
echo $Manager_Review_Date;
// NO javascript here
And the output of this script is in data variable of success callback:
success:function(data){
document.getElementById('txtresponse').innerHTML = "Success.";
document.getElementById('thisworks').innerHTML = data;
},

Ajax not able to post javascript variable to php

I want to post values of a JavaScript variable to a PHP page, and then use those values there.
I get back a new HTML page, which I did not want to happen. Also, it is showing the error message produced by:
echo"some error";
What am I missing? I don't understand why this happens?
Here is my html file try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
And this is my PHP file try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
In try.php if you echo something which in turn will comeback to try.html.
If you just want to post the data to try.php and echo there the just use form and submit. You dont need ajax in that.
Ajax is to send the data/receive back without reloading the existing page. The response will be seen in the current page itself.
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
In the try.php page you can place this code
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
Firstly, remove script from data-type.
This is how you can pass the data to php file:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - The type of data that you're expecting back from the
server. Here you don't want anything in return then it's fine. If you
are expecting anything like json or something, you can specify it.
If You want anything in response, you can handle in this manner
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - A callback function to be executed when Ajax request
succeeds.
Firstly remove href from link. By this it is directly redirecting to try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>

Calling ajax on the same page

I am trying to call ajax on the same page without click event, I am getting the following error:
Notice: Undefined index: name in index.php on line
It works fine with the click event. I am trying to do it without any events. My goal is to pass JavaScript variable to PHP.
<script>
$(document).ready(function(){
alert('est123');
$.ajax({
type: 'POST',
url: 'index.php',
data: ({name:"test"}),
cache: false,
success: function(data){
$('#results').html(data);
}
})
return false;
});
</script>
</head>
<body>
click me!
<div id="results"></div>
<div><?php echo $_POST['name'] ?></div>
</body>
</html>
Check to see if it exists before outputting it
if (isset($_POST['name'])) { echo $_POST['name'] }
BUT I do not think this is what you want to happen since you will be sticking the HTML document returned into the page.
I think this might help you.
<script>
$(document).ready(function(){
dataArray={name:"test"};
$.ajax({
type: 'POST',
url: 'index.php',
data: dataArray,
cache: false,
success: function(data){
$('#results').html(data);
$('#lblName').html(dataArray.name);
}
})
return false;
});
</script>
</head>
<body>
click me!
<div id="results"></div>
<div id="lblName"></div>
</body>
</html>

Trigger successhandler from ajax call when someone clicks a button

I have an ajax call which grabs data from a php file that connects to an api. I have a success handler that receives the data from the ajax call and then loads a function from the API library. The issue is, I want the user to click a button and then run the function inside of the success call (using the same data from the ajax call earlier).
I believe my ajax call needs to stay inside the window.onload = function(), it doesn't work if I try to run the ajax call when the user clicks the button.
<html>
<head>
<title>hi</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script>
function hello(){
alert("hi");
}
function successHandler(data){
screenleap.startSharing('DEFAULT', data, {
nativeDownloadStarting: hello
});
}
window.onload = function() {
$.ajax({
type: "POST",
url: "key.php",
data: '',
success: successHandler,
dataType: "json"
});
};
</script>
</head>
<body>
<input type="submit" value="submit" id="submit">
</body>
</html>
Please let me know how I can do this, any help would be greatly appreciated.
Update:
so I have tried adjusting my code, but for some reason nothing happens anymore when I click the button. It doesn't even shoot out my console.log confirming I had even clicked the button.
<html>
<head>
<title>hi</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://api.screenleap.com/js/screenleap.js"></script>
<script>
var dataFromServer;
function hello(){
alert("hi");
}
function successHandler(data){
dataFromServer = data;
console.log("data from server: ")
console.log(dataFromServer);
}
window.onload = function() {
$.ajax({
type: "POST",
url: "key.php",
data: '',
success: successHandler,
dataType: "json"
});
};
$("#submit").click(function(){
console.log('clicked submit');
if(dataFromServer)
{
console.log(datafromserver);
screenleap.startSharing('DEFAULT', dataFromServer, {
nativeDownloadStarting: hello
});
}
});
</script>
</head>
<body>
<input type="submit" value="submit" id="submit">
</body>
</html>
all the best,
-- 24x7
You can store data to some global variable and on button click use same variable.
var dataFromServer;
function successHandler(data){
dataFromServer = data;
}
jQuery("#submit").click(function(){
if(dataFromServer)
{
screenleap.startSharing('DEFAULT', dataFromServer, {
nativeDownloadStarting: hello
});
}
});
Update:
Instead of window.onload use jquery onload function to populate data.
http://jsfiddle.net/ZGggK/
$(function() {
$.ajax({
type: "GET",
url: "https://api.github.com/users/mralexgray",
data: '',
success: successHandler,
dataType: "json"
});
});

jQuery ajax calling javascript function

I am using jQuery and Ajax.
My MainFile has the following code:
<html>
<head>
<script src="Myscript.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
type: 'POST',
url: 'ajax.php',
success: function(data){
$("#response").html(data);
}
});
});
</script>
<body>
<div id="response">
</div>
</body>
</html>
My ajax.php get the sample data
...
MyScript.js has the following
function display (text,corner)
{
}
..
I have Myscript.js. In this, I have a function called display(text,corner). I have to call this function after executing ajax.php.
How do I do it in jQuery for the above code?
Is it possible to decide the order of execution after ajax.php and make call for display(text,corner)?
You should invoke the display function in the callback function of the Ajax Request, like such:
$.ajax({
type:'POST',
url: 'ajax.php',
success: function(data){
display(data, /* your other parameter, corner */); //Invoking your data function
}
});
In the above case, data is the response that is received from ajax.php

Categories

Resources