I'm noob in PHP, and JQuery, and i'm trying to do a pagination without changing the page.
I could submit a form, but i want to change the value from the limit without doing a submission.
My Query(i want to change the Limit):
$query = "SELECT * FROM events WHERE event_day = '".$list_day."' AND event_month = '".$month."' AND event_year = '".$year."' LIMIT 0,3";
I tried to do that -
First, i created a form with the limit value:
$limit = 0;
<form id="more" method="GET">
<button type="button" id="more_btn" value="<?= $limit ?>" class="c-button-1"><</button>
</form>
And then, i tried to get the value from the button, using Ajax
$(function(){
$(document).on("click","#more_btn",function() {
var value = $(this).attr('value');
$.ajax( {
type: 'get',
url: "modules/groups/calendar.php",
data: $('#more').serialize(),
success: function( response ) {
}
});
});
});
I was thinking about getting the value from the button, and change it in JQuery:
$query = "SELECT * FROM events WHERE event_day = '".$list_day."' AND event_month = '".$month."' AND event_year = '".$year."' LIMIT ".$limit.",3";
you don't even need the <form> there. when you are working with ajax you generally don't need any forms unless you want to do some hybrid coding for browsers with javascript turned off, or for serializing them (what you tried).
but in your case it doesn't really make any sense since your form just contains one button.
and you are already trying to get the value from the button but don't use it later on for some reason. you don't need to use .attr() there, since jQuery got the .val()-function for HTML elements with the value attribute.
so i'd do it like this:
$(function(){
$(document).on("click","#more_btn",function() {
var value = $(this).val();
$.ajax( {
type: 'get',
url: "modules/groups/calendar.php",
data: {
my_button_value : value
}
success: function( response ) {
}
});
});
});
$_GET['my_button_value'] then will receive the value in your PHP script.
in your question you also serialized the form which returns a URL-encoded string ("GET-style") which you can't just use in the data-attribute of the $.ajax function. you need an object there as i did in my code.
Related
I want to make dynamic select options based on database values.
I am getting id when user select an option, I get this id in ajax and then this id is passed in PHP. In PHP I run SQL query based on provided id. Now I want to send response back in AJAX and then I will append my next select option with the given response.
This is my AJAX, from this code I am passing selected_val in PHP.
`
$(document).ready(function() {
$(".sdpt").change(function(){
let deptid = $(this).val();
console.log(deptid);
$.ajax({
method: "POST",
url: "joins.php",
data: { selected_val: deptid },
success: function(response){
console.log(response);
}
});
});
});
`
In PHP, I am getting data (pro_name) from database and adding it in an array. I want to return this array in ajax and then I will use it there. Now it is return the whole PHP code in response. Please guide where I am doing mistake and what is the alternative.
`
if (isset($_POST['selected_val']) ) {
$value = $_POST['selected_val'];
$myq = new Database();
$result = $myq->sql("SELECT * FROM programs where dept_id=$value");
$arr = array();
while($row = mysqli_fetch_assoc($result)){
$arr[] = $row['pro_name'];
};
echo json_decode("Google");
}
`
I have a page with several buttons whose values and names are retrieved from the database. I'm trying to run an insert query on any button clicked, my code so far:
<?php
$sqlGetIllness = "SELECT * FROM illnissesandconditions ";
$resultGetIllness = $conn->query($sqlGetIllness);
while ($rowGetIllness= mysqli_fetch_array($resultGetIllness)){
echo "<div class='col-md-3'style='margin-top:20px;'><button onclick='insert(".$rowGetIllness['illness'].");' class='button button1' style=' color:white;' value='".$rowGetIllness['illness']."'>".$rowGetIllness['illness']."</button></div>";
}
function insert($value) {
$value='';
$sqlGetId = "SELECT commonID from common group by commonID DESC LIMIT 1 ";
$resultGetId = $conn->query($sqlGetId);
$r=mysqli_fetch_array($resultGetId);
$id=$r['commonID'];
$sqlGetIllness = "INSERT INTO medicalrecords (CommonID,Medical_Condition) VALUES (".$id.",'".$value."')";
$resultGetIllness = $conn->query($sqlGetIllness);
}
The value passed to the function inside onclick is correct when I inspect it in the browser, however nothing happens. I have a database connection on already, what could be wrong? Is it possible to do it like that in php without refreshing the page? Or do I need to use a client side lang like AJAX? Please note that I've never worked in AJAX btw.
New EDIT:
<script>
$("button").click(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
data: {
condition: $(this).val(), // < note use of 'this' here
},
success: function(result) {
alert('Condition Inserted!');
},
error: function(result) {
alert('error');
}
});
});
</script>
Solution:
I got it worked out, after writing the script, i retrieved the variable value on top of the page
if (isset($_POST['condition'])) {
$value=$_POST['condition']; }
inside $_SERVER['REQUEST_METHOD'] == 'POST' ) and now it inserts the value when ever any button is clicked, my next step is to give the clicked button a background color
Solution is in the post under Solution, was my first time trying ajax and it did work indeed, gave the button an id, and took its value ( any button clicked ) through this.val and sent via post, retrieved and used the value in a variable for the insert query.
I entered checkbox values into the database using the code below. When a user wants to view the checked boxes at a later time, how would I pull the data out of the database and re-check the checkboxes that were originally checked and submitted?
From the code below the data gets entered like this: DATA1|DATA2|DATA3|
var checkbox_value = "";
$(":checkbox").each(function () {
var ischecked = $(this).is(":checked");
if (ischecked) {
checkbox_value += $(this).val() + "|";
}
});
Now how to I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
Here is how I'm getting other data and re-displaying it from normal input text boxes:
$.ajax({
url: 'ajax/example/example.php',
data: "findval="+carrier+"&column="+column,
dataType: 'json',
success: function(data)
{
var auto_id = data['id'];
var auto_name = data['name'];
var auto_address = data['address'];
var auto_trailer_types = data['trailer_types'];
$('#output_autocomplete_forms').html("<form id='example' class='form-horizontal'><input type='hidden' name='auto_id' id='auto_id' class='form-control' value="+auto_id+">......<div class='form-group'>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA1'>DATA1</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA2'>DATA2</label></div>
<div class='checkbox'><label><input type='checkbox' name='trailer_kinds[]' value='DATA3'>DATA3</label></div>
var auto_trailer_types = data['trailer_types'];
Now how do I take DATA1|DATA2|DATA3| and re-check the corresponding checkboxes?
So, I am guessing that the string stored in the database is something like 0|0|1|0, and you need to restore the checkboxes to that state.
As has been said, you can use AJAX for that. First, you need a trigger to launch the AJAX routine -- a button click, usually:
<button id="mybutt">Update Checkboxes</button>
Your AJAX routine will look something like this:
var rowID = $(this).closest('tr').attr('id');
alert(rowID); //this datum must allow you to identify the row in the database
$.ajax({
type: 'post',
url: 'another_php_file.php',
data: 'id=' +rowID,
success: function(recd){
var arrCB = recd.split('|');
for (var n=0; n<arrCB.length; n++){
var z = n+1;
$('#cb'+ z).val( arrCB[n] );
}
}
});
another_php_file.php:
<?php
$id = $_POST['id'];
$pseudo_query = "SELECT `field_name` FROM `table_name` WHERE `id` = '$id' ";
echo $pseudo_query_result;
The pseudo_query_result that you echo should be your original 0|0|1|0. The PHP echo sends that datum back to the jQuery AJAX routine's success function. Important: the received data is not available outside that success function. You must do what you want with that data inside the success function, as shown in above example.
In above code, .split() was used to turn the 0|0|1|0 string into an array, and then we use a for loop (or even just manually code each checkbox update individually).
Use ajax to resolve this issue. But before try to encode your php query response in JSON
$.ajax({
url: "test.php" //Your request URI
}).done(function(data) {
//data (you can name it whatever you want) is the data that you get from your request.
//eg. if(data.checkbock){ //do something }
});
More informations here
I tried to find help via the search function on here but all the answers given to similar problems were too elaborate for me to understand, i.e. the example code was too complex for me to extract the parts which could have been relevant for my problem :(
I have a html form which sends userinput on a specific row in a datatable via an ajax-request to a php file, where the input gets inserted into my sqldb.
I have no problem sending the textinput entered by a user and also transferring additional infos like the specific row they were on, or the network account of the user. But i now want to add a checkbox, so the users can choose whether their comment is private or public. However i somehow cannot transmit the value from the checkbox, there is no error but also no checkboxdata inserted into the db.
Do i have to handle checkboxes differently than textareas? I'd be very grateful for help!
My code looks as follows:
Html:
function insertTextarea() {
var boardInfo = $( "<form id='boardComment'><textarea rows='2' cols='30'>Notizen? Fragen? Kommentare?</textarea>Privat:<input type='checkbox' name='privatcheckbox' value='private'><input type='submit' value='Submit'><input type='reset' value='Cancel'></form>");
$( this ).parent().append(boardInfo);
$("tbody img").hide();
$("#boardComment").on( "submit", function( event ) {
event.preventDefault();
var change_id = {};
change_id['id'] = $(this).parent().attr("id");
change_id['comment'] = $(this).find("textarea").val();
change_id['privatecheckbox'] = $(this).find("checkbox").val();
if( $(this).find("textarea").val() ) {
$.ajax({
type: "POST",
url: "boardinfo.php",
cache: false,
data: change_id,
success: function( response2 ) {
alert("Your comment has been saved!");
$("tbody img").show();
$("#" + change_id['id']).find("form").remove();
}
});
};
});
and this is the php part:
$id = mysql_real_escape_string($_POST['id']);
$comment = mysql_real_escape_string($_POST['comment']);
$privatecheckbox = mysql_real_escape_string($_POST['privatecheckbox']);
$sql="INSERT INTO cerberus_board_info (BOARD_INFO_COMMENTS, BOARD_INFO_USER, BOARD_INFO_CHANGE_ID, BOARD_INFO_ENTRY_CHANNEL, BOARD_INFO_PRIVACY_LEVEL) VALUES ('$comment', '$ldapdata', '$id', 'Portal', '$privatecheckbox')";
The following line:
change_id['privatecheckbox'] = $(this).find("checkbox").val();
Searches for a element with the tagname checkbox. Such an element doesn't exist, I believe you are trying to search for an <input> element with a type of checkbox.
The following should work for you:
change_id['privatecheckbox'] = $(this).find("input[type=checkbox]").val();
Or even better, the :checkbox pseudo selector:
change_id['privatecheckbox'] = $(this).find(":checkbox").val();
On a final note: Why shouldn't I use mysql_* functions in PHP?
This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
I am writing a program which I need to add php code inside script
The html has a table, with 2 chosen selectbox, I want to update 2nd selectbox when first when has been changed by user
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') //Check if first select box is changed
{
var itemcode = $(this).parent().parent().find('[data-id="item"]'); //find second select from same row
//add items from order
<?php
$ord = '<script>document.write(ord);</script>'; //javascript variable to php variable
//This code is not working, if I update the php variable from javascript variable
mysql_query('select * from ords where ord_id = '.$ord.');
?>
$(itemcode).append('<option>a</option>');
$(".chzn-select").trigger("liszt:updated");
}
});
Any ideas?
You could try sending the variables by using the jQuery load function.
page1.html:
<script type="text/javascript">
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') {
var itemcode = $(this).parent().parent().find('[data-id="item"]');
$('#ord').load('page2.php?ord='+ord);
$(itemcode).append('<option>'+$('#ord').html()+'</option>');
$(".chzn-select").trigger("liszt:updated");
}
});
</script>
<div id="ord"></div>
page2.php:
<?php
$ord = $_GET['ord'];
mysql_query('select * from ords where ord_id = '.$ord);
?>
Here's an example of how it could be done with AJAX. You probably need to adapt it to your needs. The idea was just to show you the basics of an AJAX request:
<script>
$('.chzn-select').chosen().change(function() {
var a = $(this).attr('data-id');
var ord = $(this).val();
if (a == 'ord') //Check if first select box is changed {
var itemcode = $(this).parent().parent().find('[data-id="item"]'); //find second select from same row
//add items from order
$.ajax({
url: "order.php",
type: 'POST',
data: {
ord: ord
},
cache: false,
success: function(data){
$(itemcode).append(data);
$(".chzn-select").trigger("liszt:updated");
}
});
}
});
</script>
Create a PHP file to handle the request and echo the HTML to be appended. This is just a rough example:
<?php
$ord = $_POST['ord'];
if (is_numeric($ord)){
$result = mysql_query('select * from ords where ord_id = '.$ord);
if ($result){
//process query result here
//create HTML string that will be appended
$str = '<option>'.$option.'</option>';
echo $str;
}
}
?>
PHP runs on server-side and prepares the page before the client-side javascript code is invoked. so, assuming this is a PHP file that contains javascript, be advised that best thing the PHP might do is prepare which javscript code will be in the page. if you want to pass javascript variable to PHP, you must SEND them from the client-side to the server-side (probably with $.POST command)
It does not work because $ord in literally the value of:
<script>document.write(ord);</script>
Which is no where near a id.
Try using the jquery post:
$.post("phpdoc.php", { name: ""+ord+""})//this sends the ord value to the php page
.done(function(data) {
alert("Data Loaded: " + data);//this will alert returned data
});