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
});
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 an ajax call which pulls data from the table and then transforms into a JSON object
Because I am also doing a lot with PHP as well I need to have a 2nd AJAX call
immediately after the first that will update $_SESSION info
I have tried putting
$_SESSION['company_id'] = $_POST['companyid'];
in the same file that handles the 1st AJAX call but it then doesn't process the data from the first call, hence I need to do the 2nd call
Here is my jQuery Code for the 1st and 2nd AJAX query
$(".showcompinfo").click(function(){
$("#comptable").hide();
$("#showcomptable").show();
var id = $(this).attr('id');
$("#comp_info").toggle();
var companyid = id;
var dataString = "companyid="+companyid;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/dataforms/complist.php",
data: dataString,
success: function(result){
var jsonObject = JSON.parse(result);
// here you can do your magic
var approved = jsonObject.customer_approved;
$("#showcompname").text(jsonObject.name);
// Get Reg Address Details - Check if any field is empty
var regoffice_2 = '';
var regoffice_3 = '';
var regoffice_city = '';
console.log(jsonObject.regoffice_city);
if(jsonObject.regoffice_2)
{
regoffice_2 = ', ' + jsonObject.regoffice_2;
};
if(jsonObject.regoffice_3)
{
regoffice_3 = ', ' + jsonObject.regoffice_3;
};
if(jsonObject.regoffice_city)
{
var regoffice_city = ', ' + jsonObject.regoffice_city;
};
var addlne1 = jsonObject.regoffice_1;
var regaddress = jsonObject.regoffice_1 + regoffice_2 + regoffice_3 + regoffice_city;
$("#addline1").val(jsonObject.regoffice_1);
$("#addline2").val(jsonObject.regoffice_2);
$("#addline3").val(jsonObject.regoffice_3);
$("#addcity").val(jsonObject.regoffice_city);
$("#addcounty").val(jsonObject.regoffice_county);
$("#countryselected").val(jsonObject.regoffice_country);
$("#countryselected").text(jsonObject.regoffice_country);
$("#addpostcode").val(jsonObject.regoffice_postcode);
console.log(regaddress);
if(approved == '1')
{
$("#approvedcust").text('Yes');
} else {
$("#approvedcust").text('Customer but Not Approved');
};
}
});
// 2nd Ajax
var companyid2 = jsonObject.company_id;
var dataString2 = "companyid="+companyid2;
$.ajax({ /* THEN THE AJAX CALL */
type: "POST",
url: "../inc/updatesession.php",
data: dataString2,
success: function(){
}
});
//
Here is the PHP code for complist.php
if(!empty($_POST['companyid']))
{
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$newdata = json_encode($result);
}
}
print_r($newdata);
If anyone can help even consolidate this into 1 ajax query or help me get 2 calls
working correctly it would be much appreciated
** EDIT **
OK I now have it displaying the Company ID in the session variable however when the user clicks to view a different company info result the session company_id does not update
I have changed the complist.php to the following
if(!empty($_POST['companyid']))
{
unset($_SESSION['company_id']);
$companyid = $_POST['companyid'];
$query = mysqli_query($dbc,"SELECT * FROM `comp_companies` WHERE `company_id` = '$companyid'");
$result = mysqli_fetch_assoc($query);
if($result){
$_SESSION['company_id'] = $_POST['companyid'];
$newdata = json_encode($result);
}
}
print_r($newdata);
My thinking behind the above was that once the ajax call is made it immediately unsets the session variable company info
then once a result is found for the selected company it resets the session var company_id with the new value, however its not updating the session variable
Screenshots showing what I mean
Your code updates your session variable successfully. However, since you're making an AJAX call, only the code in the PHP script directly called by the AJAX ("complist.php" in this case) is executed on the server. None of the PHP code which originally used to create your page is run again - this is why you have to use JavaScript to populate the rest of your newly selected company details.
To update the ID on screen following the AJAX call, all you need to do is follow the pattern you've used to update the rest of the fields
Change your HTML so the element which contains the company ID has an ID which lets JavaScript identify it:
<span id="showcompname"></span><span id="showcompid"><?php echo $_SESSION['company_id'];?></span>
and then in the "success" callback of your AJAX code, write
$("#showcompid").text(jsonObject.company_id);
This is exactly the same concept as the other JavaScript code you've got e.g. to update the "showcompname" element.
Meanwhile, the value stored in your PHP session will be used next time you run the PHP code which updates the whole page (e.g. by refreshing the page).
I have the following code:
<?php
$query=mysqli_query($mysqli, "SELECT assignment,a_id FROM assignments WHERE groupid='".$groupid."'");
$assignments = array(); // create empty assignments array
while ($row=mysqli_fetch_array($query)){
echo'<td class="columnname" id="'.$row['a_id'].'" contenteditable="true">'.$row['assignment'].'</td>';
$assignments[$row['a_id']] = $row['assignment']; // add assignment to array
}
?>
<script>
$('.columnname').keyup(function() {
delay(function(){
var text= $(this).text();
var id= $(this).attr('id')
$.ajax({
type:"POST",
url:"updateassignment.php",
data:{text:text, id:id},
success:function(data){
console.log('success bro!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
Basically what happens, is that i have a contenteditable and whenever that is keyup (which means whenever user types in info), it will post the data to the php file updateassignment.php which updates the values. However, it doesnt seem to work for me, it gives me the success result, but shows no error. Its sort of not getting the values from the fields, but as you can see, im using $(this) which refers to the columnname class (which is generated dynamically by php)
The php updateassignment file code is below:
<?php
include_once("config.php");
if (isset($_POST['id']) && isset($_POST['text'])) {
$id=$_POST['id'];
$text=$_POST['text'];
$query=mysqli_query($mysqli, "UPDATE assignments SET assignment='$text' WHERE a_id='$id'")or die(mysqli_error($mysqli));
}
?>
I have a feeling that the this is not refering the correct element, therefore contenteditable's ajax is unable to grab the correct value.
I found the answer.
It was because i defined the ajax this inside the delay function, so it would not reference the columnname. The way to solve this is to define $(this) outside of the delay function.
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.
I am having a problem with seeing one of my variables on a webpage. Here is what I have so far.
$(document).ready(function() {
$(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = '$("#ID").val()'
$.ajax({
type: "POST",
url: "test_wID.php",
data: "id",
success: function(data) {
$('#rightselection').html(data)
}
});
});
});
});
This is the jquery function I am using to take an ID entered into a form and use that ID with a bash script.
Here is the php.
<?php
//Get the ID from the HTML form and use it with the check chunk script.
$id = $_POST['ID'];
if (is_null($id)){
echo "$id is null";
}
echo "Selected test Game ID: ".$id;
//print shell_exec('/opt/bin/tester $id');
?>
I commented out the script because the variable is returning null, at this point I am just trying to make sure that I get the ID.
For completeness here is the form I'm using.
print "<p><h3>ID: <input type=\"text\" id=\"ID\" /></h3></p>";
#print "<br>";
print "<p><button id=\"CheckID\">Check ID</button></p>";
When i click the button I get the message in my div that the variable is null. So my question is am I missing something in the declaration? How is it that the var id is null?
Thanks for any help provided.
You should consider changing your jQuery code to:
$.ajax({
type: "POST",
url: "test_wID.php",
data: {id: $("#ID").val()},
success: function(data) {
$('#rightselection').html(data)
}
});
You mixed up strings and variable references at two points.
First, the statement var id = '$("#ID").val()' assigns just a string to your if variable and not the return value of the jQuery call. So just remove the ' here.
Second, the data parameter you're giving to the ajax() call again consists just of a string "id" and not the respective value. Here you need to change to {'id': id}.
So after correcting everything, your code should look like this:
$(document).ready(function() {
$("#CheckID").click(function() {
// submit ajax job and display the result
var id = $("#ID").val();
$.ajax({
type: "POST",
url: "test_wID.php",
data: {'id': id},
success: function(data) {
$('#rightselection').html(data);
}
});
});
});
Sidenote: Try to put all ;, where they belong. This prevents some errors, which can be hard to track!
EDIT
As pointed out in the comment by #FlorianMargaine you only need one wrapper not two around your code.
Firstly, the two following snippets are equivalent:
$(document).ready(function() {
});
// Is equivalent to:
$(function() {
});
So your code does the same as:
$(document).ready(function() {
$(document).ready(function() {
});
});
Plain useless, right?
Secondly, this line is plain wrong:
var id = '$("#ID").val()';
You're passing a string to the id variable. $('#ID').val() is not evaluated. This is the equivalent of doing this in PHP:
$id = '$_POST["id"]';
Which is just wrong, right?
You want this:
var id = $('#ID').val();
By the way, this variable naming could be improved, the same goes for the HTML ID.
Thirdly, you're doing the same mistake in the data option of $.ajax:
data: 'id'
You're just passing a string to the data option. You want the value of the id variable.
Then, if you absolutely want a string, I don't recommend it. jQuery expects a special kind of string. You better pass an object. Like this:
data: {
id: id
}
Do you see why the variable naming is wrong? You can't differentiate the property from the value. If you had done the following:
var idValue = $('#ID').val();
You could use this:
data: {
id: idValue
}
Which is way more readable.
In your $.ajax call you need to do:
data : { id: id }
If you want to pass parameters in an AJAX call you need to pass a string similar to the GET string you see in urls. So something like: d=123&name=test
Change the line
var id = '$("#ID").val()'
To
var id = 'id=' + $("#ID").val();