I want to populate my div minimal_table through ajax onchange event based on the chosen dropdown value. The <div class="minimal_table"> is the area of my page that I want to update every time I choose a value from my dropdown form. However, after my contents load, it returns no values from my database. I have checked the value being passed in my javascript using alert but it returns a right value. I also notice that it seems like it doesn't return true in the other_function.php if(isset($val_id))line even if I already chosen a value in the dropdown. Can somebody help me point out what is the wrong of my codes and what I am lacking? Thanks a lot. Here are my codes:
my_courses.php (ajax part)
$(':input').change(function(event){
event.preventDefault();
$('.minimal_table').html('<img src="../images/loading_trans.gif" style="position:relative; margin:350px; margin-top:250px;" />');
alert($(this).val());
var val_id = $(this).val();
var postData = {'val_id':val_id};
$.ajax({
url: "../includes/other_functions.php",
async: false,
type: "POST",
data: postData,
dataType: "html",
success: function(data){
setTimeout(function(){
$('.minimal_table').html(data);
},2000);
console.log(data);
},
});
});
other_functions.php
<?php
function ajax_request_val(){
$val_id = $_POST['val_id'];
$field = "course_type";
if(isset($val_id)){
$plans = db::getTable('plan',$field,$val_id);
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event',$field,$val_id);
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
else{
$plans = db::getTable('plan');
foreach ($plans as $plan) {
if (eventAccessLevel(null, $plan['plan_id']) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails(null, $plan['plan_id']);
$pid_shown[] = $plan['plan_id'];
}
}
$events = db::getTable('tbl_event');
foreach ($events as $event) {
if (!in_array($event['plan_id'], $pid_shown)) {
$event_id = $event['event_id'];
if (eventAccessLevel($event_id, null) != EVENT_ACCESS_NONE) {
$course_array[] = getCourseDetails($event_id, null);
}
}
}
return $course_array;
}
}
?>
databaseconnect.php
public static function getTable($tableName,$field='',$type_id='') {
if (!self::$db) self::connect();
if(!empty($type_id)){
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '` WHERE `'. $field .'` = `'. $type_id .'`;');
}
else{
$tableName = self::$db->escape_string($tableName);
return self::getObjects('SELECT * FROM `' . $tableName . '`;');
}
}
Output:
Initial load
Loading the form dropdown menu search
Choosing value from dropdown returns right value indicated by an alert
After content load (returns no value on the div mini_table)
In other_functions.php you define the function ajax_request_val().
As far as I can see, there is no call to that function within the same file, so when you call it with Ajax, you just define the function and never call it.
You make an ajax call to other_functions.php but that file only contains a function that is never called.
There are lots of ways to approach this and tidy it up a bit but to fix the problem quickly you could try putting this at the top of other_functions.php:
if(isset($_POST['ajax'])){ echo ajax_request_val(); }
and then change the data in your ajax call as follows
var postData = {val_id:val_id, ajax:1 }
Related
I'm trying to populate my form with the server copy of my json array, but it seems to be pulling from the local copy. Right now I have a function that populates the form when I click on a rectangle (each of which represents a json object in the array).
For example, if I change the select option attributeName on the form and submit, it saves the change correctly to the server in the json array, but when I click on a different rectangle and come back to the rectangle with the change, it doesn't populate the form field with the change (doesn't pull from the server json array).
If I load a different array, or if I refresh the page, then it works...how can I get my local copy of the array to reflect the change without refreshing?
Here is the function:
$(function() {
function populateForm() {
var matchingWidth = $('#canvas-overlay > .rectangle.targeted').width();
$(".rectangle.null").each(function() {
if ($(this).width() === matchingWidth) {
var ID_clicked = $(this).attr('id');
// populate form function
function populate(frm, data) {
$.each(data, function(key, value){
var ctrl = $('[name='+key+']', frm);
switch(ctrl.prop("type")) {
case "radio": case "checkbox":
ctrl.each(function() {
if($(this).attr('value') == value) {
$(this).prop("checked", true);
$("#attribute-form .ui.radio.checkbox").removeClass('checked');
$(this).parent().addClass('checked');
}
});
break;
default:
ctrl.val(value);
}
});
}
var selection = $('#templateSelection > option:selected').text();
// create variable for and expose JSON
var json = (function () {
var json = null;
$.ajax({
'async': false,
'global': false,
'url': 'server/php/data/' + selection,
'dataType': "json",
'success': function (data) {
json = data;
}
});
return json;
})();
// search json for index value that matches id clicked
// and populate form with associated object
json.some(function(e) {
if (e.ID === ID_clicked) {
var values = json.map(function(e) { return e.ID; });
var index = json.map(function(e) { return e.ID; }).indexOf(ID_clicked);
var data = JSON.stringify(json[index]);
populate('#attribute-form', $.parseJSON(data));
return true; // stops the "loop"
}
});
}
});
}
$(document).on('click', '#canvas-overlay > .rectangle', function() {
$('#canvas-overlay > .rectangle').removeClass('targeted');
$(this).addClass('targeted');
populateForm();
});
});
and for reference here is process.php which is the action when submitting:
<?php
$filename = $_POST['store-template-name'];
$myFile = "data/" . $filename;
$arr_data = array(); // create empty array
try
{
//Get form data
$formdata = array(
'ID'=> $_POST['ID'],
'attributeName'=> $_POST['attributeName']
);
//Get data from existing json file
$jsondata = file_get_contents($myFile);
// converts json data into array
$arr_data = json_decode($jsondata, true);
$updateKey = null;
foreach ($arr_data as $k => $v) {
if ($v['ID'] == $formdata['ID']) {
$updateKey = $k;
}
}
if ($updateKey === null) {
array_push($arr_data,$formdata);
} else {
$arr_data[$updateKey] = $formdata;
}
$jsondata = json_encode($arr_data);
if(file_put_contents($myFile, $jsondata)) {
echo 'Data successfully saved';
}
else
echo "error";
}
catch (Exception $e) {
echo 'Caught exception: ', $e->getMessage(), "\n";
}
?>
get requests are cached, either have serverside set proper no cache headers or set cache to false in jQuery.
$.ajax({
'async': false,
'global': false,
cache: false,
'url': 'server/php/data/' + selection,
'dataType': "json",
'success': function (data) {
json = data;
}
});
And do yourself a favor and refactor your code to not by synchronous. Synchronous calls are a bad idea. The code after the json code should live in the success callback or use done which is the recommended way with jQuery.
i have problem with my multilevel dependent select lists, i have six select lists dependent on each other and i have write a code to create dynamic lists using jquery. selects named as district, tehsil, project, center, school and user. it is working fine when i choose all options in a sequence, district-> tehsil-> project -> center -> school -> user, and when i change sequence at any level like district -> tehsil -> district( here district is parent of tehsil) after clicking on parent child tehsil not refreshed, and this problem exist in all hierarchy.... this jquery code calls 6 controller and models. those are not include here due to length of question. what should i do ?
this is my jquery code
$('#districts_id,#tehsils_id,#projects_id,#centers_id,#schools_id').on('change', function() {
//alert($("#districts_id option:selected").attr("title"));
//var parameters = {};
var parameters;
var url;
if($('#schools_id').val())
{
$("#users_id").removeAttr('disabled');
//parameters = JSON.stringify({schools_centers_id:$('#centers_id').val()});
parameters = {"users_schools_id": $('#schools_id').val(), users_gender: $('#gender').val()};
url = "<?php echo base_url();?>/BtaAdministratorUnionMembers/get_teachers_users_by_school_id";
}
else if($('#centers_id').val())
{
$("#schools_id").removeAttr('disabled');
//parameters = JSON.stringify({schools_centers_id:$('#centers_id').val()});
parameters = {"schools_centers_id": $('#centers_id').val()};
url = "<?php echo base_url();?>/BtaAdministratorUsers/get_schools_by_center_id";
}
else if($('#projects_id').val())
{
$("#centers_id").removeAttr('disabled');
//parameters = JSON.stringify({centers_probject_id:$('#projects_id').val()});
parameters = {"centers_probject_id": $('#projects_id').val()};
url = "<?php echo base_url();?>/BtaAdministratorUsers/get_centers_by_project_id";
}
else if($("#tehsils_id option:selected").attr("title") == 'tehsils_id')//($('#tehsils_id').val())
{
$("#projects_id").removeAttr('disabled');
//parameters = JSON.stringify({projects_tehsil_id:$('#tehsils_id').val()});
parameters = {"projects_tehsil_id": $('#tehsils_id').val()};
url = "<?php echo base_url();?>/BtaAdministratorUsers/get_projects_by_tehsil_id";
//alert(parameters + ' '+ url);
}
else if($("#districts_id option:selected").attr("title") == 'districts_id')//($('#districts_id').val())
{
$("#tehsils_id").removeAttr('disabled');
//$("#tehsils_id").empty();
//parameters = JSON.stringify({tehsils_districts_id:$('#districts_id').val()});
parameters = {"tehsils_districts_id": $('#districts_id').val()};
url = "<?php echo base_url();?>/BtaAdministratorUsers/get_tehsils_by_districts_id";
//alert(parameters + ' '+ url);
}
$.ajax({
type: "GET",
url: url,
data:parameters,
//contentType: "application/json;charset=utf-8",
dataType: 'json',
success: function(data){
//alert(data);
//alert(JSON.stringify(data));
if($('#schools_id').val())
{
//alert(JSON.stringify(data));
$('#users_id').empty();
$('#users_id').append("<option value=''>Select Teacher....</option>");
$.each(data,function(key,value){
$('#users_id').append('<option value="'+value.users_id+'">'+value.users_firstname_users_lastname+'</option>');
});
}
else if($('#centers_id').val())
{
//alert(JSON.stringify(data));
$('#schools_id').empty();
$('#schools_id').append("<option value=''>Select School....</option>");
$.each(data,function(key,value){
$('#schools_id').append('<option value="'+value.schools_id+'">'+value.schools_name+'</option>');
});
}
else if($('#projects_id').val())
{
//alert(JSON.stringify(data));
$('#centers_id').empty();
$('#centers_id').append("<option value=''>Select Center....</option>");
$.each(data,function(key,value){
$('#centers_id').append('<option value="'+value.centers_id+'">'+value.centers_schoolName+'</option>');
});
}
else if($("#tehsils_id option:selected").attr("title") == 'tehsils_id')//($('#tehsils_id').val())
{
//alert(JSON.stringify(data));
$('#projects_id').empty();
$('#projects_id').append("<option value=''>Select Project....</option>");
$.each(data,function(key,value){
$('#projects_id').append('<option value="'+value.projects_id+'">'+value.projects_name+'</option>');
});
}
else if($("#districts_id option:selected").attr("title") == 'districts_id')//($('#districts_id').val())
{
//clearDropDown($('select'), 5);
$('#tehsils_id').empty();
$('#tehsils_id').append("<option value='' title=tehsils_id>Select Tehsils....</option>");
$.each(data,function(key,value){
$('#tehsils_id').append('<option value="'+value.tehsils_id+'" title=tehsils_id>'+value.tehsils_name+'</option>');
});
}
},
error: function(data){
alert(JSON.stringify(data));
//console.log(data);
}
});
});
In each level you have to remove all next options when a top level option is changed and the set the next level again e.g in school level:
$('#schools_id').nextAll("select").each(function(){
$(this).find('option').remove();
})
// Then set again the next level
I used nextAll assuming that selects are siblings. elsewhere you have to use propper selector
With all of your if else statements organized from the most specific to least specific, fiddling with a parent input triggers the event handler but is caught by the else statement for its child.
Use separate event handlers for all six inputs based on the one you are interacting with rather than checking for values alone, and your logic will work morelike you planned.
You'll even be able to more easily handle the case where the user is jumping back a few levels and you should reset/disable a few selects.
I am trying to implement a "like" button for my website. I am using Codigniter, Ajax and Jquery. When the like button is clicked data should be entered to database and if unlike button is pressed data should delete from database. But I am facing a problem in model, data is not added to database when I click like button. Please help me to find a solution.
This is my Jquery file "likeitem.js"
function likeItem(postId)
{
if ($("#likeItem_"+postId).text() == "Like")
{
$("#likeItem_"+postId).html('Unlike');
var purpose = "Like";
}
else
{
$("#likeItem_"+postId).html('Like');
var purpose = "UnLike";
}
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "purpose=" + purpose,
success : function()
{
}
});
return false;
}
This is my model "usermodel.php"
public function itemLike()
{
$id = $this->session->userdata('userID');
$postId = $this->input->post('postId');
$purpose = $this->input->post('purpose');
if($purpose=="Like")
{
// echo 'test';
// exit();
$data = array(
"userID" => $id,
"postTextID" => $postId,
);
$this->db->insert('like', $data);
}
else
{
echo 'hai';
}
}
This is my view file "home.tpl"
<li><a class="like-unlike" href="#" id="likeItem_{$item['postID']}" onclick="likeItem({$item['postID']})">Like</a></li>
This is my Controller "user.php"
public function likeItem()
{
$this->usermodel->itemLike();
}
You mistake here. You forgot to put & symbol. Try this code.
data : "postId=" + postId + "&purpose=" + purpose,
Full code:
If you want to manipulate result returned from ajax, you can do something on success block as following code :
$.ajax({
type : "POST",
url : "http://localhost/codeig_smarty/index.php/user/likeItem",
data : "postId=" + postId + "&purpose=" + purpose,
success : function(data)
{
// do seomthing here with data
// console.log(data) --> to see data return or not
}
});
Im having some trouble here with a website im trying to renew.
In the head a script is called with the name "jquery.script.js" with some code
$.ajax({
url: 'function.js.php?option=urlget&id='+movie_id,
dataType: 'json',
success: function(data){
fanarturl = data['url'];
alert(fanarturl);
alert(data.toSource());
if (data) {
$('#background').fadeOut(500, function(){
$(this).delay(100).attr('src', 'cache/'+movie_id+'_f.jpg');
$(this).fadeIn(500);
})
}
}
});
So this call's a file with the name "function.js.php".
if ($option == 'urlget') {
require('function.php');
$fan = get_fanart($mysql_tables, $_GET['id']);
$fan_js = array(
'url' => (isset($fan['url']) ? $fan['url'] : ''),
);
echo json_encode($fan_js);
}
And this call's a function with is:
function get_fanart($mysql_tables, $movie_id) {
$pos = strrpos($movie_id, "_");
$MovieID = substr($movie_id, ($pos + 1));
if(is_numeric($MovieID)){
$img_sql = 'SELECT id, url FROM ' . $mysql_tables[5]. ' WHERE type="fanart" AND id="'.$MovieID.'"';
$img_result = #mysql_query($img_sql);
if ($img_result) {
$get_img = mysql_fetch_assoc($img_result);
foreach($get_img as $key => $val) {
$fanart[$key] = $val;
}
}
return $fanart;
}}
The alart of the "jquery.script.js" show's : ({url:""})
Now the supid thing is that when I copy the code from "function.js.php" to "index.php"
It show's this: {"url":"http://image.tmdb.org/t/p/original/A82GPC0XeoZMBWDYTe4Dba32cme.jpg"}
Why is this URL not passed on to the "jquery.script.js" file?
Thanks in advance!
At the start of function.js.php you've got this:
if ($option == 'urlget') {
It shouldn't be $option, it should be $_GET['option']. (Or something like that - my PHP is a little rusty.)
Admittedly this sort of answer is more suited to codereview.stackexchange.com but your code has tons of ambiguities and a security vulnerability.
var promise = $.ajax({
url: 'function.js.php?option=urlget&id='+movie_id,
dataType: 'json'
});
// This makes for better readability than a nest of callbacks
promise.done(function(data){
console.log(data);
$('#background').fadeOut(500, function(){
$(this).delay(100)
.attr('src', 'cache/'+movie_id+'_f.jpg')
.fadeIn(500);
});
});
promise.fail(function(data){
console.log('oh noes!', data); // #todo what do we do when 'function.js.php' fails?
});
function.js.php. Notice that we return different HTTP response codes depending on the results.
// #todo fill in db credentials
$db = new PDO('mysql:host=localhost;dbname=test', $user, $pass);
$option = $_GET('option');
if ($option === 'urlget') {
require('function.php');
$fan_art = get_fanart($mysql_tables, intval($_GET['id']), $db);
if ($fan_art && count($fan_art)) {
http_response_code(200);
echo json_encode($fan_art);
} else if (is_array($fan_art)) {
http_response_code(404);
echo json_encode(array('errors' => array('no fan_art found')));
} else {
http_response_code(500);
echo json_encode(array('errors' => array('an error occured when fetching fan art')));
}
}
function.php. Notice that here we pass in the database connection and use bound parameters to insert variables into our SQL.
/**
*
* #param [String] $table - the table to fetch data from
* #param [Int] $movie_id
* #param [PDO] $db - A PDO database connection
* #return [False, Array] Returns false if query fails, otherwise returns array of results
*/
function get_fanart($table, $movie_id, $db) {
$statement = $db->prepare( "SELECT id, url FROM :table WHERE type = 'fanart' AND id = :id" );
$sth->bindParam(':table', $table); // default param type is string
$sth->bindParam(':id', $movie_id, PDO::PARAM_INT);
if ( $sth->execute() ) {
return $sth->fetchAll();
} else {
return false;
}
}
On a side comment, your file & variable naming scheme is pretty horrible. Naming a file .js.php implies that the PHP file renders javascript. Also naming your files function or functions is a maintainence nightmare - why not fan_art.json.php and fan_art.php.
I am trying to update and get the updated row at a time from database in ajax call
JS in ready function
$("button[name='teacher_lock_exam']").on(ace.click_event, function () {
var current_exams_id = $(this).attr('id');
bootbox.confirm("Are you sure you want to lock the exam? <br/><br/>" +
"Locked exam cannot be modified until exam committee unlock it.", function (result) {
if (result) {
lock_exam(current_exams_id);
bootbox.alert("Your Exam has been Locked !<br/><br/> Contact with Exam committee to modify that exam again.");
}
});
});
function lock_exam(current_exams_id) {
$.ajax({
url: "teacher_internal_exam_management/lock_exam/" + current_exams_id,
type: "POST",
dataType: "json",
success: function (row) {
alert('success');
alert(row[0].access_status);
}
});
}
My teacher_internal_exam_management controller
public function lock_exam($current_exams_id)
{
$this->load->model('teacher_internal_exam_management_model');
$this->teacher_internal_exam_management_model->lock_exam($current_exams_id);
echo (json_encode($this->teacher_internal_exam_management_model->get_exam_details($current_exams_id)));
}
My teacher_internal_exam_management_model Model
function lock_exam($current_exam_id, $data)
{
$this->db->query("update current_exams set access_status = 'locked' where current_exams_id='".$current_exam_id."'");
}
function get_exam_details($exam_id)
{
$query = $this->db->query("select * from current_exams
where
current_exams_id = '" . $exam_id . "'
");
return $query->result();
}
Now the ajax call is updating the data but the row is not returned by the echo in the controller.Means the success function of ajax is not running. Why this is not working? Is there any problem in the code?
The very last line of your model:
return $query->result();
http://ellislab.com/codeigniter/user-guide/database/results.html
This function returns the query result as an array of objects, or an empty array on failure.
This is returning an array of objects.
You have to convert it appropriately -
return $query->result_array();
According to the php manual at http://www.php.net/manual/en/class.mysqli-result.php, I do not see a result() method for the type mysqli_result. I think you need to use
return $query->fetch_all();
instead of
return $query->result();