javascript data wont show in php codeigniter - javascript

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;
}

Related

How to fix 'ERR_ACCESS_DENIED' when uploading multiple files

I am trying to upload multiple files to a server. It works fine when there is one file, but as soon as there are multiple, I get "ERR_ACCESS_DENIED". Not sure if this has something to do with my permissions or just my naive code. Thanks in advance!
PHP:
session_start();
function outputJSON($msg, $code = 0, $status = 'error'){
header('Content-Type: application/json');
if ($code == 200 || $code == 201){
echo $code;
exit();
}
echo $msg . "||" . $code . "||" . $status;
die();
}
//ERROR CODES:
//200 - Upload and Processing successful;
//201 - Upload and Processing successful; - Rename made
//400 - Upload Failed
//511 - Not Authorized
//520 - Unknown
$tempDir = guidv4();
mkdir("disk/processing/" . $tempDir);
$putdir = 'disk/processing/' . $tempDir . '/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
outputJSON($_FILES["files"]["error"], 520, 'error');
} else {
if (file_exists($putdir . $_FILES["files"]["name"][$i])) {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], $putdir . $_FILES["files"]["name"][$i] . ' (1)');
outputJSON($tempDir, 200, 'done');
} else {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], $putdir . $_FILES["files"]["name"][$i]);
outputJSON($tempDir, 201, 'done');
}
}
}
} else {
outputJSON('Empty Upload.', 400, 'error');
}
JS/JQ
$('#information').show();
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploadbackend.php', // point to server-side PHP script
dataType: 'application/json', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
xhr: function() {
var started_at = new Date();
xhr.upload.addEventListener( 'progress', function( e )
{
if( e.lengthComputable )
{
// Append progress percentage.
var loaded = e.loaded;
var total = e.total;
var progressValue = Math.round( ( loaded / total ) * 100 );
// Bytes received.
jQuery( '.recievedValue' ).html( '' );
jQuery( '.recievedValue' ).append( humanFileSize( loaded ) + ' / ' );
// Total bytes.
jQuery( '.totalValue' ).html( '' );
jQuery( '.totalValue' ).append( humanFileSize( total ) );
// Time Remaining
var seconds_elapsed = ( new Date().getTime() - started_at.getTime() )/1000;
var bytes_per_second = seconds_elapsed ? loaded / seconds_elapsed : 0 ;
var Kbytes_per_second = bytes_per_second / 1000 ;
var remaining_bytes = total - loaded;
var seconds_remaining = seconds_elapsed ? remaining_bytes / bytes_per_second : 'calculating' ;
jQuery( '.timeRemaining' ).html( '' );
jQuery( '.timeRemaining' ).append( seconds_remaining );
// Percentage.
$('#_explorer_progress').css("width", "" + progressValue + "%")
if (progressValue >= 100){
$('#information').html('Processing...')
}
}
}, false );
return xhr;
},
success: function (response) {
$('#information').html('Done.');
$('#upload').html('Uploaded! <i class="fa fa-check ml-5"></i>');
$('#upload').removeClass('btn-primary');
$('#upload').removeClass('btn-danger');
$('#upload').addClass('btn-info');
document.getElementById("upload").disabled = true;
$('#msg').html(response); // display success response from the PHP script
setTimeout(function () {
$('#upload').html('Start Upload <i class="fa fa-upload ml-5"></i>');
document.getElementById("upload").disabled = false;
$('#upload').addClass('btn-primary');
$('#upload').removeClass('btn-danger');
$('#upload').removeClass('btn-info');
$("#multifiles").val('');
}, 3000)
},
error: function (response) {
$('#information').html('There was a problem.');
console.log(response);
}
});
HTML:
<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
There is no response from the server except an "ERR_ACCESS_DENIED" error from the POST request.
When there is one file, it functions as expected.

handle more than one ajax response

First I want to describe what I want to do.
I've a table and one column has buttons. Each button represents an ID. When the button is clicked, I store the ID into a variable in javascript. I want to use this ID in a MySQL-Statement to get some informations, which are in more than one row and creare a PDF file with these data.
I want to use ajax to handle the recived data, but I don't know exactly how to.
Until now, this is what I got:
<script>
$("#grid-table").bootgrid({
formatters: {
"buttonID": function(column, row){
return "<button type=\"button\" id=\"edit\" class=\"btn btn-xs btn-default print-pdf\" + data-row-id1=\"" + row.ID + "\" ><span class=\"fa fa-file-pdf-o\"></span></button> ";
}
}).on("click", function(e){
var id = $(this).data("row-id1"); // id is a string
var recv_data1[];
var recv_data2[];
var recv_data3[];
var recv_data4[];
var i = 0;
if(id != ""){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
// how to get all datas and store them here?
// and get the count of $i
var doc = new jsPDF(); // pdf object
mainPage(doc); // my function to create a pdf background
var xPos = 25;
var yPos = 60;
while(i){
doc.setFontSize(12);
doc.setFontType('normal');
doc.text(70, 55, recv_data1[i]); // here I want to use some of the data
doc.setFontSize(11);
doc.setFontType('bold');
doc.text(xPos+10, yPos+10, recv_data2[i]); // some more data I got from the mysql-statement
doc.text(xPos+55, yPos+10, recv_data3[i]);
doc.text(xPos+80, yPos+10, recv_data4[i]);
i--;
}
doc.save(recv_data1 + '.pdf'); // save pdf file
}
};
xmlhttp.open("GET","get_data.php?id="+ id, true);
xmlhttp.send();
}
});
</script>
PHP-Part from get_data.php:
<?php
include "dbconnect.php";
$revc_id = htmlspecialchars_decode($_GET['id']);
$result = mysqli_query($db, "SELECT *
FROM table
WHERE table.id = 'revc_id';");
$i = 1;
while($row = mysqli_fetch_array($result)) {
// how to handle the fetched array and alle the data to
// more than one variable for the js like
// echo $row['name'] for recv_data1[]
// echo $row['city'] for recv_data2[]
// echo $row['street'] for recv_data3[]
// echo $row['country'] for recv_data4[]
// echo $i to know how many datas are in there
$i++;
}
mysqli_close($db);
?>
This is just a general example of what I want to do and not the original code. So what I want is that the respone I got from get_data.php, which is in the most cases more than one row, to be saved into the array.
I hope you know what I mean, if not fell free to ask please.
Tricky to answer when the code shown is not the actual code but in general you could try something like this.
php
---
$data=array();
while( $row = mysqli_fetch_object( $result ) ) {
$data[]=array(
'name' => $row->name,
'city' => $row->city,
'street' => $row->street,
'country' => $row->country
);
}
echo json_encode( $data );
/* javascript */
document.getElementById('BTTN_ID_ETC').onclick = function(e){
e.preventDefault();
var id = $( this ).data("row-id1");
if( id != "" ){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if( this.readyState == 4 && this.status == 200 ) {
var json=JSON.parse( this.response );
var doc = new jsPDF();
mainPage( doc );
var xPos = 25;
var yPos = 60;
for( var n in json ){
try{
var obj=json[ n ];
if( typeof( obj )=='object' ){
var name=obj.hasOwnProperty('name') ? obj.name : false;
var city=obj.hasOwnProperty('city') ? obj.city : false;
var street=obj.hasOwnProperty('street') ? obj.street : false;
var country=obj.hasOwnProperty('country') ? obj.country : false;
if( name && city && street && country ){
doc.setFontSize(12);
doc.setFontType('normal');
doc.text(70, 55, name );
doc.setFontSize(11);
doc.setFontType('bold');
doc.text(xPos+10, yPos+10, city );
doc.text(xPos+55, yPos+10, street );
doc.text(xPos+80, yPos+10, country );
}
}
} catch( err ){
console.log( err );
continue;
}
}
doc.save( json[0].name + '.pdf');
}
};
xmlhttp.open( 'GET', 'get_data.php?id='+ id, true );
xmlhttp.send();
}
};

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

how to retrieve data through ajax?

I want a user to input a country, then it will output its population. My javascript is suppose to look up the country that the user input when the button is clicked, then goes through the PHP file and gets the country's population.
my HTML is:
<label>
Country:
<input name="country" type="text" id="country"></label>
<input type="button" value="Find population" id="findPop">
<p id="output"></p
and javascript:
var countryFound = function(data) {
var theCountry = $("#country").val();
var population = data["country"];
if (data["country"])
{
$("#output").html(theCountry + " population is " + population);
}
else {
$("#output").html(theCountry + " is not found");
}
};
$("#findPop").click(function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.getJSON("countrylookup.php", "country="+theCountry , countryFound);
});
my PHP code is:
if (isset($_GET['country'])) { // get the parameters country
$column = 'country';
$value = $_GET['country'];
else {
print -1; // an error code
return;
}
$data = array( 'country'=>'Peru', 'capital'=>'Lima', 'area'=>'1285220', 'population'=>'29907003', 'continent'=>'South America' ),
array( 'country'=>'Philippines', 'capital'=>'Manila', 'area'=>'300000', 'population'=>'99900177', 'continent'=>'Asia' );
function findData ( $whichColumn, $data, $searchValue)
{
$result = array();
foreach ($data as $row) {
if ($row[$whichColumn] == $searchValue)
$result[] = $row;
}
return $result;
}
print json_encode ( findData($column, $data, $value) );
but for some reason, when I input Peru as the country, it says Peru is not found. Am I not retrieving the correct data from the php or what? I'm pretty sure that my php code is correct.
Here's how I'd do it :
$(function() {
$("#findPop").on('click', function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.getJSON("countrylookup.php", {country: theCountry}, function(data) {
var population = data[0] != "false" ? data.population : false,
msg = population ? (" population is " + population) : " is not found";
$("#output").html(theCountry + msg);
});
});
});
PHP
$value = isset($_GET['country']) ? strtolower(trim($_GET['country'])) : false;
$result = false;
if ($value) {
$data = array(
'peru' => array(
'capital'=>'Lima',
'area'=>'1285220',
'population'=>'29907003',
'continent'=>
'South America'
),
'philippines' => array(
'capital'=>'Manila',
'area'=>'300000',
'population'=>'99900177',
'continent'=>'Asia'
)
);
if (array_key_exists($value, $data)) $result = $data[$value];
}
echo json_encode($result);
For the jQuery side, I recommend using the .get() function.
$("#findPop").click(function(){
var theCountry = $("#country").val();
$("#output").html("Loading...");
$.get("countrylookup.php", function(data) {
if(data) {
// Do whatever you want to do with the data, e.g.:
var population = data.population,
theCountry = $("#country").val();
// Do more magic
$("#output").html(theCountry = " population is " + population)
} else {
// Error handling
}
});
});
There is a } missing before the else in the fourth line of the PHP code.

Categories