I need a sanity check here. I'm posting data through an AJAX call but for some reason it comes through as null.
javascript:
var data = {};
data['pkStudyYears'] = id;
data['years'] = [];
data['years']['pkStudyYears'] = id;
data['years']['fkStudyID'] = $('#fkStudyID').val();
data['action'] = action;
data['years']['intStartYr'] = $('#startYearBox').val();
data['years']['intEndYr'] = $('#endYearBox').val();
console.log(data['years']);
var posturl = '<?php echo site_url('manage/climate_indicators/updateStudyYears');?>'
$.when($.ajax({
type: "POST",
url: posturl,
data: data,
dataType: 'json'
}))
.done(function(result) {
console.log(result.status);
if (result.status === 'failed') {
console.log(result.errors);
}
});
php (updateStudyYears)
$postData = $this->input->post(NULL, true);
$yearArray = $postData['years'];
if(empty($yearArray)) {
echo json_encode(array('status'=>'failed', 'errors'=>'Years are empty'));
exit();
}
I keep getting a failed result with the error "Years are empty". I can't figure out what I'm missing!
Related
I am working with OT system.i have some problem regrading OT hours request program.this program send the department employee OT hours in to the admin panel notification and OT hours save in the database.my problem is when send OT request each person create the separate OT notification .I want send the single notification set of the department people.
$(document).on('click', '.overtime_send', function() {
temp = 0;
$('#employee_table tbody tr').each(function(row, tr) {
var emp_no = $(tr).find('td:eq(0)').text();
var ot_hours = $(tr).find('input').val();
//ot_array.push([emp_no,ot_hours]);
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_ot',emp_no : emp_no, ot_hours:ot_hours},
dataType:"json",
success:function(data)
{
if(data.success)
{
swal("Good job!", "OverTime Request Send Successfully!", "success");
temp = 1;
dataTable.ajax.reload();
}
}
});
});
alert(temp);//if data.success block execute but alert still get value as 0
if (temp == 1) {
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_comment'},
dataType:"json",
success:function(data)
{
if(data.success)
{
dataTable.ajax.reload();
}
}
});
}
i all ready got some solution .i get create the temp variable and OT request process successful it assign temp = 1 and after the each loop i try to insert notification data into the database.but if data.success success but alert(temp); not get value as 1 .how do i solve this question.
back end code
if($_POST["action"] == 'add_ot')
{
$today = date("Y-m-d");
$department = $_SESSION["dept_Id"];
$state = 5 ;
$emp_no = $_POST["emp_no"];
$ot_hours = $_POST["ot_hours"];
if($ot_hours != '00:00'){
$data = array(
':today' => $today,
':department' => $department,
':emp_no' => $emp_no,
':ot_hours' => $ot_hours,
':state' => $state
);
$query = "
INSERT INTO otresquest
(emp_id,date,ot_hour,dept_Id,overtime_status)
VALUES (:emp_no, :today, :ot_hours,:department,:state)
";
$statement = $connect->prepare($query);
if($statement->execute($data))
{
$output = array(
'success' => 'OT request has been Sent succesfully',
);
}
}
echo json_encode($output);
}
if($_POST["action"] == 'add_comment')
{
$today = date("Y-m-d");
$department = $_SESSION["dept_Id"];
$comment_status = 0 ;
$data = array(
':today' => $today,
':department' => $department,
':state' => $comment_status
);
$query = "
INSERT INTO comments
(dept_Id,date,comment_status)
VALUES (:department,:today,:state)
";
$statement = $connect->prepare($query);
$statement->execute($data);
}
**This might be solve your problem**
(document).on('click', '.overtime_send', function() {
temp = 0;
$('#employee_table tbody tr').each(function(row, tr) {
var emp_no = $(tr).find('td:eq(0)').text();
var ot_hours = $(tr).find('input').val();
//ot_array.push([emp_no,ot_hours]);
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_ot',emp_no : emp_no, ot_hours:ot_hours},
dataType:"json",
success:function(data)
{
swal("Good job!", "OverTime Request Send Successfully!", "success");
temp++;
dataTable.ajax.reload();
if (temp == 1) {
$.ajax({
url: 'otrequset_action.php',
type: 'POST',
data: { action:'add_comment'},
dataType:"json",
success:function(data)
{
if(data.success)
{
dataTable.ajax.reload();
}
}
});
}
}
});
});
swal({title: "No data entering?",text: "Not set the overtime hours !",type: "warning"});
});
I have a registraion php class that displays a form and when the registration button is clicked, calls a function in a login javascript file. This file uses ajax to post data to a index.php file. My index.php file cannot access this data, despite the post being a success (ajax success is true as the alert is being called).
Login.js
var loginData, urlPath;
// Allow users to log in or register
function Login() {
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val();
urlPath = "../index.php?action=register";
// Send the login/registration data to database
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
})
}
index.php
<?php
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->Begin();
// Client wants to register
if(isset($_GET['action'])) {
if($_GET['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}
?>
You used POST method of ajax. So send data also in POST manner like below:-
// Send the login/registration data to database
$(document).ready(function() {
var username = $("#usernameField").val();
var email = $("#emailField").val();
var password = $("#passwordField").val();
$.ajax({
type: "POST",
url: "../index.php",
data: {"username":username,"email":email,"password":password,"action":"register"},
success: function (result) {
alert(result);//check the change
}
});
});
And then change GET to POST at php end:-
<?php
require_once("Model/model.php");
require_once("Controller/controller.php");
require_once("View/view.php");
$model = new Model();
$view = new View();
$controller = new Controller($model, $view);
$controller->Begin();
// Client wants to register
//single condition can do the job and use POST instead of GET
if(isset($_POST['action']) && $_POST['action'] == "register" ) {
echo "hello"; //check the change
}
?>
Note:- Please take care of comments too.(added in the code)
loginData = "username=" + $("#usernameField").val() + "&email=" + $("#emailField").val() + "&password=" + $("#passwordField").val() + "&action=" + "register";
urlPath = "../index.php";
$(document).ready(function() {
$.ajax({
type: "POST",
url: urlPath,
data: loginData,
success: function (result) {
alert("success");
}
})
});
Try adding the action also in post data and receive it as $_POST
if($_POST['action']) {
if($_POST['action'] == "register") {
echo '<script type="text/javascript">alert("hello")</script>';
}
}
So i have a php file, that prints data from a table encoded on JSON format.
This is the php file:
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo "success";
else
echo "error";
}
echo json_encode($data);
?>
This is the javascript script:
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
if (data == "success") {
$.getJSON(url, function(result) {
console.log(result);
$.each(result, function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
});
} else if (data == "error") {
alert("error");
}
}
});
});
So basically i a have where i have all items from the database select (list_all.php), and then when i click on a single item, the ID of that item is passed on the URL, and i retrieve it on the otherside with javascript. I dont use GET because this is with phonegapp, so i use a .js file called getURI.js.
First, the function gets the ID that was passed. Then it posts to the PHP file, and the PHP file will get the ID, and make the query for that single item on the database. Is successed, i wanted to store all that data on variables. But for some reason, im getting an error on the console saying
POST http://192.168.1.241:3000/proxy/http%3A%2F%2Fpedrofidalgo.pt%2Fbilapoint%2Flistar_sitio_single.php 500 (Internal Server Error)
THe server is responding correctly because others scripts on the app are working.
In PHP
<?php
include "db.php";
$id=$_POST['id'];
$data=array();
$q=mysqli_query($con,"select * from `sitios` where `id_sitio`='$id'");
while ($row=mysqli_fetch_object($q)){
$data[]=$row;
}
if($q)
echo json_encode(array('status' => true, 'data' => $data));
else
echo json_encode(array('status' => false, 'data' => $data));
?>
In Jquery
$(document).ready(function() {
var id = decodeURI(getUrlVars()["id"]);
var dataString = "id=" + id;
$.ajax({
type: "POST",
url: "http://pedrofidalgo.pt/bilapoint/listar_sitio_single.php",
data: dataString,
crossDomain: true,
cache: false,
success: function(data) {
data = JSON.parse(data);
if (data['status']) {
$.each(data['data'], function(i, field) {
var id = field.id_sitio;
var nome = field.nome;
var descricao = field.descricao;
var img = field.img;
var morada = field.morada;
var coordenada_x = field.coordenada_x;
var coordenada_y = field.coordenada_y;
document.getElementById("titulo").innerHTML = nome;
document.getElementById("desc").innerHTML = descricao;
document.getElementById("morada").innerHTML = morada;
});
} else {
alert("error");
}
}
});
});
My script code like :
function changePrice(id) {
var url = '<?php echo $base_url ?>home/getprice/';
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
success: function(msg) {
alert(msg);
/*
"regular_price": "800",
"discount_price": 720
*/
}
});
}
I want to both regular price and discount price on separate variable.How??
If you are getting the response as "regular_price": "800", "discount_price": 720 then make it valid JSON, parse it and get the properties.
var obj = JSON.parse('{' + msg + '}');
// valid json -^-----------^-
// get object properties
var regular = data.regular_price;
var discount = data.discount_price;
UPDATE : If response data is valid JSON format then set dataType: 'json' option.
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
// set response datatype as json
dataType:'json',
success: function(msg) {
// get properties
var regular = msg.regular_price;
var discount = msg.discount_price;
}
});
Or parse it directly if the response is a string.
$.ajax({
url: url,
type: 'post',
data: 'id='+id,
success: function(msg) {
// parse the string
var data = JSON.parse(msg);
// get properties
var regular = data.regular_price;
var discount = data.discount_price;
}
});
Thanx to all..Here are the solution :
<script>
function changePrice(id)
{
var url = '<?php echo $base_url ?>home/getprice/';
$.ajax({
url:url,
type:'post',
data:'id='+id,
dataType:'json',
success:function(msg)
{
var regular = msg.regular_price;
var discount = msg.discount_price;
}
});
}
</script>
My Function :
$new = array (
"regular_price" => $result->price,
"discount_price" => $price
);
$newarray = json_encode($new, JSON_PRETTY_PRINT);
print_r($newarray);
Try this:
In server side ajax call:
$respose['regular_price'] = 120;
$respose['discount_price'] = 100;
echo json_encode($response);
In JS: Considering msg is an json object
var data = JSON.parse(msg);
var regular = data.regular_price;
var discount = data.discount_price;
I am using CI 3.0.1 was uploading and inserting image to db successfully before i used ajax, i guess trying to do it with ajax i'm missing something which isn't even sending data to upload maybe because we have to use multipart() in form while in ajax we are just sending data direct to controller, another thing i don't know how to receive the variable in response
my Ajax request function is:
<script type="text/javascript">
$(document).ready(function() {
alert("thirddddddddd");
$('#btnsubmit').click(function()
{
alert("i got submitted");
event.preventDefault();
var userfile = $("input#pfile").val();
alert("uploading");
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload', //how to receive var here ?
type: 'POST',
cache: false,
data: {userfile: userfile},
success: function(data) {
alert(data);
$('.img_pre').attr('src', "<?php echo base_url().'uploads/' ?>");
$('.dltbtn').hide();
},
error: function(data)
{
console.log("error");
console.log(data);
alert("Error :"+data);
}
});
});
});
And my controller Upload's function do_upload is:
public function do_upload()
{
$config['upload_path'] = './uploads/'; #$this->config->item('base_url').
$config['allowed_types'] = 'gif|jpg|png|jpeg';
$this->upload->initialize($config);
if ( ! $this->upload->do_upload('userfile'))
{
$error = array('error' => $this->upload->display_errors());
$this->load->view('layouts/header');
$this->load->view('home_page', $error);
$this->load->view('layouts/footer');
}
else
{
$data = array('upload_data' => $this->upload->data());
$imagedata = $this->input->post('uerfile');
$session_data = $this->session->userdata('logged_in');
$id = $session_data['id'];
$result = $this->model_edit->update_dp($id, $imagedata);
$image_name = $result->images;
$this->session->set_userdata('image', $image_name);
echo json_encode($name = array('image' => $image_name));
// $image_name = $this->upload->data('file_name');
// $data = array('upload_data' => $this->upload->data());
// redirect("account");
}
}
Now image is not even going to uploads folder, if any other file is needed tell me i'll post it here. Thanks
You cannot send file data using $("input#pfile").val();
var len = $("#pfile").files.length;
var file = new Array();
var formdata = new FormData();
for(i=0;i<len;i++)
{
file[i] = $("input#pfile").files[i];
formdata.append("file"+i, file[i]);
}
and send formdata as data from ajax
Hope it helps !
Try with the below ajax code
var formData = new FormData($('#formid'));
$.ajax({
url: '<?php echo base_url(); ?>upload/do_upload',
data: formData ,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data){
alert(data);
}
});
The file contents may not send through ajax as per your code. Try with the attributes mentioned in above code.