Ajax - send button value to php - javascript

I have a problem with send data to php. I want to send button value via jquery ajax. This is my code:
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
</script>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
PHP:
<?php
$name = $_POST['data'];
echo $name;
?>
It doesn't working...

try this out, i just did and worked fine
here's my js file
<html>
<head>
</head>
<body>
<button id="1" name="1" value="some_value">1</button>
<button id="2" name="2" value="some_value">2</button>
</body>
<footer>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('button').click(function() {
var val = $(this).val();
$.ajax({
// your uri, pay attention if the post is going to the right place
url: "try.php",
type: "POST",
// myVar = name of the var that you will be able to call in php
// val = your data
data: {'myVar': val}
});
});
});
</script>
</footer>
</html>
and here's my php
<?php
$name = $_POST['myVar']; //the var you put in your ajax data:{}
print_r($name);
in google chrome you can press f12 and go to Network Tab, you will be able to see the requisitions that your browser made and theirs responses

Make proper json string to send data. You are having extra ; there.
$(document).ready(function(){
$.ajax({
url: "try.php",
type: "POST",
data: {
data: val // removed ; after val.
}
});
});
And get it with data key in php.
<?php
$name = $_POST['data'];
echo $name;
?>
Also, write your event listeners inside document.ready(). Currently your listeners are not getting applied as the script is on the top and is not able to find the <button> as they are not yet present.

<button id="example" name="name_example" value="some_value">
1</button>
$(document).ready(function () {
$('#example').click(function() {
var buttonValue = $(this).val();
$.ajax({
url: "try.php", //assuming that your html file is in the same folder as
//your php script.
type: "POST",
data: {'example': buttonValue}
});
});
});
look this: https://jsfiddle.net/willianoliveirac/yarLfdnu/
In your .php file, which should be in the same folder as your html file doing the request you will have:
<?php
echo '<pre>'; print_r($_POST); die; // see if you now have those vars.
?>

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 value with redirect and echo to page

I have developed the website using jquery & PHP, I have created a page using HTML, / PHP so what I want is if I click on submit, item ajax should send value to PHP variable and then execute index.php and get that value to another page.
Please help me to resolve the issues.
So far, I have tried the following:
index.php
my Javascript Code
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = $("#number").val();
$.ajax ({
type: "POST",
url: "ajax.php",
data: { val : val },
dataType:'text',
success: function( result ) {
// window.location.href = 'ajax.php';
// alert(result);
}
});
});
});
</script>
my HTML Code
<form name="numbers" id="numbers">
<input type="text" name="number" id="number" >
<button type="button" id="btn">Submit</button>
</form>
ajax.php
<?php
session_start();
$_SESSION['val'] = $_POST['val'];
print_r($_SESSION);
?>
You can store the value in session and redirect the user to other page and get data from session at other pages.
<?php
session_start();
$_SESSION['data'] = $_GET['val'];
?>
Your HTML code must be like that
<form name="numbers" id="numbers">
<input type="text" name="number" id="number">
<button type="button" id="btn">Submit</button>
</form>
For redirect to other page you can use like
<script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function() {
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
window.location.href = 'url';
}
});
});
});
</script>
in this if you click button its refresh the page because you using input type="submit" on button , so just change it to input type="button"
<input type="button" id="btn" value="submit">
and if you want to keep input type="submit" as you already did then just add prevent default to jquery
$(document).ready(function(){
$("#btn").click(function(event) {
event.preventDefault();
var val = "Hi";
$.ajax ({
url: "ajax.php",
data: { val : val },
success: function( result ) {
}
});
});
});
you can use session
in ajax.php you have to add:
<?php
session_start();
echo $_GET['val'];
$_SESSION['val'] = $_GET['val'];
?>
and use variable $_SESSION['val'] to any page

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>

codeigniter sending a variable from ajax to controller

I'm currently doing an ajax add,update and delete. And I think I'll just start with the delete since it is the easiest and hope that it might help me in the others.
In jquery (this is inside $doc.ready and the event is triggered properly)
if ($a == "Delete")
{
var postid = $(this).next('.postid').val();
$(this).closest(".todo-content").fadeOut();
jQuery.ajax({
type: "POST",
dataType: 'json',
url: "<?=base_url()?>.index.php/classes/deletepost",
data: {postid: postid},
async: false,
});
}
in html
<form method="post">
<button class="btn" onclick="return confirm('Are you sure to delete this item?')">Delete</button>
<input type="hidden" value="<?php echo $id; ?>" name="postid">
</form>
In controller
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}
This is already working but then I am planning on making the crud to ajax. I'm trying to pass the postid from ajax to controller to delete this post. The fadeout already works but only the ajax does not. I'm very new to ajax so I do not know where I am going wrong and I might also ask questions again regarding the other parts of crud.
Fixed!
The problem was the url inside the $.ajax. It returns a garbage.
So I added a script in the header
<script type="text/javascript">
var BASE_URL = "<?php echo base_url();?>";
</script>
And just use BASE_URL in the url: like so url: BASE_URL+'classes/deletepost',
Please Try to follow this:
In Codeigniters View:
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- Store ID and baseurl as attributes . this would help you to fetch data -->
<button class="btn" postId="5" baseUrl="<?php echo base_url();?>" id="button">Delete</button>
<!-- reading jquery file .. -->
<script type="text/javascript" src="http://localhost/jquery/js_search/jquery.js"></script>
<!--you can write file in extra js file .. it depends on you -->
<script type="text/javascript">
$('#button').click(function(){
// ask for confirmation
var result = confirm("Want to delete?");
// if it is confirmed
if (result) {
// get baseURL and ID using attributes
var base_url = $('#button').attr('baseUrl');
var postid = $('#button').attr('postId');
// make a ajax request
$.ajax({
url: base_url,
type: "POST",
dataType: 'json',
success: function (data) {
if(data){
// Fade out the content id
$('#content_id').closest(".todo-content").fadeOut();
}
}
});
}
});
</script>
in controller:
// You just need to delete the post and return a status code of "200"
public function deletepost(){
$id = $this->input->post('postid');
$data = array('active' => 0);
$this->Model_name->deletepost($id,$data);
redirect('/abc/123');
}

How to pass data to PHP page through AJAX and then display that page in another's DIV?

I have 2 pages with which I am working with: test1.php and test2.php. test1.php contains 2 <DIV> tags, one named "SubmitDiv" and the other named "DisplayDiv". In SubmitDiv, there is a check box and a submit button. When the check box is checked and the submit button is clicked, I would like it to display test2.php in the DisplayDiv div tag. I have figured that much already.
However, now I want test2.php to receive data from test1.php and process that data. In this case, it is receiving the checkbox's name, "chk" and will be printing that with an echo command. This is where I am a bit stumped as to how to go about this. After searching a bit for an answer, this is what I have written so far:
test1.php:
<html>
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<meta charset="utf-8">
<script type="text/javascript">
function sendQuery() {
e.preventDefault();
$.ajax({
type: 'POST',
url: 'test2.php',
data: $('#SubmitForm').serialize(),
success: function() {
$('#DisplayDiv').load('test2.php');
}
});
return false;
}
</script>
<body>
<form id="SubmitForm" action="" method="post">
<div id="SubmitDiv" style="background-color:black;color:white;">
<input type="checkbox" id="chk" name="chk" form="SubmitForm" value="chk">CHECK</input><br>
<button name="submit" id="submit" type="submit" form="SubmitForm" onclick="return sendQuery();">Submit</button>
</div>
</form>
<div id="DisplayDiv"></div>
</body>
</html>
test2.php:
<html>
<meta charset="utf-8">
<?php
$chk = $_POST['chk'];
echo $chk;
?>
</html>
When the submit button is clicked, however, all it does is refresh the page, rather than display the test2.php in the DisplayDiv like it's supposed to. Any ideas on how to pass the data to test2.php and then also display it within the DisplayDiv section?
Instead of .load function use the following
success: function(response) {
$('#DisplayDiv').html(response);
}
If you want to use e.preventDefault(); you must pass the event to the function
function sendQuery(e) {
e.preventDefault();
//...
}
Otherwise I assume your form is simply submitted on click.
You must first remove e.preventDefault(); in the sendQuery function because that is failing to return false onclick.
Then change your AJAX call to as follows:
$.ajax({
type: 'POST',
url: 'test2.php',
data: $('#SubmitForm').serialize(),
success: function(data) {
$("#DisplayDiv").html(data);
}
});
This works:
$.ajax({
type: 'GET',
url: 'data.php',
data: {
"id": 123,
"name": "abc",
"email": "abc#gmail.com"
},
success: function (ccc) {
alert(ccc);
$("#result").html(ccc);
}
});
Include jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
data.php
echo $id = $_GET['id'];
echo $name = $_GET['name'];
echo $email = $_GET['email'];

Categories

Resources