Issue on Quering Database Using jQuery Ajax and PHP - javascript

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?

Related

Get Array from JSON encode via AJAX

I'm trying to get 4 JSON arrays that I have in a separate file into my main file using AJAX request. For reason, I can't seem to get the arrays into variables and to display it in console log.
This is the results from the JSON file:
[[5,10,10.99,10.99,13,5,14.31,1,1,5,5,5,1,5,3,3,5,5,1,5,10.32,10.32,5,8,5,10,5,5,19,5,7.36,7.36,5,12.2,12.2,2.2,2.2,23.3,5,10.87,6.87,6.87,5,5,10,10,10,10,5,5,5,5,5,0,5,5],
[8,12.5,12.5,12.53,12.53,8,10.11,1,1,8,8,8,1,8,3,3,8,8,1,8,12.83,32.32,8,8,8,10,8.31,8,10,8,18.2,18.2,8,10.3,10.3,2.29,2.29,12.3,8,8.23,2.23,2.23,8,8,10,10,10,20,5,5,5,5,8,0,8,2],
[6,8.86,8.86,8.87,8.87,6,8.33,1,2,6,2,3,1,6,3,8,6,6,1,6,8.32,7.32,6,8,6,10,3.31,6,12,6,12.3,12.3,6,11.1,11.1,4.09,4.09,33.1,6,5.16,12.16,2.16,6,6,10,20,30,30,30,30,5,0,6,0,6,5],
[19,31.36,32.36,32.4,34.4,19,32.76,3,4,19,15,16,3,19,9,14,19,19,3,19,31.47,49.96,19,24,19,30,16.62,19,41,19,37.86,37.86,19,33.6,33.6,8.6,8.6,68.7,19,24.26,21.26,11.26,19,19,30,40,50,60,40,40,15,10,19,0,19,12]]
This is how I tried to get it into my main page:
function callback(response) {
var array1 = response[0];
var array2 = response[1];
var array3 = response[2];
var array4 = response[3];
console.log(array1);
}
$.ajax({
url: 'loadchart.php',
success: callback
});
The result that I get from trying to get only the all the array1 is only a bracket:
[
Code from loadchart.php:
<?php
session_start();
if(!isset($_SESSION['usersId']))
{
header("Location: ../index.php");
exit();
}
else
{
include_once 'includes/dbh.inc.php';
}
$id = $_SESSION['userId'];
$dBname = "infosensor";
$conn = mysqli_connect($servername, $dBUsername, $dBPassword, $dBname);
$sql = "SELECT sensor1, sensor2, sensor3 FROM `$id`;";
$result = mysqli_query($conn, $sql);
$jsonsensor1 = array();
$jsonsensor2 = array();
$jsonsensor3 = array();
$jsonsensorsum = array();
if (mysqli_num_rows($result) > 0)
{
while ($row = mysqli_fetch_assoc($result))
{
$jsonsensor1[] = intval($row['sensor1'] * ($p = pow(10, 2))) / $p;
$jsonsensor2[] = intval($row['sensor2'] * ($p = pow(10, 2))) / $p;
$jsonsensor3[] = intval($row['sensor3'] * ($p = pow(10, 2))) / $p;
$jsonsensorsum[] = intval(($row['sensor1'] + $row['sensor2'] + $row['sensor3']) * ($p = pow(10, 2))) / $p;
$data = [$jsonsensor1,$jsonsensor2,$jsonsensor3,$jsonsensorsum];
}
}
echo json_encode($data);
Add dataType as json:
$.ajax({
url: 'loadchart.php',
dataType:"json",
success: callback
});
Just do one thing user JSON.parse to parse your json array
like i have done in your function
function callback(response) {
var res= JSON.parse(response);
var array1 = res[0];
var array2 = res[1];
var array3 = res[2];
var array4 = res[3];
console.log(array1);
}

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 }

Ajax POST is sending empty parameters

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);?>");

Passing 2 arrays to a javascript function with ajax

This code submits a form and an ID # to addBand.php. The php inserts the form data into a DB, and then echos an array that houses 2 arrays: 1 is an array of ids, the other is a string to update an HTML select element. I've only included the PHP that generates and echos the arrays.
i keep getting "Uncaught TypeError: Cannot read property 'selectRestults' of undefined" with the following code. what am I doing wrong?
javascript/jquery:
$(function() {
$("#addBandForm").submit(function(event) {
event.preventDefault();
var globalShowID = '&id=' + window.globalShowID;
$.ajax({
url: "womhScripts/addBand.php",
type: "POST",
data: $('#addBandForm').serialize() + globalShowID,
success: function(msg) {
var actArray = msg['actIDArray'];
var bandArray = msg['bandSelectArray'];
var result = bandArray['selectResults'];
window.globalShowID='';
$("#band1").html(result)
},
error:function(errMsg) {
console.log(errMsg);
}
});
});
});
addBand.php
$bandSelectArray = array();
$actIDArray = array();
$bandResults = "";
if (isset($_POST['id']))
{
$ShowID = $_POST['id'];
$actSQL = mysqli_query($link, "SELECT actID FROM Act WHERE showID=".$ShowID."");
while($actRow = mysqli_fetch_array($actSQL))
{
$actIDArray[] = array(
'actID' => $actRow['actID'],
);
}
}
$selectBandSQL = mysqli_query ($link, "SELECT bandID, bandName FROM Band");
while ($row = mysqli_fetch_array($selectBandSQL))
{
$bandID = $row['bandID'];
$bandName2 = $row['bandName'];
$bandResults .= '<option value="'.$bandID.'">'.$bandName2.'</option>';
}
$bandSelectArray['selectResults'] = $bandResults;
$resultArray = array();
$resultArray['actIDArray'] = $actIDArray;
$resultArray['bandSelectArray'] = $bandSelectArray;
echo json_encode($resultArray);

Ajax post is not returning response

Here is my code:
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
<script type="text/javascript">
$(document).ready(function() {
var ColorId = "1";
$( "#targetButton" ).click(function() {
$.ajax({
url: 'checkcolors.php',
type: 'post',
dataType: 'json',
success: function (data) {
var arr = data.msg.split(',');
arr.forEach(function(id){
$('#' + id.trim()).hide();
});
//$('#target').html(data.msg);
},
data: ColorId
});
});
});
</script>
<button type="button" id="targetButton">Send</button>
<div class="BlackAndWhite" id="24604682">24604682</div>
<div class="BlackAndWhite" id="24604682x">24604682x</div>
<div class="BlackAndWhite" id="24604679">24604679</div>
<div class="BlackAndWhite" id="24604621">24604621</div>
Here is how the result looks like from checkcolors.php:
24604603, 24604684, 24604640, 24604609, 24604682, 24604686, 24604681, 24604689, 24604602, 24604679, 24604680, 24604622, 24604685, 24604683, 24604621, 24604677, 24604688,
And here is the code from checkcolors.php:
<?PHP
$url = 'http://www.sportsdirect.com/dunlop-mens-canvas-low-top-trainers-246046?colcode=24604622';
libxml_use_internal_errors(true);
$doc = new DOMDocument();
$doc->loadHTMLFile($url);
$xpath = new DOMXpath($doc);
$DataVariants = $xpath->query('//span[#class="ImgButWrap"]/#data-variants')->item(0)->nodeValue;
$jsonStart = strpos($DataVariants, '[');
$jsonEnd = strrpos($DataVariants, ']');
$collections = json_decode(substr($DataVariants, $jsonStart, $jsonEnd - $jsonStart + 1));
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
$SizeNames = [];
foreach ($item->SizeVariants as $size) {
$SizeNames[] = $size->SizeName;
}
if (in_array("7", $SizeNames)) {
echo "$ColVarId, ";
}
}
?>
When i click the button i am watching the browser console for any warnings or errors but there are none. Somehow it is not working and i do not know why.
It is supposed to hide all div elements with the same ids given from the checkcolors.php response, but it is not working. Why ?
Can you please help me out?
Thanks in advance!
Try to change this line:
var arr = data.msg.split(',');
to this:
var arr = data.split(',');
In your php script "checkcolors.php", you must return a JSON file.
$res = array();
foreach ($collections as $item) {
$ColVarId = $item->ColVarId;
$SizeNames = [];
foreach ($item->SizeVariants as $size) {
$SizeNames[] = $size->SizeName;
}
if (in_array("7", $SizeNames)) {
$res[] = $ColVarId;
}
}
echo json_encode($res);
Then in your javascript, you replace arr by data.
data.forEach(function(id){
$('#' + id.trim()).hide();
});

Categories