Passing value from jquery to php variable in same page - javascript

I know similar questions to this have been asked before but I don't see an answer that suits my question. I have a div that triggers a jquery script which stores an id. I can get the id into a variable in the jquery but I want to then assign that id to a PHP variable that exists on the same page.
So far this is what I've got. Here is my div that exists in index.php:
echo '<div id="'.$unit_id.'" class="dropdown unit '.$unit_size.' unit-'.$unit_number.' '.$unit_status.' data-unit-id-'.$unit_id.'">';
And here is my jquery that I call in from functions.php:
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>
I want to pass the unit_id into a variable on index.php called $getID but I can't seem to find a way of getting in there. I've tried using post but there really isn't a form being submitted. It's just a dive being clicked on.

You must change your id in your <div> and set it to fetch the variable sent by jQuery. Other than that, your jQuery script looks fine.
Here's how I would do it:
# Fetch the variable if it's set.
<?php $unit_id = (isset($_POST["id"])) ? $_POST["id"] : null; ?>
# Echo it as the id of the div.
<div id = "<?= $unit_id; ?>" class = "dropdown unit"></div>
EDIT:
The PHP code above is equal to:
# Fetch the variable if it's set.
<?php
if (isset($_POST["id"])):
$unit_id = $_POST["id"];
else:
$unit_id = null;
endif;
?>

Assign id to div id attribute like this, Use:
<div id="<?php echo $unit_id; ?>" class="dropdown unit"></div>

Try this hope it will work
<div id="<?php echo $unit_id;?>" class="dropdown unit"></div>
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
$.ajax({
type: 'post',
'id='+unit_id, //Pass the id
});
});
</script>

What you mean by this '$unit_id' in div ID. Just put the code in PHP Tag, while working with PHP in HTML pages use the code inside PHP tags.
Availale PHP tags : <?php echo $unit_id ?> (or) <?=$unit_id ?> (short tag).
Change your div with :
<div id="<?=$unit_id ?>" class="dropdown unit"></div>
or
<div id="<?php echo $unit_id ?>" class="dropdown unit"></div>
Then your script will be work
<script>
$('.unit.available').click(function(){
var unit_id = $(this).attr('id');
// to check whether value passing or not
console.log(unit_id);
$.ajax({
type: 'post',
data: {id: unit_id}, //Pass the id
});
});
</script>

Related

Javascript - Getting button tag value for ajax call

Basically what I have is a lot of <a> tags which are queried from a database. They are displayed and when a user clicks on one of the tags then it fires an ajax function. Right now one button does the work of all the buttons.
The tags look like this:
<a value='<?php echo $setit ?>' class='button' setdata='<?php echo
$setit ?>'><?php echo $setit ?></a>
And the ajax function looks like this:
$(document).ready(function(){
$(".button").click(function(event){
var data1=$(this).data('setdata');
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});
I'm thinking that I need to make the button id-s unique so the function can only get the correct button value. Am I on the right track? How can it be done?
There is no need to make the ids of your buttons unique. You could simply use
$('.button').click(function(e) {/*ajax*/});
to query all buttons. Note that you have to query using a . (for class names) instead of a # (for ids). Inside of the function $(this) will always refer to the link that was clicked.
On the other hand your id's should be unique. If you do not mind that they change on every refresh, you might use uniqueid:
<a id="<?= uniqueid(); ?>" ... >
Else your database should have an unique index that you might use. But i think there is no reason to set an id at all since your JavaScript is fine without.
$("#button") targets an element with id="button" but you certainly want to target element with class="button" as seen in your HTML... So you should replace the # with a dot, just like in CSS. $(".button")
Also, you do not need to use ID for this, even if you have multiple buttons, the eventHandler receives this as the target element, so you'll always have access to the "current" data.
Also I think you have wrong format for data property.
The right is here:
<a value='<?= $setit ?>' class='button' data-set='<?= $setit ?>'><?= $setit ?></a>
Just change your a tag as follows.
<a class='button' data-setdata='<?php echo $setit ?>'><?php echo $setit ?></a>
Replace your tag :
<a value='<?php echo $setit ?>' class='button' setdata='<?php echo
$setit ?>'><?php echo $setit ?></a>
To:
<a class='button' id='setit'><?php echo $setit ?></a>
and replace your ajax function :
$(document).ready(function(){
$(".button").click(function(event){
var data1=$(this).data('setdata');
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});
To :
$(document).ready(function(){
$(".button").click(function(event){
var data1 = document.getElementById("setit").innerHTML
$.ajax({
url: "set_freq.php",
type: "POST",
data: {"set_freq":data1},
success: function(data){
data = JSON.stringify(data);
console.log(data);
}
});
});
});

Passing data id from a php loop to jquery

I am using PHP foreach loop to use create rating inputs:
<input id="input<?php echo $i ?>" data-id="<?php echo $i ?>" class="rating-loading">
The problem is id="input" should be unique for the jQuery function and I do not know how to pass this data id to the jQuery, I tried to make it something like this:
$(document).on('ready', function(){
$('#input'+id).rating({
//my function
});
});
However it is not working. If on top I make id="input1" and in the script I add var id = 1; it is working only for my first inputs inside loop, but I'm not sure how to pass this data-id to the jQuery. I even tried:
$(document).on('ready', function(){
$(this).attr('data-id').rating({
//my function
});
});
However this is also not working. Please help me.
Don't use incremental id attributes; they quickly become a pain to maintain. Use a common class instead. Your inputs already have a .rating-loading class, so we can use that:
<input data-id="<?php echo $i ?>" class="rating-loading">
$('.rating-loading').rating({
//my function
});
some thing below must work
dataString = 'inID=' + valID
$.ajax({
type: "POST",
url: "yourfile.php",
data: dataString,
success:
function(data)
{
if (data='Posted')
{
///
}//posted
}//function data
});//ajax

How to post data without a form

Good day sir/ma'am I am a new programmer, I would like to ask how to post data like the functionality of form that when submitting the form the URL in action will display using javascript.
"WITHOUT USING A FORM" or using xmlHTTP that not return to main page
sample is
HTML
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
JS
function revisetask(idtask)
{
//In this function sir i would like to post here
}
Im very sorry if my english is too bad.. thanks in advance :D
You can use javascript for submitting the values of input boxes,
to do so,
write a javascript function which will read all your input boxes values into javascript variables,
Prepare a URL, and call that URL using window.location.href
function SubmitMyForm
{
var Firstname = document.getElementbyId('FirstName').value;
var Lastname = document.getElementbyId('LastName').value;
var URL="myDBoperations.php?firstname="+Firstname+"&lastname="+Lastname;
window.location.href= URL;
}
On the operations form you will receive these value in GET.
Hope this will help you.
U can use ajax for this. U don't need a form for ajax post, and it won't refresh the page too.
Below is an example code
<input type="text" id="test_name" />
<input type="button" value="Submit" obclick="save_this()" />
<script type="text/javascript">
function save_this(){
var text = $('#test_name');//stores te value in text field
$.ajax({
url: 'http://example.com/test.php',//your URL
type: 'POST',
data: { text: text },
success: function(data){
alert(data);
}
});
}
</script>
test.php
<?php
echo $_POST['text'];
As I've seen in this code:
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
I assume and believe that the reason why you don't want to use form because you want your $id to be submitted through javascript/jquery. But alternatively, you could just do it this way:
HTML:
<form method = "POST" action = "updatetask.php">
<input type = "hidden" value = "<?php echo $id; ?>" name = "taskid" id = "taskid"/>
<input type = "submit" value = "UPDATE" name = "updatebutton">
</form>
PHP:
<?php
$taskid = $_POST['taskid'];
?>
In the above code I just set the type hidden and which contains the value of your $id in which would be post in your Php file.
UPDATE:
If it still doesn't fit to what you want then you could just have this other alternative which will be using the GET method: <a href = "updatetask.php?id='<?php echo $id; ?>' REVISE </a>"
That's the only option you have. and if you don't want to show the id in your url then you could just use URL Rewriting (refer to this link: https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/)
Hope this helps.

AJAX GET simple PHP Multiple variables

I need a simple way to retrieve multiple PHP variables into html divs. I searched a lot of posts but I can't found an answer.
I am looking for something like this:
go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
?>
index.php
<div class="name">Your Name is : <?php echo $name; ?></div>
<div class="phone">Your Phone Number is : <?php echo $phone; ?></div>
<div class="details">Your Details are : <?php echo $details; ?></div>
I want instead of echo to get them via AJAX Call.
What is the correct AJAX REQUEST syntax to do that?
UPDATE
My bad I do not noticed before but forgot to say I also need to load the calls one by one. I have too many requests and take a lot of time.
May the query .each() function should work like I want?
In your PHP:
<?php
echo json_encode(Array(
'name' => "John",
'phone' => "1234567890",
'details' => "Details about..."
));
Your HTML:
<div class="name">Your Name is : <span class="name_value"></span></div>
<div class="phone">Your Phone Number is : <span class="phone_value"></span></div>
<div class="details">Your Details are : <span class="details_value"></span></div>
Your jQuery:
$(document).ready(function(){
$.getJSON('user-info.php',function(data){
$(".name_value").html(data.name);
$(".phone_value").html(data.phone);
$(".details_value").html(data.details);
});
});
Note: you'll set the user-info.php string to the URL (relative or absolute) of your PHP script that grabs the user info.
You need a PHP script that will output JSON containing the values you want, and you need a Javascript handler to ask for that data and do something when it gets it. Here's an example:
# File: go-to-index.php
<?php
$name = 'Jonh';
$phone = '123456789';
$details = 'Detail about';
echo json_encode(
[
'name' => $name,
'phone' => $phone,
'details' => $details
]
);
Then your HTML page:
<!-- File: index.php -->
<div class="name">Your Name is : <span class="container"></span></div>
<div class="phone">Your Phone Number is : <span class="container"></span></div>
<div class="details">Your Details are : <span class="container"></span></div>
<button class="loadMe" type="button">Click here to make things work</button>
And finally your jQuery:
$(document).ready(function() {
$('.loadMe').click(function() {
$.ajax({
// Path to your backend handler script
url: 'go-to-index.php';
// Tell jQuery that you expect JSON response
dataType: 'json',
// Define what should happen once the data is received
success: function (result) {
$('.name .container').html(result.name);
$('.phone .container').html(result.phone);
$('.details .container').html(result.details);
},
// Handle errors in retrieving the data
error: function (result) {
alert('Your AJAX request didn\'t work. Debug time!');
}
});
});
});
You can do this on any event - the button was just an example. You can also use plain Javascript or any other library, just used jQuery since you tagged it in your question.

twitter bootstrap modal vs. PHP POST request through javascript-ajax

why the code below doesn't do its job ?
I just need POST via javascript id content on click btn.
this code works properly in many other situations but not here that i'm using twitter bootstrap modal.
thanks.
<button id="<?php echo $id; ?>" class="btn btn-warning" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
<span class="glyphicon glyphicon-trash"></span> delete id
</button>
<script type="text/javascript">
//delete id
$(document).on('click','.btn-warning',function(){
var element = $(this);
var del_id = element.attr("id");
var info = 'id=' + del_id;
if(confirm("are you sure ?")){
$.ajax({
type: "POST",
url: "page.php",
data: info,
success: function(){ window.location.href = "/logout.php"; }
});
}
return false;
});
</script>
PHP
if($_POST['id']){
$id=$_POST['id'];
$id = mysql_real_escape_string($id);
...
info = {'id' : del_id };
Try to send data as array.
First, I think you should be using isset(variable) in the PHP:
if (isset($_POST['ID'])
{
...
Second, it doesn't work because you need to set the data and a key -> value array.
data: {id: "ID_NUMBER"}
Look over the examples on Jquery's site: https://api.jquery.com/jQuery.ajax/
I would also suggest using a unique ID property or a new/unique class proverty, and then using that to add the onClick event.

Categories

Resources