Send values to PHP - php

I have a button within my HTML that, when you click it, I need to have it run a query in a PHP file which would then echo the results.
I've tried the following, however, when I click the button, it does nothing. What's wrong?
HTML/Ajax:
<?php
$reply_id = 15;
?>
<html>
<body>
<center><a class="btn show-more">Show more comments</a></center>
<div id="resultcomments"></div>
<script type="text/javascript">
var id = $reply_id;
$(document).ready(function() {
$(".show-more").click(function() {
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: ({id_variable: id}),
function(data) {
$("#resultcomments").html(data);
}
});
});
});
</script>
</body>
</html>
PHP (located in assets/misc/test.php):
<?php
$replyid= $_POST['id_variable'];
echo $replyid;
// query would go here
?>

since $reply_id is PHP variable, for using it inside javascript you need to do like:
var id = <?php echo $reply_id; ?>;
....
and change:
data: ({id_variable: id})
to
data: {id_variable: id}
like:
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: {id_variable: id},
success: function(data) {
$("#resultcomments").html(data);
}
});

You're not assigning your AJAX success function to a key, so I don't think it's ever firing. (You could try a console.log() or a debugger to check.) Try this instead:
$.ajax({
url: 'assets/misc/test.php',
type: "POST",
data: {id_variable: id}
}).done(function (data) {
$("#resultcomments").html(data);
});

Try this in javascript
var id = <?php echo $reply_id; ?>;

No brackets needed for data attribute in ajax,
data: {id_variable: id},
Try this for data attribute

Related

How to POST jQuery variable through ajax to external PHP SQL script and return values

I'm trying to pass a jQuery variable (var datastring), that is a string, through ajax to the external drug_scripts.php file that echos out the value. I can get it to work if I set the data to a numerical value, however if I set it to the variable it returns NULL.
I've set data: ({dataSTring: dataString}) -- returns NULL.
Setting data: ({name: 123}) --- returns 123
AJAX:
var dataString = '<?php print $DF_NAME1; ?>';
$.ajax({
url: "/wp-content/themes/Avada-Child-Theme/assets/php/drug_scripts.php",
type:"POST",
dataType: 'json',
data: ({dataString: 125}),
success: function(data){
console.log(data);
}
});
PHP:
$userInput = $_POST['dataString'];
echo $userInput;
Again, the current state returns 123. If you were to set data to data: (dataString) it returns NULL.
I will assume $DF_NAME1 is defined as something like <?php $DF_NAME1 = 'name'; ?> (which you will get somewhere, like the database)
Then:
<script>var dataString = "<?=$DF_NAME1?>";</script>
<script>
$( document ).ready(function() {
var dataToSend = 'dataString=' + dataString;
$.ajax({
url: "/wp-content/themes/Avada-Child-Theme/assets/php/drug_scripts.php",
type:"POST",
dataType: 'json',
data: dataToSend,
success: function(data){
console.log(data);
}
});
});
</script>
The PHP file:
<?php
$userInput = $_POST['dataString'];
echo json_encode($userInput);
?>
You need both ... attribute name and attribute value
....
type:"POST",
dataType: 'json',
data: ({attribute_name:'attribute_value'}),
....
in your case
....
type:"POST",
dataType: 'json',
data: ({dataString : dataString }),
....
in $_POST['dataString'] you should obtain the content of the var dataString
Try this it works as I have rewritten the code for you.
In the script below, You can see that I just alert the dataString variable to see if it has any value. if the alert is empty, it means you are not passing any value to the datastring variable.
I have also tested it with variable data string set to NancyMooree which I commented
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//var dataString = 'NancyMoore';
var dataString = '<?php echo $DF_NAME1; ?>';
// check that datastring has value in it by alerting it
alert(dataString);
var datasend = "dataString ="+ dataString ;
$.ajax({
type:'POST',
url:'/wp-content/themes/Avada-Child-Theme/assets/php/drug_scripts.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(data){
console.log(data);
$('#listresult').fadeIn('slow').prepend(data);
}
});
});
</script>
</head>
<body>
<div id="listresult"> </div>
</body>
</html>
php
<?php
$userInput = $_POST['dataString'];
echo $userInput;
?>

pass sessionid through jquery ajax call to php

JS in (start.php)
$(document).ready(function()
{
$('#btn_1').click(function(){
$.ajax({
type: "POST",
url: "get_data.php",
data: 'func=getData1',
success: function(msg){
$('#div_1').html(msg);
}
});
$('#div_1').show();
})
});
PHP (somename.php)
<?php
session_start();
if(trim($_POST['func']) == "getData1")
{
echo "Test";
}
?>
How can i pass the sessionid from start.php through my ajax to the get_data.php file ?
And how can pass the complete URL "url: "get_data.php," to the js-File so that i can switch the php-files, that should be called from ajax ?
Store Session ID in javascript variable and send it through ajax call, like this:
var session_id = '<?php echo session_id();?>';
Complete code should be:
var data = {func:'getData1',session_id:session_id};
$('#btn_1').click(function(){
$.ajax({
type: "POST",
url: "get_data.php",
data: data,
success: function(msg){
$('#div_1').html(msg);
}
});
$('#div_1').show();
})
Updates
If you want to access php variable in external js file, define variable before including js file. Like:
<script type="text/javascript">
var session_id = '<?php echo session_id();?>';
</script>
<script src="./ajax.js" type="text/javascript"></script>
$(document).ready(function()
{
$('#btn_1').click(function(){
$.ajax({
type: "POST",
url: "get_data.php",
data: {func:'fuc_name',session:'<?php echo session_id();?>'},
success: function(msg){
$('#div_1').html(msg);
}
});
$('#div_1').show();
})
});
var session_id = '<?php echo session_id();?>';
$('#btn_1').click(function(){
$.ajax({
type: "POST",
url: "get_data.php",
data: {func:"getData1","session":session_id},
success: function(msg){
$('#div_1').html(msg);
}
});
$('#div_1').show();
})
});
Use json encode. By using json you can pass the php data to js. Changing the code as per below. Set session id after session starts.
$(document).ready(function()`{
$('#btn_1').click(function(){ ` $.ajax({ `type: "POST",` dataType:"json", `url: "get_data.php,` data: 'func=getData1'`success: function(msg){ ` $('#div_1').html(msg.id); `}
});
$('#div_1').show();
})
});
in php side echo the variable with json encode.
echo json_encode($id); `
Use json encode. By using json you can pass the php data to js. Changing the code as per below. Set session id after session starts.
$(document).ready(function()
'{
$('#btn_1').click(function(){ `
$.ajax({
type: "POST",`
dataType:"json", `url: "get_data.php,`
data: {func:'enter the data you want to pass'},
success: function(msg){
$('#div_1').html(msg.id);
}
});
$('#div_1').show();
})
});
in php side echo the variable with json encode.
echo json_encode($id); `

Pass php value with ajax with ajax post

I'm using an ajax script to post a value to a PHP file.
I'm not able to pass the variable.
My variable is declared in PHP and I would like to pass it with ajax.
Here is the variable and my button:
<?php $employee_id= '3'; ?>
<input class="btn btn-danger" type="submit" value="Delete" id="delete-btn">
This is the Javascript:
<script>
$(document).ready(function () {
$("input#delete-btn").click(function(){
$.ajax({
type: "POST",
url: "delete.php", //
data: {id: '$employee_id'},
success: function(msg){
$("#thanks").html(msg)
},
error: function(){
alert("failure");
}
});
});
});
</script>
Here is the PHP code where I want to receive the value:
if (isset($_POST['id'])) {
$emp_id = strip_tags($_POST['id']);
echo $emp_id;
$query = "DELETE FROM `employee` WHERE id='$emp_id'";
$result = mysql_query($query) OR die(mysql_error());
echo 'You successfully deleted the user.';}
I know I'm doing something wrong around the data...
That is because your variable is in php but you are not using php to attach your variable to your ajax, try wrapping your variable in php tags and then make sure you use 'echo' to print the value of your variable into javascript.
data: {id: <?php echo '$employee_id'?>},
Your javascript code, as far as the client will see, will end up looking like this for them:
data: {id: '3'},
They won't see the php code, they will just see the end result as their javascript.
You need PHP tags around your variables:
<script>
$(document).ready(function () {
$("input#delete-btn").click(function(){
$.ajax({
type: "POST",
url: "delete.php", //
data: {id: <?php echo '$employee_id'; ?> }, // <---
success: function(msg){
$("#thanks").html(msg)
},
error: function(){
alert("failure");
}
});
});
});
</script>

How to get json data and display in div using jquery

Let's say .. I have the following script in my controller:
$result= array("Name"=>Charlie Sheen, "Age"=>30);
echo josn_encode($result);
And in my view file I have the following java script. Now could you please tell me what exactly to write in the success function of the script below in order to get the "Name" and "Age" displayed in two different divs inside body tag? I have found some tutorials on this but all those are very confusing to me. Could you please kindly help?
Thanks in Advance :)
<script type="text/javascript">
$(function(){ // added
$('a.read').click(function(){
var a_href = $(this).attr('href');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>batch/get_info",
data: "id="+a_href,
success: function(server_response){
//What exactly to write here
}
}); //$.ajax ends here
return false
});//.click function ends here
}); // function ends here
</script>
Make sure you spell you json_encode function correctly.
Your html should look like this:
<head>
<script type="text/javascript">
$(function(){ // added
$('a.read').click(function(){
var a_href = $(this).attr('href');
$.ajax({
dataType : 'json', //You need to declare data type
type: "POST",
url: "<?php echo base_url(); ?>batch/get_info",
data: "id="+a_href,
success: function(server_response){
$( '#name' ).text( server_response.Name );
$( '#age' ).text( server_response.Age);
}
}); //$.ajax ends here
return false
});//.click function ends here
}); // function ends here
</script>
</head>
<body>
<div id='name'></div>
<div id='age'></div>
</body>
First of all, you should set the dataType. It should have the value 'json'. As for accessing it, you just access it as you would any other JavaScript object:
<script type="text/javascript">
$(function() {
$('a.read').click(function() {
var a_href = $(this).attr('href');
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>batch/get_info",
data: "id=" + a_href,
dataType: 'json',
success: function(result) {
alert(result.Name); // Charlie Sheen
}
});
return false;
});
});
</script>

jquery-ajax: pass values from a textfield to php file and show the value

index.html
<html>
<head>
</head>
<body>
<input type="text" id="inputtext"><input type="button" value="submit "id="submit">
<br>
<div id="response">
</div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript" src="thescript.js"></script>
</body>
</html>
thescript.js
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "greet.php",
data: dataString,
success: function(){
$("#response").load("greet.php");
}
});
});
});
greet.php
<?PHP
print "hello " . $_POST['dataString'];
?>
The value that was entered in the textfield should show when the greet.php is loaded. not sure why it won't work
I think it can easier:
$("#submit").click(function()
{
var dataString = $("#inputtext").val();
$.ajax({
type: "POST",
url: "greet.php",
data: "dataString=" + dataString,
success: function(result){
$("#response").html(result);
}
});
});
And for php:
<?PHP
if(isset($_POST["dataString"]))
{
echo "hello " . $_POST['dataString'];
}
?>
I don't think you've got your jQuery .ajax call right. From the jQuery documentation:
Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
You want to be passing params as your data, in key/value format, rather than just the data, That way you can access it in your php as 'dataString' is to pass data: "dataString=" + dataString instead.
$.ajax returns the "hello" already. however while your page receives it, it queries "greet.php" again.
$.ajax({
type: "POST",
url: "greet.php",
data: dataString,
success: function (response) {
$("#response").append(response); // or .html(response)
}
});
or better: use .post();
$.post("greet.php", dataString, function (response) {
$("#response").append(response); // or .html(response)
});
finally, is your submit button is in a form, and you handle the click event, you shoudld prevent the form to submit on click if you want to stay on the page and not reload it.
$("#submit").click(function(event) {
event.preventDefault();
// stuff
return false;
});
$(document).ready(function(){
$("#submit").click(function(){
var dataString = $("#inputtext").val();
$("#response").load("greet.php"+ dataString );
});
});
Try this;
$("#response").load("greet.php", {dataString : dataString});

Categories