How to call a php function on button click with one param - php

I want to call a php function with one param, id of a button, when I press that button.
This is what I tried:
<!DOCTYPE html>
<html>
<body>
<?php
include ("sterge2.html");
<button onclick="writeMsg(this.id)">Click me</button>
function writeMsg($id) {
echo $id."Hello world!";
//add that id in a database...
}
?>
</body>
</html>
But it does nothing...

you can not combine javascript and php. instead of it use ajax.
try below ajax code..
<button class="btnsubmit" id="submit" data-id="5" >Click me</button>
$(".btnsubmit").click(function() {
var id = $(this).attr('data-id');
$.ajax({
url : URL+'writeMsg',
type : 'POST',
data : {'id': id},
success : function(data)
{
}
});
});
and in writeMsg function perform database opertaion.
i hope this code will help you.

Try this:
<!DOCTYPE html>
<html>
<body>
<?php
include ("sterge2.html");
echo '<button onclick="writeMsg(this.id)">Click me</button>';
?>
<script>
function writeMsg(id) {
alert(id + "Hello world!");
// Use AJAX to call PHP file and save id into DB
}
</script>
</body>
</html>

With onclick-event you can call a javascript function. Not php.
Just try this.
<!--html -->
<button onclick="writeMsg(<?php echo $id_val ?>)">Click me</button>
<!--html -->
Function will be included in javascript
<script type="text/javascript>">
var id;
function writeMsg(id) {
alert(id."Hello world!");//give you result
}
</script>

Related

Undefined Index in PHP after Using AJAX

It seems that this question has already been asked many times but none of the solution is working for me. I'm new to AJAX so maybe there are some basics that I've missed? Basically I just want to pass the content of an html paragraph to a PHP script and I don't want to use html form.
I have two files: tes.html
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#post").click(function(){
var getContent = $("#text").html();
$.ajax({
url:"tes.php",
type:"POST",
data:{text:getContent},
dataType:"html",
});
});
});
</script>
</head>
<body>
<p id="text" contenteditable="true">This is the content</p>
<button id="post">post 2</button>
</body>
</html>
and tes.php
<?php
if (isset($_POST['text'])) {
$content = $_POST['text'];
echo $content;
} else {
echo "no content";
}
?>
After I clicked the Post button, in the PHP file it returns
Notice: Undefined index: text in C:\xampp\htdocs\projects\lab\tes.php on line 3.
Where did it go wrong? Really need your help guys. Thanks!
can you try this
$(document).ready(function(){
$("#post").click(function(){
var getContent = $("#text").html();
$.ajax({
url:"tes.php",
type:"POST",
data:{text:getContent},
dataType:"html",
success:function(data) {
console.log(data)
}
});
});
});
and in the HTML (as reza suggested)
<button id="post">post 2</button>
then, open the developer console and see if you can see the response from the tes.php
change html
<button id="post2">post 2</button>
to
<button id="post">post 2</button>
You have a click event and that sends an AJAX request so far, so good. You have
target="_blank"
which makes sure the page is opened in another tab/window. As far as I understood, you only want to send the request, so you need to prevent default:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script type="text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#post").click(function(e){
e.preventDefault();
var getContent = $("#text").html();
$.ajax({
url:"tes.php",
type:"POST",
data:{text:getContent}
});
});
});
</script>
</head>
<body>
<p id="text" contenteditable="true">This is the content</p>
<button id="post">post 2</button>
</body>
</html>
The new tab/window will give you the error, since an expected parameter is not there, so don't open it.

Passing data using Jquery Post method to the same page

I'm a newbie to Jquery , my question is simple , I'm trying to pass data using Jquery Post method, I have read a lot , but I can't figure it out:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="TestAd" id="TestAd">
<iframe data-aa='58593' src='https://ad.a-ads.com/58593?size=468x60' scrolling='no' style='width:468px; height:60px; border:0px; padding:0;overflow:hidden' allowtransparency='true' frameborder='0'></iframe>
</div>
<button>Send request</button>
<br>
<?php
if(!empty($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var height = $('.TestAd').height();
$("button").click(function()
{
if (height==0)
{
$.post("", {block:true});
}
}
</script>
</body>
</html>
The script is a simple AdBlocker checker, thanks for your help
<form method="post">
<input type="hidden" value="true" name="block">
<input type="submit" value="Send request">
</form>
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
if you want to redirect it to the same page why dont you use simple form tag to pass the block value.By default it will redirect it on the same page
Change your PHP to this:
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
And Change your jQuery to this:
<script>
var height = $('.TestAd').height();
$("button").click(function () {
if (height == 0) {
$.post("somepage.php",{block: true}, function (data) {
// data is the response
// do something with it here
alert(data);
});
}
}
</script>
Here are the docs for $.post(), essentially, the way you had it, ignores the response. You have to pass the anonymous function (function (data) {}) callback as the 3rd argument to be able to work with the response.
From the docs:
Examples:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.post( "test.php", { name: "John", time: "2pm" } );

why i cannot pass json data to another PHP file?

i have two php files home.php and ajax.php. i have two buttons on home.php. when they are clicked the according php functions in ajax.php should get called.
home.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
</html>
ajax.php
<?php
echo 'this was called';
echo $_POST['action']; //THROWS AN ERROR undefined index 'action'
if ( isset( $_POST['action'] ) ) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
the problem is the json data i assign to data property in jquery code will not get passed to the ajax.php. Is there any reason why it doesn't not pass it?
here is my youtube video on the error video
There are two possibilities, depending of what you want to achieve afterwards.
Eighter you stick on doing a backgroud ajax-call to ajax.php and then do with the response whatever you want (that's what I'd suggest):
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).id(); // changed to id here!
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
console.log(response); // log what the response is
alert("action performed successfully and the resonse is: \n"+response);
// do with that data whatever you need
});
});
});
</script>
</head>
<body>
<!-- changed to buttons, removed the form -->
<button class="button" id="insert">insert</button>
<button class="button" id="select">select</button>
</body>
</html>
or you submit the form and output on screen the response from ajax.php:
<html>
<head>
<!--script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script-->
<script type='text/javascript'>
// no need for any javascript then
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
and in ajax.php:
<?php
echo 'this was called';
if ( isset( $_POST['insert'] ) ) {
insert();
}
if ( isset( $_POST['select'] ) ) {
select();
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
try
$.post(ajaxurl, data)
.done(function( r ) {
alert("action performed successfully");
});
I like to use the jQuery on() and to be sure post has worked, I moved in your variables as such. Also you can try to do console.log(clickBtnValue) after the click to be sure you are able to see the value itself. After confirming, the post() should send that value into action post param.
<script type='text/javascript'>
$(document).ready(function(){
$('.button').on('click',function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
$.post(ajaxurl, {action:clickBtnValue}, function (response) {
alert("action performed successfully");
});
});
});
</script>
If you need to do a ajax call, remove the following part from the home.php
<form action='ajax.php' method="POST">
</form>
I think you are messed up with Ajax technology and the form post mechanism.

Issue On Getting jQuery Post Result

I am trying to run this simple Ajax Post example like:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$.post("test.php",
{
name:"Hello Ajax"
},
function(data){
$("p").html(data);
}
);
});
});
</script>
</head>
<body>
<p></p>
</body>
</html>
and PHP (test.php) as:
<?php
$name = $_POST['name'];
echo '<a>'.$name.'</a>';
?>
No error message but not getting any result back! can you please let me know what I am doing wrong?
Just a simple change, added button element in your markup. Click it and it should work:
<body>
<button>Click Me</button>
<p></p>
</body>
Your javascript is looking for the button element on which when clicked, will trigger the ajaxcall in test.php
$("button").click(function(){
By clicking the button, it will display Hello Ajax, the echo from the test.php and the one that you've send.
$.post("test.php",
{
name:"Hello Ajax"
},

Pass javascript variable to php with ajax and the result doesn't show anything

This is my code and i want to pass javascript variable with ajax to php when i click submit button then the result doesn't show var_data variable from javascript What code is wrong?
This is edit order one before everybody help me
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<?php
$test = $_GET['var_PHP_data'];
echo $test;
?>
</body>
</html>
and this is source code now
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
this statement if(isset($_GET['var_PHP_data'])) output false and then show Hello World What should i do to do for isset($_GET['var_PHP_data']) is true?
Your solution has PHP issues: you don't check if the data exists, and also, you don't do anything with the result. I've modified the script to do the following:
Check if the var_PHP_data var is set (in PHP, on the server).
If yes, just send a blank text response containing that data.
If no, then draw the form and everything else.
In the form, I've created a #result div.
Ajax response will be shown in this div.
Also make sure that you host the script at localhost and that it is called test.php. To make sure this is resilient, you can change the Ajax URL to
<?php echo $_SERVER['PHP_SELF'];?> to make sure that you'll hit the correct script.
<?php
if (isset($_GET['var_PHP_data'])) {
echo $_GET['var_PHP_data'];
} else {
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js">
<script>
$(document).ready(function() {
$('#sub').click(function() {
var var_data = "Hello World";
$.ajax({
url: 'http://localhost/test.php',
type: 'GET',
data: { var_PHP_data: var_data },
success: function(data) {
// do something;
$('#result').html(data)
}
});
});
});
</script>
</head>
<body>
<input type="submit" value="Submit" id="sub"/>
<div id="result">
</body>
</html>
<?php } ?>
Try jQuery Form its this will help to solve many problems.
For you question: try url without domain name, add tags 'form', change event click to submit, add data type
what are the contents of PassVariable.php ? if is the same where you have they jquery bit wont work coz php will print all the page again, if the file is different try
success: function(data) {
alert('databack = '+ data);
}
Try placing your input into a form and attaching the ajax call to the form onsubmit event. The way it happens in the provided happen is when you click in the field, in which case it submits before you can write anything really.
$(document).ready(function() {
$('#brn').click(function() {
var var_data = "Hello World";
alert("click works");
$.ajax({
url: 'http://localhost/ajax/PassVariable.php',
type: 'GET',
data: { x: var_data },
success: function(data) {
alert(data);
}
});
});
});
change it to this code
then in PassVariable.php put
make button
<input type="button" id="btn" value="click me" />
it should work because it is very basic example. If it doesn't work check your console if there are any JavaScript errors and remove them.

Categories