Passing data id from a php loop to jquery - javascript

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

Related

how to get each selected checkbox value from foreach loop using jquery

I have received the value from the array then made a foreach to achieve each value from it.
after adding each value to checkbox then made a onclick function to pass value to jquery function.
i have receiving each value just one by one I need to collect all those value who has been selected from user by clicking on checkbox.
Here is my code
$val = array();
$val = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
foreach ($val as $value){
<input type="checkbox" id="vehicle1" name="vehicle1" value="<?php print_r($value['id']); ?>"
onclick="assignId(<?php echo (isset($value['id'])?$value['id']:'0') ?>)">
}
Here is my jquery function where I need to collect all checkbox selected record and pass to controller
function assignId(val) {
alert(val);
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'json',
data: {param1: 'value1'},
success : function(response){
alert(response);
}
});
}
As you can see, I just need to get all the selected value of the checkbox which is here under foreach and pass it to controller.
The array that you are looping over is an associative array, which means it has key-value pairs. When you loop over such an array you can destructure the keys and values in the foreach statement. This way you can dynamically set the id, name and value of each checkbox.
Making your ids and names unique is actually quite important. Takes makes it possible to distinguish elements from one another and it makes it possible to pair each input with a value. Names can be the same though, but for now make them unique.
Wrap your <input> elements in a <form> tag. This form tag will make it easier for you to use jQuery and get all the values from each input whenever you need them. Also add a <button> to submit the form.
<?php
$data = array(
"Peter" => 35,
"Ben" => 37,
"Joe" => 43
);
?>
<form id="vehicleForm">
<?php foreach ($data as $key => $value) { ?>
<input type="checkbox" name="vehicle-<?php echo $key); ?>" value="<?php echo $value); ?>"/>
<?php } ?>
<button type="submit">Submit</button>
</form>
Modify your assignId function to accept a single string which can be used for the data property on your AJAX call. This string will be generated by the jQuery after this example.
function assignIds(data) {
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'json',
data: data,
success: function(response){
alert(response);
}
});
}
Listen to the submit event on the form. This event will be triggered every time you click on the submit button. Forms have a default behavior. You'll want to prevent this default behavior so you can create your own.
With the .serialize() method you extract the values from the form. The result of this method is a query string ready to send to the server. Pass that to the assignIds function and your data is sent.
$('#vehicleForm').on('submit', function(event) {
event.preventDefault();
var $this = $(this);
var data = $this.serialize();
assignIds(data)
});
What bad thing comes up to your code is that every time you click the checkbox it will send a request to your server. So I've made you a simple solution for your problem.
in your PHP Code write this:
<form id="myForm">
<?php
$value = array("Peter"=>35, "Ben"=>37, "Joe"=>43);
var_dump($value);
foreach ($value as $val => $data){
echo '<input type="checkbox" id="vehicle1" name="vehicle1" value="'.$data.'" /><label>'.$val.'</label>';
}
?>
<input type="submit" name="" value="submit">
</form>
Then for your Script:
$('form').on('submit', function( event ) {
console.log($(this).serialize());
event.preventDefault();
$.ajax({
url: '/path/to/file',
type: 'POST',
dataType: 'json',
data: {param1: $(this).serialize()},
success : function(response){
alert(response);
}
});
});
I hope this will help you. Happy Coding!!!
All main problems of your code has been already well explained and fixed by #Emiel but always there is different approach to solve every problem. The following are steps i followed and i have decided to use only one function. In addition there might be something useful for future readers. That's why i'm writing this answer.
I created a button to submit the form because you cannot use onclick() function on each checkbox that will be triggered every time someone clicks on it. So create a button with onclick=assignID().
I fixed the approach you have used is not correct which have already been mentioned in first answer by #Emiel so better not repeat it.
I kept the name of checkboxes the same so that i can access them in general later using getElementsByName(vehicle1) function.
in assignID() I created an array to hold the value of checked boxes
then used JSON.stringify() to format the array as JSON data.
<?php
$val =array("Peter"=>35, "Ben"=>37, "Joe"=>43);
foreach ($val as $key=>$value){//assouciative array have key and value relation
?>
<input type="checkbox" id="vehicle1" name="vehicle1" value="<?php echo $value; ?>"><!--//you don't have to put onclick functio in here-->
<?php
}
?>
<button onclick="assignId()">Button</button><!--Its necassary to have a button to submit value-->
<script type="text/javascript">
function assignId() {
var datas = [];//crating array
var checkboxes=document.getElementsByName("vehicle1");//getting all checkboxes by name
for(var i=0, n=checkboxes.length;i<n;i++) {//looping through each checkboxes to see if they are checked
if(checkboxes[i].checked==true){//check if checkbox is checked
datas.push(checkboxes[i].value);//push the value of the checked checkbox into datas array
}
}
$.ajax({
url: 'path/to/php/file',
type: 'POST',
datatype:"json",
data: {
param1: JSON.stringify(datas)//send the array in JSON data form
},
success : function(response){
alert(response);
}
});
}
</script>

Passing value from jquery to php variable in same page

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>

Correct method of sending a variable from a html form to a php function via ajax

I'm coding a voting system for multiple uploads; each uploaded image is in a foreach statement with a form attached to each, with three buttons to vote up, down or none, each associated with an INT in my mysql database.
I got it to work by submitting the form data straight to the PHP function that 'UPDATE's the database. To avoid a page refresh, I attach ajax. I got the ajax to send the two variables needed for the PHP function to update the correct "image" row and INT in the db.
Question: The ajax function works, but the PHP function doesn't seem to update.
SUSPECTED PROBLEM: I'm pretty sure it's the way I'm defining the variables in ajax that I want to pass, I was trying to grab the ID of the "image" it's handling, but I don't know how to translate this data to the PHP function so that it UPDATE's correctly.
Here's the form, javascript, and php:
// IMAGE, and rest of foreach above this, and ending after form
// This form only shows one button, there are three, each
// I'll treat the same once I get one to work
<form action="feed.php" method="post" id="vote_form_1">
// If js isn't turned on in broswer, I keep this
// hidden input, to send unique ID
<input type="hidden" name ="input_id"
class="input_id" value="<?php echo $row['id']; ?>"/>
<input type="submit" name="post_answer1" onclick="sayHi(event);"
class="answer_L" id="<?php echo $row['id']; ?>"
value="<?php echo $row['post_answerL']; ?>"/>
</form>
// end of foreach
//AJAX
<script type="text/javascript">
function sayHi(e) {
var input_id = $(e.currentTarget).attr('id');
var post_answer1 = $("input[name='post_answer1']");
jQuery.ajax({
type: 'POST',
url: 'feed.php', //name of this file
data:input_id,post_answer1,
cache: false,
success: function(result)
{
alert ('It worked congrats');
}
});
e.preventDefault();
</script>
// PHP VOTE UPDATE FUNCTION
<?php>
if(isset($_POST['post_answer1'],$_POST['input_id'])){
$current_id = $_POST['input_id'];
$vote_1 = "UPDATE decision_post set " .
"post_answer1=post_answer1+1 WHERE id = '".$current_id."' ";
$run_vote1 = mysqli_query($conn2, $vote_1);
if($run_vote1){ echo 'Success'; }
}
?>
Here a simple answer, just serialize all your form data!
$('form').submit(function(){
$.post('feed.php', $(this).serialize(), function(data){
console.log(data);
}, 'json');
return false;
});
var post_answer1 = $("input[name='post_answer1']").val();

Passing a php variable to another php file using ajax

I have some divs with class content-full which are created according to the data stored in a MySQL table. For example, if I have 3 rows there will be 3 divs.
When I click on any of the divs then the data associated with the ID for that div should be displayed inside div content-full. However, the content associated with the last div appears when I click on any of the divs because I am not passing any kind of variable ID that can be used to specify the clicked div.
<script type="text/javascript">
$(document).ready(function() {
$(".content-short").click(function() { //
$.ajax({
type: "GET",
url: "content.php", //
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
});
</script>
content.php
<?php
include "mysql.php";
$query= "SELECT Content FROM blog limit 1";
$result=mysql_query($query,$db);
while($row=mysql_fetch_array($result))
{
echo $row['Content'];
}
mysql_close($db);
?>
Is there an alternate way to do this or something that I need to correct for it to work?
Thanks
First off, you will have to pass actual data to the your PHP script. Let's first deal with the JavaScript end. I am going to assume that your HTML code is printed using php and you are able to create something like the following: <div class=".content-short" data-id="2" />:
$(".content-short").click(function() {
// get the ID
var id = $(this).attr('data-id');
$.ajax({
type: "post",
url: "content.php",
data: 'id=' + id
dataType: "text",
success: function(response){
$(".content-full").html(response);
}
});
});
Next up is reading the value you passed in using the script:
<?php
include "mysql.php";
// Use the $_POST variable to get all your passed variables.
$id = isset($_POST["id"]) ? $_POST["id"] : 0;
// I am using intval to force the value to a number to prevent injection.
// You should **really** consider using PDO.
$id = intval($id);
$query = "SELECT Content FROM blog WHERE id = " . $id . " limit 1";
$result = mysql_query($query, $db);
while($row=mysql_fetch_array($result)){
echo $row['Content'];
}
mysql_close($db);
?>
There you go, I have modified your query to allow fetching by id. There are two major caveats:
First: You should not use the mysql_ functions anymore and they are deprecated and will be removed from PHP soon if it has not happened yet!, secondly: I cannot guarantee that the query works, of course, I have no idea what you database structure is.
The last problem is: what to do when the result is empty? Well, usually AJAX calls send and respond with JSON objects, so maybe its best to do that, replace this line:
echo $row['Content'];
with this:
echo json_encode(array('success' => $row['Content']));
Now, in your success function in JS, you should try to check if there a success message. First of, change dataType to json or remove that line entirely. Now replace this success function:
success: function(response){
$(".content-full").html(response);
}
into this:
success: function(response){
if(response.success) $(".content-full").html(response);
else alert('No results');
}
Here the deprecation 'notice' for the mysql_ functions: http://php.net/manual/en/changelog.mysql.php
You can look at passing a parameter to your script, generally like an id by which you can search in the db.
The easiest way to achieve this is by get parameters on the url
url: "content.php?param=2",
Then in php:
<?php $param = $_GET['param'];
...

Insert/Edit records using php and javascript/ajax

I'm trying to make user interface to edit/insert records and i'm having some troubles with my code.
Lists the records :
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)){
extract($row);
$html.="<tr>
<td style>{$row['name']}<input type='hidden' id='id' value='$row[a_id]'></td>
<td>{$row['season']}</td>
<td><a href='edit1/new' id='edit'></a></td>
<tr style='height: 5px;'></tr>
</tr>..
Now the js that i`m having trubles with:
<script type='text/javascript'>
$('#edit').on( 'click', function () {
var x = document.getElementById('id').value;
$.ajax({
type: 'post',
url: 'insert_edit.php',
data: {
id: x
},
success: function( data ) {
console.log( data );
}
});
});
</script>
inside the insert_edit.php
if(isset($_POST['id'])){
$html = Edit();
}else{
$html = Add();
}
For some reason the on click function doesnt seem to work and it doesnt posts datainsert_edit.php`
Any help will be apriciated thank you.
NOTE: I'm not sure even if the posts works I'm using the Java Script the right way since my while loop prints it foreach ID and my guess is even it if it posts the data it will aways posts the value of the first record.
Try this- on click function replace with this-
$(document).on("click", "#edit", function(){
// ..
})
I managed to fix it. Here is how I did it:
I made an array $urlparts wich is my permalinks.
The button code goes like this
..a href='/account/competitions/edit1/update/$row[a_id]'>Edit..
And some php
if (isset($urlparts[4]) && is_numeric($urlparts[4])){
require_once ("insert_edit.php");
$html = Edit();
}
and inside the Edit();
just snach the id with
$id = $urlparts[4];
Thank you for the feeedback guys. Made me realize that I`m looking at the issue from the wrong angle:)

Categories

Resources