Ajax POST is sending empty parameters - javascript

UPDATE - I've solved the problem
I found the problem, it was the property of the post_max_size in php.ini which was set to 8MB. After changing it to 20MB everything worked as it should. Thanks for pointing out some syntax problems in the code.
Original post
I have this code in the body tag of a page:
<script type = "text/javascript" >
$(document).ready(function() {
var scriptPath = "<?php echo $jobJSPath[0]; ?>";
if (scriptPath != "") {
var hasInput = "<?php echo $hasInput; ?>";
var jobExecIp = "<?php echo $jobtekerIP; ?>";
var sentToExec = "<?php echo $sentToExececution;?>";
var hasOutput = <?php echo json_encode($allOutputVarName);?>;
$.getScript(scriptPath, function(data, textStatus, jqxhr) {
var jobBatchID = "<?php echo $jobsArray[0];?>";
var jobID = "<?php echo $jobsArray[1];?>";
var jobName = "<?php echo $jobsArray[2];?>";
// execute a function inside the script has no input parameter
if (typeof hasInput !== 'undefined' && hasInput === 'no'){
// execute a function inside the script with no input parameter
var returnVar = <?php echo $newJobName; ?>;
}
// execute a function inside the script has input parameter
if (typeof hasInput !== 'undefined' && hasInput === 'yes'){
var vars = [];
// create an array of all the paths of the input variables
var arrayFromPHP = <?php echo json_encode($newAllInputVarPath);?>;
for (var i = 0; i < <?php echo sizeof($newAllInputVarPath);?>; i++) {
vars.push(JSON.parse($.ajax({type: "GET", url: arrayFromPHP[i], async: false, cache: false}).responseText));
}
// execute a function inside the script with multiple input parameter
var returnVar = <?php echo $jobsArray[2]; ?>.apply(this, vars);
}
// get the execution status
var execMessage = textStatus;
// for the jobs without any return parameter
if (hasOutput.length = 1 && hasOutput[0] === "NULL") {
var result = "No parameters are being returned";
$.ajax({
url: 'executedJobs.php',
type: 'POST',
data: {results : result, job_batch_id : jobBatchID, job_id : jobID, job_name : jobName, sentToExec : sentToExec, jobExecIp : jobExecIp, execMessage : execMessage},
cache: false
});
} else { // for the jobs with any return parameter
if (typeof returnVar != 'undefined' ) {
// this parameter is going to be posted to another page
var result = [];
var numOfOutputVar = <?php echo $jobsArray[4]; ?>;
if (Object.prototype.toString.call(returnVar) === '[object Array]') {
var countIndex = 0;
var countValue = 0;
var allValuesNoArray = false;
// check if all the returnVar values are not [object Array]
$.each(returnVar, function(index, value) {
console.log(Object.prototype.toString.call(value));
countIndex = countIndex + 1;
// check if value is not an [object Array] not an '[object String]'
if (Object.prototype.toString.call(value) !== '[object Array]' && Object.prototype.toString.call(value) !== '[object String]'){
countValue = countValue + 1;
}
});
// if all returnVar values are not [object Array] then true
if (countIndex === countValue) {
allValuesNoArray = true;
}
// if at least one returnVar value is an [object Array] then do
if (allValuesNoArray === false ) {
// if the job has more than one return variable
if (numOfOutputVar > 1) {
$.each(returnVar, function(index, value) {
result.push(JSON.stringify(value));
})
} else { // if the job has only one return variable
var allRetVarToOne = [];
$.each(returnVar, function(index, value) {
allRetVarToOne.push(value);
})
result.push(JSON.stringify(allRetVarToOne));
}
} else { // if all returnVar values are not [object Array] then do
console.log(numOfOutputVar);
// if the job has more than one return variable
if (numOfOutputVar > 1) {
$.each(returnVar, function(index, value) {
result.push(JSON.stringify(value));
})
} else { // if the job has only one return variable
result.push(JSON.stringify(returnVar));
}
}
} else {
result.push(JSON.stringify(returnVar));
}
// executes the POST if everything is ok
$.ajax({
url: 'executedJobs.php',
type: 'POST',
data: {results : result, job_batch_id : jobBatchID, job_id : jobID, job_name : jobName, sentToExec : sentToExec, jobExecIp : jobExecIp, execMessage : execMessage},
cache: false
});
} else { // executes this POST if the job execution was not successful, with no reason
var execMessage = "An unknown falure has accourd while executing, will be executed once more"
$.ajax({
type: 'POST',
data: {results : result, job_batch_id : jobBatchID, job_id : jobID, job_name : jobName, sentToExec : sentToExec, jobExecIp : jobExecIp, execMessage : execMessage},
cache: false,
url: 'executedJobs.php'
});
}
}
}).fail(function(jqxhr, settings, exception) { // executes if the getScript(scriptPath, function(data, textStatus, jqxhr) {}) faild
var execMessage = exception.message;
var result = undefined;
var jobBatchID = "<?php echo $jobsArray[0];?>";
var jobID = "<?php echo $jobsArray[1];?>";
var jobName = "<?php echo $jobsArray[2];?>";
var sentToExec = "<?php echo $sentToExececution;?>";
$.ajax({
type: 'POST',
data: {results : result, job_batch_id : jobBatchID, job_id : jobID, job_name : jobName, sentToExec: sentToExec, jobExecIp : jobExecIp, execMessage : execMessage},
cache: false,
url: 'executedJobs.php'
});
});
}
});
</script>
The problem is that my post under the comment “executes the POST if everything is ok” sends empty parameters if the function that I’m executing using var returnVar = <?php echo $newJobName; ?> or var returnVar = <?php echo $jobsArray[2]; ?>.apply(this, vars); has var maxNum = 500000; and var arrayMaxSize = 500000;. When I look in the console under the parameter window of the POST to executedJobs.php, I the right results there just not on the view window of the and of course not on the executedJobs.php page itself.
And this is the function that is being called by the var returnVar
function job1() {
var notSortNumArray = [];
var notSorted1 = [];
var notSorted2 = [];
var maxNum = 500000;
var arrayMaxSize = 500000;
var minNum = 1;
// create an array with arrayMaxSize random nmber between minNum and maxNum
for (var x = 0; x < arrayMaxSize; x++) {
notSortNumArray.push(Math.floor(Math.random() * (maxNum - minNum)) + minNum);
}
// The notSorted1 is from possition 0 untill random between 0 and arrayMaxSize
notSorted1 = notSortNumArray.slice(0, Math.floor(Math.random() * notSortNumArray.length));
// The notSorted2 is from where the notSorted1 ends untill the last number form the notSortNumArray
notSorted2 = notSortNumArray.slice(notSorted1.length, notSortNumArray.length);
// job dependencies
var nextJob = "job2, job3";
var prevJob = "null";
// results
return [ notSortNumArray, arrayMaxSize, notSorted1, notSorted2 ];
}
Funny thing is that for var maxNum = 250000; and var arrayMaxSize = 250000 everything works perfect and all the results are being sent to the executedJobs.php page for further.
Again I hope someone can help me solve this since I don’t have a clue why it’s not working for higher numbers of the var maxNum and the var arrayMaxSize parameters, the results are there they and something is being sent to the executedJobs.php page but nothing comes over.
I know this is a lot of code, but I hope someone can help me solve this since I don’t have a clue why it’s not working.

No semicolon at lines :
var scriptPath = "<?php echo $jobJSPath[0]; ?>"
var execMessage = "An unknown falure has accourd while executing, will be executed once more"
in line :
var hasOutput = <?php echo json_encode($allOutputVarName);?>;
you should change it to :
var hasOutput = JSON.parse("<?php echo json_encode($allOutputVarName);?>");

Related

CodeIgniter ajax reloading page issue

I have a page with ajax pagination on it, I am currently able to check if the session exists and process accordingly. However, I cannot seem to remove the menu or reload the page properly if the session has expired. Only the menu remains and the login page shows in the small area where the table was.
Controller code
public function index()
{
$conditions = array();
$data = array();
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search(array('limit'=>$this->get_per_page()));
$data['user'] = $this->AccountModel->get_person($this->get_person_id());
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('layout/admins/common/header');
$this->load->view('layout/admins/common/navigation');
$this->load->view('layout/admins/common/title');
$this->load->view('layout/admins/common/errors');
$this->load->view('layout/admins/common/search');
$this->load->view('admins/documents/index',$data);
$this->load->view('layout/admins/common/footer');
}
public function search(){
if($this->input->is_ajax_request()){
if(!$this->logged_in()){
$this->index();
}else{
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$this->load->view('admins/documents/ajax_pagination', $data, false);
}
}
}
My JS Code that is placed in the view
<script>
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (html) {
$('#list').html(html);
$('.loading').fadeOut("slow");
}
});
}
function changeStatus(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/ChangeStatus/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
console.log(result);
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
function deleteDocument(input){
var id = input;
$.ajax({
type:'POST',
url:'url/AdminDocuments/Delete/',
data:'id='+id,
beforeSend: function () {
$('.loading').show();
},
success:function(result){
searchFilter(0);
$('.loading').fadeOut("slow");
}
});
}
</script>
i am assuming $('#list').html(html); code loads the html in the dom. instead of directly sending the html from php you can send a json containing the html as well the login status. like this.
$data = [
'login_status' => 1 // or 0,
'html' => $html // full html your are sending now
];
echo json_encode($data);
then in ajax success.
function searchFilter(page_num) {
page_num = page_num?page_num:0;
var keywords = $('#search').val();
$.ajax({
type: 'POST',
url: 'url/AdminDocuments/Search/'+page_num,
data:'page='+page_num+'&keywords='+keywords,
beforeSend: function () {
$('.loading').show();
},
success: function (response) {
var data = $.parseJSON(response);
if(data.login_status == 0)
{
window.location.href = 'redirect to login page';
}
if(data.login_status == 1)
{
$('#list').html(data.html);
}
$('.loading').fadeOut("slow");
}
});
}
controller method :
public function search(){
if($this->input->is_ajax_request()){
$conditions = array();
$page = $this->input->post('page');
if(!$page){
$offset = 0;
}else{
$offset = $page;
}
$keywords = $this->input->post('keywords');
if(!empty($keywords)){
$conditions['search']['keywords'] = $keywords;
}
$totalRec = count($this->DocumentModel->admin_get_and_search($conditions));
$config['target'] = '#list';
$config['base_url'] = site_url('/AdminDocuments/Search');
$config['total_rows'] = $totalRec;
$config['per_page'] = $this->get_per_page();
$this->ajax_pagination->initialize($config);
$conditions['start'] = $offset;
$conditions['limit'] = $this->get_per_page();
$data['links'] = $this->ajax_pagination->create_links();
$data['datatable'] = $this->DocumentModel->admin_get_and_search($conditions);
$data['current_page'] = $this->ajax_pagination->getCurrPage();
$html = $this->load->view('admins/documents/ajax_pagination', $data, true);
$res['html'] = $html;
$res['login_status'] = ($this->logged_in()) ? '1' : '0';
echo json_encode($res);
}

javascript data wont show in php codeigniter

I'm trying to get ajax data from my controller to view. but the javascript code seems doesnt execute well. here's my script
<script type="text/javascript">
function view_data(act){
var w = $('#origin').val();
var x = $('#destination').val();
var y = $('#weight').val();
var z = $('#courier').val();
if(w == "" && x == "" && y == "" && z == "" ){
alert("I am an alert box!");
}else{
$.ajax({
url: "<?php echo base_url()?>Cart/getCost",
type: "GET",
data : {origin: w, destination: x, berat: y, courier: z},
success: function (ajaxData){
$("#result").html(ajaxData);
}
});
}
};
</script>
for orgin and destination is came from option select
and for weight and courier from input text.
here's my controller
function getCost()
{
$origin = $this->input->get('origin');
$destination = $this->input->get('destination');
$weight = $this->input->get('weight');
$courier = $this->input->get('courier');
$data = array('origin' => $origin,
'destination' => $destination,
'weight' => $weight,
'courier' => $courier
);
$this->load->view('rajaongkir/getCost', $data);
}}
the problem is , data wontt show up in #result on view.
change your url to this :
url: "<?php echo base_url();?>Cart/getCost",
in ajax you have to give full url address .
please replace load view , to var_dump , and in your ajax success part, console.log(result) to show what we have in controller .
Second one:
another way is to set your view to a variable ( i name it , $Datares) , and add this code after it
$this->set_output($Datares);
This will helps you
<script type="text/javascript">
function view_data(act){
var w = $('#origin').val();
var x = $('#destination').val();
var y = $('#weight').val();
var z = $('#courier').val();
if(w == "" && x == "" && y == "" && z == "" ){
alert("I am an alert box!");
}else{
$.ajax({
url: "Cart/getCost",
type: "GET",
data : {origin: w, destination: x, berat: y, courier: z},
success: function (ajaxData){
$("#result").html(ajaxData);
}
});
}
};
</script>
function getCost()
{
$origin = $this->input->get('origin');
$destination = $this->input->get('destination');
$weight = $this->input->get('weight');
$courier = $this->input->get('courier');
$data = array('origin' => $origin,
'destination' => $destination,
'weight' => $weight,
'courier' => $courier
);
echo $data;
exit;
}

How to show the errors through ajax and Jquery in codeigniter

This is my ajax call
function exportCSV(){
var sampleid = $("#sampleid").val();
var scheme = $("#scheme").val();
var v = $("#v").val();
var date = $("#date").val();
var assignedvalue = $("#assignedvalue").val();
var units = $("#units").val();
var assayvalue = $("#assayvalue").val();
var analyte = $("#analyte").val();
var filename=$("#filename").val();
var sample_error=$("#sample_error").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "import/validate_file",
dataType: 'json',
data: {
sampleid: sampleid,
scheme: scheme,
v: v,
date: date,
assignedvalue: assignedvalue,
units: units,
assayvalue: assayvalue,
analyte: analyte,
filename:filename,
sample_error: sample_error
},
success: function (data) {
console.log(data); //as a debugging message.
}
});
}
and this is my controller
<?php
if (!empty($unit_check) and !empty($analyt) and !empty($sch) and count($sample_id) == count(array_unique($sample_id)) and $assigned_check == '1' and $assay_check == '1') {
for ($row = 2; $row <= $lastRow; $row++) {
$data['sample_id'] = $worksheet->getCell($sampleid . $row)->getValue();
$data['scheme'] = $worksheet->getCell($scheme . $row)->getValue();
$data['v'] = $worksheet->getCell($v . $row)->getValue();
$data['units'] = $worksheet->getCell($unit . $row)->getValue();
$data['date'] = $worksheet->getCell($date . $row)->getFormattedValue();
$data['assay_value'] = $worksheet->getCell($assayvalue . $row)->getValue();
$data['assigned_value'] = $worksheet->getCell($assignedvalue . $row)->getValue();
$data['analyte'] = $worksheet->getCell($analyte . $row)->getValue();
$data['trace_id'] = $insert_id;
$this->import_model->insert_data($data);
$response['success'] = true;
}
} else {
$data['sample_id'] = '';
$data['analyte'] = '';
$data['unit_check'] = '';
$data['sch'] = '';
$data['assigned_value'] = '';
$data['assay_value'] = '';
if (count($sample_id) != count(array_unique($sample_id))) {
$data['sample_id'] = '1';
}
if (empty($analyt)) {
$data['analyte'] = '1';
}
if (empty($unit_check)) {
$data['unit_check'] = '1';
}
if (empty($sch)) {
$data['sch'] = '1';
}
if ($assigned_check == '') {
$data['assigned_value'] = '1';
}
if ($assay_check == '') {
$data['assay_value'] = '1';
}
$data['file_name'] = '';
}
?>
I have to show the errors and success message on ajax call.
Right now I'm succeeded in valuating the data and putting it in the database.
But I want to show the success message at the end of the page by clicking the submit button.
And if there is validations error it must shows the errors in that fields at the end of the page
Any help would be appreciated.
Here inside your success method of ajax
success: function (data) {
$("#resultDiv").html(data)
}
Return some real data from your controller in both case success and failed. and based on your data inside success method show your message.
Like:
success: function (data) {
$("#resultDiv").html(data.success) //this requires string to convert your result in string if neccessary
//But you should return a JSON data as msg from your controller
}
You should put a result HTML element for example:
<div id='resultDiv'></div> <!-- to match with #resultDiv -->
Put response data in both condition if success=true and else success=false
In your controller
if(.....){
//what ever check you wanna do
..........
..........
$response['msg']='success';
header('Content-Type', 'application/json');
echo json_encode($response);
}
else{
$response['msg']='failed';
header('Content-Type', 'application/json');
echo json_encode($response);
}
In your ajax
success: function (data) {
$("#resultDiv").html(data.msg)
}
Try something like:
$response = array(
'errCode' = 0,
'errMsg' = 'msg'
);
return this kind of array by json_encode() from php to ajax() call and use it in ajax() success like:
var data = JSON.parse(response);
alert(data.errMsg);
You can also put a check on errCode like:
if(errCode == 0) { something }
if(errCode == 1) { something }

jQuery.ParseJson didn't return a value from mysql database

I have a div that will store a value from DB that parse from JSON
<div id='nsnt' class="huge"> </div>
I have a getdata.php to getdata from mysqldb
getdata.php
<?php
$objConnect = mysql_connect("localhost","xxxxxx","xxxxx") or die(mysql_error());
$objDB = mysql_select_db("musicstore");
$strSQL = "SELECT count(song_id) as cnt FROM song ";
$objQuery = mysql_query($strSQL) or die (mysql_error());
$intNumField = mysql_num_fields($objQuery);
$resultArray = array();
while($obResult = mysql_fetch_array($objQuery))
{
$arrCol = array();
for($i=0;$i<$intNumField;$i++)
{
$arrCol[mysql_field_name($objQuery,$i)] = $obResult[$i];
}
array_push($resultArray,$arrCol);
}
mysql_close($objConnect);
echo json_encode($resultArray);
?>
I use var_dump on $resultArray it's return a data perfectly
On my index.php I have a jQuery function to return data from getdata.php and display on <div id='nsnt' class="huge"> </div> like this
<script>
function getDataFromDb()
{
$.ajax({
url: "~/getdata.php" ,
type: "POST",
data: ''
})
.success(function(result) {
var obj = jQuery.parseJSON(result);
if(obj != '')
{
//$("#myTable tbody tr:not(:first-child)").remove();
$("#nsnt").empty();
$.each(obj, function(key, val) {
var m = val["cnt"];
$('#nsnt').append( m );
});
}
}
setInterval(getDataFromDb, 1000); // 1000 = 1 second
</script>
It's doesn't return anything
I think Success should be one of ajax properties, otherwise use .done(), try this :
$.ajax({
url: "~/getdata.php" ,
type: "POST",
data: '',
success : function(result) {
var obj = jQuery.parseJSON(result);
if(obj != '')
{
//$("#myTable tbody tr:not(:first-child)").remove();
$("#nsnt").empty();
$.each(obj, function(key, val) {
var m = val["cnt"];
$('#nsnt').append( m );
});
}
}
});
or
$.ajax({
url: "~/getdata.php" ,
type: "POST",
data: ''
}).done(function(result) {
var obj = jQuery.parseJSON(result);
if(obj != '')
{
//$("#myTable tbody tr:not(:first-child)").remove();
$("#nsnt").empty();
$.each(obj, function(key, val) {
var m = val["cnt"];
$('#nsnt').append( m );
});
};
});

Issue on Quering Database Using jQuery Ajax and PHP

Can you please take a look at This Demo and let me know why I am getting empty array?
I have a jquery ajac request as:
$( "#appinfo" ).on( "submit", function( e ) {
var eTraget = $(".opacity").html().replace(/\D/g,'');
var senario = current;
if(qtype =="econo"){
var col = senario +"_"+eTraget;
var data='column='+col;
$.ajax({
type:"POST",
url:"assets/econo.php",
data:data,
dataType : 'json',
success:function(html) {
coords = html;
console.log(data);
st = map.set();
for (var i = 0; i < coords.length; i++) {
var circle = map.circle(coords[i][0], coords[i][1], 6);
st.push(circle);
}
e.preventDefault();
});
and econo.php as:
<?PHP
include 'conconfig.php';
$con = new mysqli(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$collm = $_POST['column'];
$query = "SELECT x, y FROM econo WHERE".$collm."=1";
$results = $con->query($query);
$return = array();
if($results) {
while($row = $results->fetch_assoc()) {
$return[] = array((float)$row['x'],(float)$row['y']);
}
}
$con->close();
echo json_encode($return);
?>
As you can see I console.log(data); and the console display the result like column=ce_3000 but the $collm = $_POST['column']; is empty because whrn tried to dump it I just got an empty []. Can you please let me know why this is happening?

Categories