how to retrieve data through ajax? - javascript

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.

Related

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

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

how to Check ID verification if already exists in the database using PHP CodeIgniter, JQuery, AJAX

I am trying to check the id's validity using ajax and codeigniter. when The status of the id if it is taken will appear "NPP tidak ada di database".
my contrroler:
public function ajax_add()
{
$this->_validate();
$data = array(
'id' => $this->input->post('id'),
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'level' => $this->input->post('level'),
);
$insert = $this->user_model->save($data);
echo json_encode(array("status" => TRUE));
}
private function _validate()
{
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
$id = $this->input->post('id');
$result = $this->user->checknpp( $id ); #send the post variable to the model
//value got from the get metho
$id= $id;
if( $result == '0' )
{
$data['inputerror'][] = 'id';
$data['error_string'][] = 'NPP tidak ada di database';
$data['status'] = FALSE;
}
if($data['status'] === FALSE)
{
echo json_encode($data);
exit();
}
}
My modal:
public function checknpp($id)
{
$this->db->select('id');
$this->db->where('id', $id);
$this->db->from('id', 1);
$query = $this->db->get();
if( $query->num_rows() > 0 ){ return 0; }
else{ return 1; }
}
My js:
function save()
{
$('#btnSave').text('saving...'); //change button text
$('#btnSave').attr('disabled',true); //set button disable
var url;
if(save_method == 'add') {
url = "<?php echo site_url('user/ajax_add')?>";
} else {
url = "<?php echo site_url('user/ajax_update')?>";
}
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
if(data.status) //if success close modal and reload ajax table
{
$('#modal_form').modal('hide');
reload_table();
}
else
{
for (var i = 0; i < data.inputerror.length; i++)
{
$('[name="'+data.inputerror[i]+'"]').parent().parent().addClass('has-error'); //select parent twice to select div form-group class and add has-error class
$('[name="'+data.inputerror[i]+'"]').next().text(data.error_string[i]); //select span help-block class set text error string
}
}
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
$('#btnSave').text('save'); //change button text
$('#btnSave').attr('disabled',false); //set button enable
}
});
}
my view:
<input name="id" id="masukpun" placeholder="NPP" class="form-control" type="text" />
However, when I run it, it always says that error updating/adding data.
Just try this,
public function ajax_add() {
$data = array();
$data['error_string'] = array();
$data['inputerror'] = array();
$data['status'] = TRUE;
$id = $this->input->post('id');
$result = $this->user->checknpp($id); #send the post variable to the model
//value got from the get metho
$id = $id;
if ($result == '0') {
$data['inputerror'][] = 'id';
$data['error_string'][] = 'NPP tidak ada di database';
$data['status'] = FALSE;
} else {
$data = array(
'id' => $this->input->post('id'),
'username' => $this->input->post('username'),
'password' => $this->input->post('password'),
'level' => $this->input->post('level'),
);
$insert = $this->user_model->save($data);
$data = array("status" => TRUE);
}
echo json_encode($data);
}

Why is my code not passing to my div?

I'm trying to create a gameserver query for my website, and I want it to load the content, save it, and echo it later. However, it doesn't seem to be echoing. It selects the element by ID and is supposed to echo the content of the VAR.
Here's my HTML code:
<center><div id="cstrike-map"><i class="fa fa-refresh fa-spin"></i> <b>Please wait ...</b><br /></div>
JavaScript:
<script type="text/javascript">
var map = "";
var hostname = "";
var game = "";
var players = "";
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
map = ( data.map );
hostname = ( data.hostname );
game = ( data.game );
players = ( data.players );
}, "json");
function echoMap(){
document.getElementByID("cstrike-map");
document.write("<h5>Map: " + map + "</h5>");
}
</script>
PHP files:
query.php
/* SOURCE ENGINE QUERY FUNCTION, requires the server ip:port */
function source_query($ip)
{
$cut = explode(":", $ip);
$HL2_address = $cut[0];
$HL2_port = $cut[1];
$HL2_command = "\377\377\377\377TSource Engine Query\0";
$HL2_socket = fsockopen("udp://".$HL2_address, $HL2_port, $errno, $errstr,3);
fwrite($HL2_socket, $HL2_command); $JunkHead = fread($HL2_socket,4);
$CheckStatus = socket_get_status($HL2_socket);
if($CheckStatus["unread_bytes"] == 0)
{
return 0;
}
$do = 1;
while($do)
{
$str = fread($HL2_socket,1);
$HL2_stats.= $str;
$status = socket_get_status($HL2_socket);
if($status["unread_bytes"] == 0)
{
$do = 0;
}
}
fclose($HL2_socket);
$x = 0;
while ($x <= strlen($HL2_stats))
{
$x++;
$result.= substr($HL2_stats, $x, 1);
}
$result = urlencode($result); // the output
return $result;
}
/* FORMAT SOURCE ENGINE QUERY (assumes the query's results were urlencode()'ed!) */
function format_source_query($string)
{
$string = str_replace('%07','',$string);
$string = str_replace("%00","|||",$string);
$sinfo = urldecode($string);
$sinfo = explode('|||',$sinfo);
$info['hostname'] = $sinfo[0];
$info['map'] = $sinfo[1];
$info['game'] = $sinfo[2];
if ($info['game'] == 'garrysmod') { $info['game'] = "Garry's Mod"; }
elseif ($info['game'] == 'cstrike') { $info['game'] = "Counter-Strike: Source"; }
elseif ($info['game'] == 'dod') { $info['game'] = "Day of Defeat: Source"; }
elseif ($info['game'] == 'tf') { $info['game'] = "Team Fortress 2"; }
$info['gamemode'] = $sinfo[3];
return $info;
}
cstrike.php
include('query.php');
$ip = 'play1.darkvoidsclan.com:27015';
$query = source_query($ip); // $ip MUST contain IP:PORT
$q = format_source_query($query);
$host = "<h5>Hostname: ".$q['hostname']."</h5>";
$map = "<h5>Map: ".$q['map']."</h5>";
$game = "<h5>Game: ".$q['game']."</h5>";
$players = "Unknown";
$stats = json_encode(array(
"map" => $map,
"game" => $game,
"hostname" => $host,
"players" => $players
));
You need to display the response in the $.post callback:
$.post( "serverstats-cstrike/cstrike.php", { func: "getStats" }, function( data ) {
$("#map").html(data.map);
$("#hostname").html(data.hostname);
$("#game").html(data.game);
$("#players").html(data.players);
}, "json");
You haven't shown your HTML, so I'm just making up IDs for the places where you want each of these things to show.
There are some things that I can't understand from your code, and echoMap() is a bit messed up... but assuming that your php is ok it seems you are not calling the echomap function when the post request is completed.
Add echoMap() right after players = ( data.players );
If the div id you want to modify is 'cstrike-map' you could use jQuery:
Change the JS echoMap to this
function echoMap(){
$("#cstrike-map").html("<h5>Map: " + map + "</h5>");
}
So what I did was I had to echo the content that I needed into the PHP file, then grab the HTML content and use it.
That seemed to be the most powerful and easiest way to do what I wanted to do in the OP.
<script type="text/javascript">
$(document).ready(function(){
$.post("stats/query.cstrike.php", {},
function (data) {
$('#serverstats-wrapper-cstrike').html (data);
$('#serverstats-loading-cstrike').hide();
$('#serverstats-wrapper-cstrike').show ("slow");
});
});
</script>
PHP
<?php
include 'query.php';
$query = new query;
$address = "play1.darkvoidsclan.com";
$port = 27015;
if(fsockopen($address, $port, $num, $error, 5)) {
$server = $query->query_source($address . ":" . $port);
echo '<strong><h4 style="color:green">Server is online.</h4></strong>';
if ($server['vac'] = 1){
$server['vac'] = '<img src="../../images/famfamfam/icons/tick.png">';
} else {
$server['vac'] = '<img src="../../images/famfamfam/icons/cross.png">';
}
echo '<b>Map: </b>'.$server['map'].'<br />';
echo '<b>Players: </b>'.$server['players'].'/'.$server['playersmax'].' with '.$server['bots'].' bot(s)<br />';
echo '<b>VAC Secure: </b> '.$server['vac'].'<br />';
echo '<br />';
} else {
echo '<strong><h4 style="color:red">Server is offline.</h4></strong>';
die();
}
?>

Save popup window's data into database

I m trying to save popup windows data in to database.but its throw error when i m trying pass data in queryString.Its just write "error".I dont know why its not call the update_clientstatus.php
Javscript :
function SaveNotes()
{
var notecontent = $("#txtPopNotes").val();
lookup(notecontent, globalNoteId);
overlay.appendTo(document.body).remove();
return false;
}
function lookup(inputstr, eleid) {
var inputString = inputstr;
// var row = parseFloat(eleId.substring(eleId.indexOf('_') + 1))+1;
var noteId = '#noteContent_' + eleid;
var editLinkId = '#editlink_' + eleid;
var saveLinkId = '#savelink_' + eleid;
var cancelLinkId = '#cancellink_' + eleid;
var txtBoxId = '#txt_' + eleid;
// var eleId = ele.id;
$.post("update_clientstatus.php", {queryString: ""+inputString+"", id: ""+eleid+"" }, function(data){
if(data=="success") {
alert("Status updated successfully");
$('.popup').hide();
var noteId = '#noteContent_' + globalNoteId;
$(noteId).html(inputstr);
$('.message').html('Status Updated successfully');
}
else
{
**document.write('error');**
}
});
} // lookup
PHP code(update_clientstatus.php)
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
}
try this
if(isset($_POST['queryString'])) {
$queryString = $db->real_escape_string($_POST['queryString']);
$eleid = $_POST['id'];
$query = mysqli_query($db,"UPDATE tblclientmaster SET status = '$queryString' WHERE id= '$eleid'");
if ($query ) {
echo "success";
} else {
echo "error";
}
} else {
echo "error";
}

Categories