AJAX PHP function onchange select box - javascript

I have a problem about which I am very confused. I have a select box with s dynamically generated using a mysqli query:
$result = mysqli_query($db, "SELECT * FROM `users` WHERE `user_id` > 0");
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
while($row = $result->fetch_assoc()){
echo '<option value = '.$row['user_name'].'>'.$row['user_name'] . '</option>';
}
echo '</select></form>';
I am completely new to AJAX, but I need to use jquery and ajax to pass the this.value variable to a php variable for use in a later query.
Here is my script (most of which was found online):
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
$("#contacts").change(function() {
//get the selected value
var selectedValue = this.value;
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});
</script>
Now, when I click a value in the select box, nothing happens. There are no warnings or errors, etc.
Please help me.
p.s. function.php does exist. It is just a simple echo for now (for testing purposes)
UPDATE: HERE IS FUNCION.PHP:
<?php
/*$val = $_REQUEST['selectedValue'];
echo $val;*/
function function(){
$val = $_REQUEST['selectedValue'];
echo $val;
}
?>
UPDATE: Thank you everyone for all your help. I have now got it to work in that the network section of chrome inspect shows the function.php being requested however I still don't get the echo (I used external .js files to get it to work). My J query function is also successful (the success function echoes into the console)

Your select box has no ID and you are watching the change event of $("#contacts").
Change:
echo '<html><form name="contacts" method="post"><select name="contacts"><option value="Contact list" onchange="func()">Contact List</option>';
to:
echo '<html><form name="contacts" method="post"><select name="contacts" id="contacts"><option value="Contact list">Contact List</option>';
^^^^^^^^^^^^^ here
You also only need one event handler, so I have removed the inline one which doesn't seem to do anything anyway.
Edit: If the select is created using ajax as well, you need event delegation:
$("body").on('change', '#contacts', function() {
^^^^ for example
Edit 2: Your variable is called $_REQUEST['option'] and not $_REQUEST['selectedValue']. You are also not calling your -badly named - function so you will not get any output from php except from an error like Parse error: syntax error, unexpected 'function' ....

Call onchange function in select tag as below
echo '<form name="contacts" method="post"><select name="contacts" onchange="func(this.value)"><option value="Contact list">Contact List</option></form>';
Javascript src should be in head of the html page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
Add the above one in head of html. Update javacript as below
As onchange function is called in the select tag itself, following is enough
<script>
function func(selectedValue)
{
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
}
</script>
Updated php: If you must want to get value from function, you must call it. Otherwise, simply, you can make as below
<?php
if($_REQUEST['option'])
{
$val=$_REQUEST['option'];
echo $val;
}
?>

In .php file, receive it first-
$val = $_REQUEST['selectedValue'];
echo $val;

set an id attribute in your php code for the select tag and
please don't use the same value for the name attribute in form and select tags !!

just change your function to a 'body'.on, and give your elements an id of 'contacts'
$("body").on('change', '#contacts', function() {
//get the selected value
var selectedValue = $(this).val();
//make the ajax call
$.ajax({
url: 'function.php',
type: 'POST',
data: {option : selectedValue},
success: function() {
console.log("Data sent!");
}
});
});

Related

editableSelect() does not fire after ajax method

I have an ajax method that runs as soon as the page is loaded without listening to any event. The ajax fetches student ID from the database and shows the student ID in a select box. I want the select box to be editable (http://indrimuska.github.io/jquery-editable-select/). The function $('#studentID').editableSelect(); runs completely fine when the options are hardcoded in the select tag. However, no data is shown in the selectbox when $('#studentID').editableSelect(); is called and the data is fetched from the database.
Here is the code that is written in the JavaScript file
$('#studentID').editableSelect();
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
}
});
#studentID definition
<label for="studentID">ID</label>
<select id = "studentID" class="form-control">
</select>
php code
<?php
$connection = new mysqli ("127.0.0.1", "root", "", "test");
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
$query = "SELECT `SID` FROM `student` ORDER BY `SID` ";
$result1= mysqli_query($connection, $query);
while($row1 = mysqli_fetch_array($result1)):;?>
<option value="<?php echo $row1[0];?>"><?php echo $row1[0];?></option>
<?php endwhile;
$connection->close();
?>
Any help will be appreciated.
Move the editableSelect into the ajax.success method. The problem is that you are initializeing an empty select element, and then inserting it the options with the asynchronous ajax method. The success will forever happen after the data will successfully loaded, and then you can initialize the select with any framework/library, including editableSelect that you want to.
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
let student_el = $('#studentID');
student_el.html(html);
student_el.editableSelect();
}
});
EDIT:
you might not included the library in the right way, so for any case, here is the two ways to include it:
Inside the head tag
<head>
<!--Include jQuery + you libraries...-->
<script src="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js"></script>
<link href="https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.css" rel="stylesheet" />
</head>
Inside the ajax call
$.ajax({
type: 'POST',
url: './public/api/studentID.php',
success: function(html){
let student_el = $('#studentID');
student_el.html(html);
$.getScript("https://rawgit.com/indrimuska/jquery-editable-select/master/dist/jquery-editable-select.min.js")
.then(() => {
student_el.editableSelect(); // Call this function after the script have been successfully loaded.
});
//student_el.editableSelect();
}
});
Why don't you try calling editableSelect on your callback
$.ajax({
type:'POST',
url:'./public/api/studentID.php',
success:function(html){
$('#studentID').html(html);
$('#studentID').editableSelect();
}
});

Codeigniter weird ajax result in controller

I've started a codeigniter project and now a i have to do an ajax call to a special controller.
It goes something like this:
- I have two select fields: 1 for selecting county's and the other one must populate with the city's in the selected county.
The problem is I get a really weird result when I send the selected county id to the ajax controller.
If I put something like this in the controller : echo "a $county_id" in the controller it will give me the response : a [selected county_id], but if I only echo out the county id it shows some json empty response, and I don't know what's wrong, below is the code:
the ajax(jquery) call.
$(document).ready(function(){
$('#judet').change(function(){
var county = $( "select option:selected" ).val();
$.ajax({
type:'POST',
/*dataType: "json",*/
data:{cou_county:county},
url:'<?php echo base_url("ajax_controller/") ?>',
success:function(){
console.log('id_judet:' + county);
},
error:function(mesaj){
console.log("there's an error");
}
});
});
});
The codeigniter ajax_controller Controller:
public function index()
{ header('content-type text/html charset=utf-8');
$cou_county = $this->input->post('cou_county');
$decodedCounty = $cou_county;
echo "$decodedCounty";
}
The county and city selectors are two simple select inputs with id's I'll post some pictures if you think i haven't explained it well eneugh.
EDIT: the ajax call does access the controller, where i actually echo that id, but in the response i get some weird json thingy instead of the number, like in the picture below:
the response
Thanks for taking the time to read this, and thanks in advance to those of you who take the time to help a brother out.
You can't use PHP code in javascript:
<?php echo base_url("ajax_controller/") ?>
Instead, you should create a js variable like this:
base_url = '<?php echo base_url("ajax_controller/") ?>';
Then use this variable with your function.
In order to use base_url() you have to load url helper in controller like this..
$this->load->helper('url');
Or load in application/config/autoload.php.
Then in your ajax edit url to
url:'<?php echo base_url("ajax_controller/index");?>',
In controller:
public function index()
{
$cou_county = $this->input->post('cou_county');
echo $cou_county;
}
In ajax:
$.ajax({
type:'POST',
/*dataType: "json",*/
data:{cou_county:county},
url:'<?php echo base_url("ajax_controller/index");?>',
success:function(data){
console.log(data); //see your console
},
error:function(data){
console.log("there's an error");
}
});

Partial Update a list with AJAX

I have a list from the database and I want to implement edit functionality where in onclicking a table column, the column becomes editable and on clicking out of column, the value gets updated.
I have used AJAX for this purpose. My code is as under:
Page1.php
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
$(editableObj).css("background","#FDFDFD");
}
});
}
</script>
The column of my table is as under:
<td contenteditable="true" onBlur="saveToDB(this, 'exmid','<?php echo $p0; ?>')"
onClick="showEdit(this);"><?php echo $p3 ?>
Note: $p0 contains the serial no of row from mysql database table and $p3 contains the displayed text.
The code for page2.php is:
<?php
include_once 'includes/db_connect.php';
?>
<?php
$result = mysql_query("UPDATE examlist1 set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE sno=".$_POST["id"]);
?>
Problem:
When I click on the column it becomes editable. Using alert() inside saveToDB() I have checked that the function is called on clicking out of the column and also values of column and id are correct.
Then I tried the alert() function inside $.ajax and it was not called. I am not sure whether ajax is running or not. This is the first time I am trying to use ajax in a php code myself.
Please suggest what is the problem and what is the solution? The code is being implemented on a Linux based server hosted at Godaddy using PHP 5.4.
Also I would like to set the background color on fail. How to write it inside ajax block?
If you are getting the correct values when alerting.In your page2.php. Use mysqli instead of mysql and also use $connection object in mysqli_query().
<?php
include_once 'includes/db_connect.php';
$column=$_POST["column"];
$editval=$_POST["editval"];
$id=$_POST["id"];
$result = mysqli_query($connection,"UPDATE examlist1 SET $column='$editval' WHERE sno=$id");//$connection is database connection variable
if ($result)
{
echo json_encode(array('success'=>true));
}
else
{
echo json_encode(array('success'=>false));
}
?>
Here is Javascript: Try 100% works (Define what you want on if/else statement)
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
<script>
function showEdit(editableObj)
{
$(editableObj).css("background","#FFF");
}
function saveToDB(editableObj,column,id)
{
$.ajax(
{
url: "page2.php",
type: "POST",
data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
success: function(data)
{
var res=eval(data);
//if success then
if (res.success)
{
//write JS code that you want after successful updation
$(editableObj).css("background","#FDFDFD"); //<- according to problem
}
//if fails then
else
{
//write JS code that you want after unsuccess
}
}
});
}
</script>

Getting a variable from my form to my parser file via ajax

I'm a total AJAX noob, so please forgive me, but this is what I'm trying to do...
I have a php form that submits the information via ajax to a parser file. I need to get a few ids from that form to the parser file so I can use them in my sql update. I'll try to keep my code simple but give enough info so someone can answer.
My form is being generated via a foreach loop that iterates through a list of teams and grabs their various characteristics. For simplicity, let's say the main thing I need to get to the parser file is that team_id.
I'm not sure if I need to add
<input type="hidden" name="team_id" value="<?=$team->id ?>">
or
<tr data-teamid="<?=$team->id; ?>">
or something like that to my form....but either way, it gets passed through this AJAX file...
<script type="text/javascript">
function updateNames() {
jQuery('#form-message, #form-errors').html("");
var post_data = jQuery('form[name="update_names"]').serialize();
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
if(resp == 'success'){
jQuery('#form-message').html("Names and Scores have been Updated!");
}else{
jQuery('#form-errors').html(resp);
}
}
});
return false; // <--- important, prevents the link's href (hash in this example) from executing.
}
jQuery(document).ready(function() {
$(".linkToClick").click(updateNames);
});
</script>
And is making it to my parser file, which looks like this...
require_once '../core/init.php';
$db = DB::getInstance();
$errors = [];
// $camp_id = Input::get('camp_id');
$camp_id = 18;
//Find the Teams that Belong to the Camp
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
$teamsQ = $db->query($sql);
$all_teams = $teamsQ->results();
//validation and sanitization removed for simplicity.
if(empty($errors)){
$fields = [];
foreach($_POST as $k => $v){
if($k != 'camp_id'){
$fields[$k] = Input::get($k);
}
}
$db->update('teams',$all_teams->id,$fields);
echo 'success';
}else{
echo display_errors($errors);
}
SO. The main question I have is how do I get that camp_id and team_id into the parser file so I can use them to update my database?
A secondary question is this...is the fact that the form is being generated by a foreach loop going to make it difficult for the ajax to know which field to update?
So, how would I get that camp_id to
$sql = "SELECT * FROM teams WHERE camp_id = $camp_id";
And the team_id to
$db->update('teams',$all_teams->id,$fields);
I tried to break this down to the simplest form and it's still not getting to the function. This code...
<form name="update_names" method="post">
<input type="hidden" name="team_id" value="<?=$teams->id ?>">
<button onclick="updateNames();return false;" class="btn btn-large btn-primary pull-right">test</button>
<script type="text/javascript">
function updateNames() {
alert('test');
}
</script>
Gives me... Uncaught ReferenceError: updateNames is not defined
The jQuery .serialize() method uses the name attribute of an element to assign a variable name. It ignores the element's id, any classes and any other attribute. So, this is the correct format if using .serialize():
<input type="hidden" name="team_id" value="<?=$team->id ?>">
Looking at your ajax code, your parser file would be called parsers/update_names.php.
To verify that the desired field is getting to your parser file, add this to the top for a temporary test:
<?php
$tid = $_POST['team_id'];
echo 'Returning: ' .$tid;
die();
and temporarily modify the ajax code block to:
$.ajax({
url: 'parsers/update_names.php',
method: 'POST',
data : post_data,
success: function(resp) {
alert(resp);
{
});
return false;
If the ajax processor file (your "parser") receives the team_id data, then you will get that data returned to you in an alert box.
Thus, you can now determine:
1. That you are receiving the team_id information;
2. That the ajax back-and-forth communications are working
Note that you also can install FirePHP and echo text to the browser's console from the php processor file.

How do i make my php variable accessible?

I am trying to implement a timer. I learned this idea from a SO post.
<?php
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
}
?>
This is my php code. My php,html and JS codes are in the same page. I have a button in my html. When a user clicks on the html page, It will call a Ajax function
//url:"onlinetest.php",
//dataType: 'json',
beforeSend: function()
{
$(".startMyTest").off('click');
setCountDown();
}
It will call setCountDown() method, which contains a line at the very beginning
var days = <?php echo $remainingDay; ?>;
When i run the page, it says[even before clicking the button] "expected expression, got '<'" in the above line. My doubt is
Why this php variable get replaced before i am triggering the button. Please let me know hoe to solve this or how to change my idea.
The problem is, since initial load, $_POST values aren't populated (empty on first load),
That variable you set is undefined, just make sure you initialize that variable fist.
<?php
// initialize
$remainingDay = 1;
if(($_SERVER['REQUEST_METHOD'] === 'POST') && !empty($_POST['username']))
{
//secondsDiff is declared here
$remainingDay = floor($secondsDiff/60/60/24);
echo json_encode(array('remaining_day' => $remainingDay);
exit;
}
?>
<script>
var days = <?php echo $remainingDay; ?>;
$('.your_button').on('click', function(){
$.ajax({
url: 'something.php',
dataType: 'JSON',
type: 'POST',
beforeSend: function() {
// whatever processes you need
},
success: function(response) {
alert(response.remaining_day);
}
});
});
</script>
That is just the basic idea, I just added other codes for that particular example, just add/change the rest of your logic thats needed on your side.
You can pass a php variable into JS code like
var jsvariable ="<?php echo $phpvariable ?>";
NOTE:
If you ever wanted to pass a php's json_encoded value to JS, you can do
var jsonVariable = <?php echo $json_encoded_value ?>; //Note that there is no need for quotes here
Try this,
var days = "<?php echo $remainingDay; ?>";

Categories