I am developing a small applicatopn using php with ajax to get place when user enter a pincode. Now I'm shore to my aim, but now I am getting some unwanted results but incluing the actual result.
This is my code...my html code is given below
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" /><div id="section1"></div>
and my javascript code is
<script>
$(document).ready(function() {
$('#pincode').keyup(function() {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { <!--console.log(data.success);-->
if(data.success){
$.each(data.results[0].address_components, function(index, val){
console.log(index+"::"+val.long_name);
/*alert(index+"::"+val.long_name); */
$('#section1').append( val.long_name);
});
}
},
});
});
});
</script>
in pincode_check.php
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->results[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
When i enter a pincode , for eg: 690561
The output is
Les JumeauxCourzieuRhĂ´neRhone-AlpesFrance6967015Heilige HuisjesZevenaarZevenaarGelderlandThe Netherlands6905 AAAnayadi Edakkad RdThottuvaPallickalKollamKeralaIndia690561Yitzhak Rabin HighwayIsraelYitzhak Rabin HighwayIsrael328BoulevardAndersonAnderson CountySouth CarolinaUnited States29621164Lenina avenueOrdzhonikidzevs'kyi districtZaporizhiaZaporiz'ka city councilZaporiz'ka oblastUkraine
But I need only AAAnayadi Edakkad . Please help me to filter out this output.
Kindly check this your pin code and press enter key
<script>
$(document).ready(function() {
$('#pincode').keyup(function (e) {
if (e.keyCode == 13) {
//ajax request
$.ajax({
url: "pin_request.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { <!--console.log(data.success);-->
if(data.success){
//console.log(data.results[0].formatted_address.split(','))
var long_address=data.results[0].formatted_address.split(',');
console.log(long_address[0]);
$('#section1').append(long_address[0]);
}
}
});
}
});
});
</script>
Related
I am getting error in Ajax by using the method post and getting the total attendance between two dates of the selected person.
<script type="text/javascript">
$(document).ready(function(){
$("#submit").click(function(event){
event.preventDefault();
var fromdate = $("#fromDate").val();
var todate = $("#toDate").val();
var dep = $("#dep").val();
$.ajax(
{
type: "POST",
url: "<?php echo base_url(); ?>" +"index.php/Ajaxcontroller/getAttendence",
dataType: 'json',
data: {from: fromdate, to: todate,dep:dep},
cache:false,
success: function(result) {
$("#row2").html(result);
},
error: function() {
alert("error");
}
});
});
});
</script>
Please help me to resolve this error.
**this is my controller..**
public function getAttendence()
{
if($this->input->post() && $this->input->is_ajax_request()){
$credentials=array(
'from' => $this->input->post('from'),
'to' = $this->input->post('to'),
'dep' => $this->input->post('dep')
);
$this->load->model('Ajaxmodel');
if($this->Ajaxmodel->selectAttendence($credentials)){
$data['result']=$this->Ajaxmodel->selectAttendence($credentials);
echo json_encode($data);
}
}
else{
$this->load->view('Salarycontrol');
}
}
Edit your code as
data: {'from': fromdate, 'to': todate, 'dep':dep}
If still getting error please elaborate the error exactly you are getting
I have created an associative array like this
HeaderArray["BillNo"] = ["BillNo", BillNo];
HeaderArray["CustomerId"] = ["CustomerId", CusId];
HeaderArray["Date"] = ["CustomerId", "03/11/1995"];
Now I am trying to pass this array to a PHP file.
$.ajax({
type: 'POST',
url: 'Resource/Start.php',
data: { HeaderDetails: HeaderArray },
success: function (Data) {
console.log(Data);
},
});
php file
if (!isset($_POST['HeaderDetails'])) {
echo 'HeaderDetails is not set';
} else {
echo 'HeaderDetails Set';
}
In the console I always get the output as HeaderDetails not set.
Try with
$.post({
url:'Resource/Start.php',
data:{HeaderDetails:JSON.stringify(dataStringHeaderArray)
}.done(function (Data){
console.log(Data);
});
});
the thing you're missing is the ajax dataType(text,json,xml) in our case we use text as print_r($_POST) will return an array which is not json formated.
And secondly no declaration for HeaderArray which will be in this case of type object. so,
Try with:
<form method="POST">
<input type="submit" value="Send">
</form>
<script>
$(function(){
$("form").submit(function(event){
event.preventDefault();
var HeaderArray = {};
HeaderArray["BillNo"] = ["BillNo", "12"];
HeaderArray["CustomerId"] = ["CustomerId", "12"];
HeaderArray["Date"] = ["CustomerId", "03/11/1995"];
$.ajax({
url:"backend/yourHandler.php",
type:"POST",
dataType:"text",
data:{ HeaderArray : HeaderArray },
success:function(result){
console.log(result);
},
error:function(err,status,xhr){
console.log(err);
}
});
return false;
});
});
</script>
// backend/yourHandler.php
<?PHP print_r($_POST); ?>
I have a page with list of buttons, when each button is clicked, it's value is captured and ajax call in made. PHP does DB updates on ajax call. I want to return data to ajax call. The data is obtained from DB. But I'm unable to point out what's the error in below code.
Here is PHP code:
if (isset($_GET['val']))
{
$chapter_id=$_GET['val'];
$sql= "SELECT file_name,edit_link,name,email FROM `chapter_list` where chapter_id='$chapter_id'";
$result = mysql_query($sql,$rst);
while($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
}
$update=mysql_query("UPDATE `chapter_list` SET `status` = '$update_status' WHERE `chapter_list`.`chapter_id` = '$chapter_id';");
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
}
Here is the AJAX request
$(document).ready(function(){
$('.btn').click(function(){
var clickBtnValue = $(this).val();
$.ajax ({
url: '',
data: { val : clickBtnValue},
dataType:'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I'm not getting the alert!
Try like this.
Maybe response data is null.check your php code(query lines).
Here My php code is :
if (isset($_GET['val'])) {
$vol_name = 'dummy_name';
$vol_email = 'dummy_email';
$vol_link = 'dummy link';
header('Content-Type: application/json');
echo json_encode(array("name"=>$vol_name,"email"=>$vol_email,"link"=>$vol_link));
exit;
}
My javascriptcode is :
<input type="text" class="btn" value="test" />
<script type="text/javascript">
if('addEventListener' in document){
document.addEventListener("DOMContentLoaded", function(e){
//dom loaded
$(document).on("click",".btn",function(e){
e.preventDefault()
var e_val = $(this).val();
console.log('my value is :' + e_val);
if(e_val){
$.ajax({
type: "get",
dataType: 'json',
url: 'here your url or slash',
data: { // request e_val
val : e_val,
}
}).done(function(xhr) {
// console.log(xhr);
if(xhr.name){
alert('response data is '+ xhr.name);
}
})
}
})
},false)
}
</script>
try this..
while($row = mysql_fetch_assoc($result))
{
$vol_name = $row["name"];
$vol_email= $row["email"];
$vol_link= $row["edit_link"];
$ret[$vol_name]= array(
'email'=>$vol_email,
'link'=>$vol_link
);
}
then use in the return statement..
echo json_encode($ret);
You can send parameters in HTML
<button class="btn" atribute_id="21543">Button</button>
$(document).ready(function() {
$('.btn').click(function() {
var Value_of_Btn= $(this).attr("atribute_id"); <-------
$.ajax({
url: '',
data: {
val: clickBtnValue
},
dataType: 'JSON',
success: function(res) {
alert(res.name);
}
});
});
});
I have a form that collect user info. I encode those info into JSON and send to php to be sent to mysql db via AJAX. Below is the script I placed before </body>.
The problem now is, the result is not being alerted as it supposed to be. SO I believe ajax request was not made properly? Can anyone help on this please?Thanks.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var param2 = <?php echo $param = json_encode($_POST); ?>;
if (param2 && typeof param2 !== 'undefined')
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: param2,
cache: false,
success: function(result) {
alert(result);
}
});
}
});
});
</script>
ajaxsubmit.php
<?php
$phpArray = json_decode($param2);
print_r($phpArray);
?>
You'll need to add quotes surrounding your JSON string.
var param2 = '<?php echo $param = json_encode($_POST); ?>';
As far as I am able to understand, you are doing it all wrong.
Suppose you have a form which id is "someForm"
Then
$(document).ready(function () {
$("#submit").click(function () {
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: $('#someForm').serialize(),
cache: false,
success: function (result) {
alert(result);
}
});
}
});
});
In PHP, you will have something like this
$str = "first=myName&arr[]=foo+bar&arr[]=baz";
to decode
parse_str($str, $output);
echo $output['first']; // myName
For JSON Output
echo json_encode($output);
If you are returning JSON as a ajax response then firstly you have define the data type of the response in AJAX.
try it.
<script>
$(document).ready(function(){
$("#submit").click(function(){
var param2 = <?php echo $param = json_encode($_POST); ?>
if( param2 && typeof param2 !== 'undefined' )
{
$.ajax({
type: "POST",
url: "ajaxsubmit.php",
data: dataString,
cache: false,
dataType: "json",
success: function(result){
alert(result);
}
});}
});
});
</script>
It's just really simple!
$(document).ready(function () {
var jsonData = {
"data" : {"name" : "Randika",
"age" : 26,
"gender" : "male"
}
};
$("#getButton").on('click',function(){
console.log("Retrieve JSON");
$.ajax({
url : "http://your/API/Endpoint/URL",
type: "POST",
datatype: 'json',
data: jsonData,
success: function(data) {
console.log(data); // any response returned from the server.
}
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="submit" value="POST JSON" id="getButton">
For your further readings and reference please follow the links bellow:
Link 1 - jQuery official doc
Link 2 - Various types of POSTs and AJAX uses.
In my example, code snippet PHP server side should be something like as follows:
<?php
$data = $_POST["data"];
echo json_encode($data); // To print JSON Data in PHP, sent from client side we need to **json_encode()** it.
// When we are going to use the JSON sent from client side as PHP Variables (arrays and integers, and strings) we need to **json_decode()** it
if($data != null) {
$data = json_decode($data);
$name = $data["name"];
$age = $data["age"];
$gender = $data["gender"];
// here you can use the JSON Data sent from the client side, name, age and gender.
}
?>
Again a code snippet more related to your question.
// May be your following line is what doing the wrong thing
var param2 = <?php echo $param = json_encode($_POST); ?>
// so let's see if param2 have the reall json encoded data which you expected by printing it into the console and also as a comment via PHP.
console.log("param2 "+param2);
<?php echo "// ".$param; ?>
After some research on the google , I found the answer which alerts the result in JSON!
Thanks for everyone for your time and effort!
<script>
$("document").ready(function(){
$(".form").submit(function(){
var data = {
"action": "test"
};
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "response.php", //Relative or absolute path to response.php file
data: data,
success: function(data) {
$(".the-return").html(
"<br />JSON: " + data["json"]
);
alert("Form submitted successfully.\nReturned json: " + data["json"]);
}
});
return false;
});
});
</script>
response.php
<?php
if (is_ajax()) {
if (isset($_POST["action"]) && !empty($_POST["action"])) { //Checks if action value exists
$action = $_POST["action"];
switch($action) { //Switch case for value of action
case "test": test_function(); break;
}
}
}
//Function to check if the request is an AJAX request
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
function test_function(){
$return = $_POST;
echo json_encode($return);
}
?>
Here's the reference link : http://labs.jonsuh.com/jquery-ajax-php-json/
Finding place when enter pincode using ajax php. But it doesn't work properly. When we enter each pincode that pincode is checked and then result of that place is displayed .
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" />
<div id="section1"></div>
I am setting this section as input fields.
<script>
$(document).ready(function() {
$('#pincode').keyup(function() {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { console.log(data.success);
if(data.success){
$.each(data.results[0].address_components, function(index, val){
console.log(index+"::"+val.long_name);
$('#section1').append( val.long_name+'<br>');
});
}
},
});
});
});
</script>
This is ajax section for send data to pincode_check.php.
I am doing pincode_check.php look like below. Here passing value retrive in $pincode variable then using maps.google.com to find logitude of that place. Then find corresponding place. That place name display in below the form field. But it does not worked properly.
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->results[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
Try this, In your ajax response success object was missed. I have rewritten the code,
also, pincode_check.php
if($data==true)
{ // Check if address is available or not
$data->result[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
In HTML: should be (Remove # in html id element)
<div id="section1"></div>
instead of
<div id="#section1"></div>
UPDATE:
<script>
$(document).ready(function() {
$('#pincode').keyup(function() {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) { console.log(data.success);
if(data.success){
$.each(data.results[0].address_components, function(index, val){
console.log(index+"::"+val.long_name);
$('#section1').append( val.long_name+'<br>');
});
}
},
});
});
});
</script>
HTML:
<label for="pincode">Pin-Code:</label>
<input name="pincode" type="text" class="text" id="pincode" />
<div id="section1"></div>
PHP code
<?php
$pincode=$_REQUEST['pincode'];
$geocode=file_get_contents('http://maps.google.com/maps/api/geocode/json?address='.$pincode.'&sensor=false');
$response= json_decode($geocode); //Store values in variable
$lat = $response->results[0]->geometry->location->lat; //Returns Latitude
$long = $response->results[0]->geometry->location->lng; // Returns Longitude
$geocode=file_get_contents('http://maps.googleapis.com/maps/api/geocode/json?latlng='.$lat.','.$long.'&sensor=false');
$data= json_decode($geocode);
if($data==true)
{ // Check if address is available or not
$data->result[0]->formatted_address ;
$data->success=true;
echo json_encode($data);
}
else {
$data->success= false;
echo json_encode($data);
}
?>
Try this which has a ready handler
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#pincode').live('change', function() {
//ajax request
$.ajax({
url: "pincode_check.php",
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) {
if(data.success ==true){
$('#section1').html(data.address_components);
}
},
});
});
});
</script>
Debug your script.
Are you getting data in your $pincode variable?
var_dump($pincode);
I prefer use a defined method in the ajax request, like post:
$.ajax({
url: "pincode_check.php",
method: 'POST'
data: {
'pincode' : $('#pincode').val()
},
dataType: 'json',
success: function(data) {
if(data.success ==true){
$('#section1').html(data.address_components);
}
},
});
Your success function has already the response, there is no need to use the conditional:
if(data.success ==true){
$('#section1').html(data.address_components);
}
Try to debug it to know what data are you recieving:
success: function(data) {
console.log(data);
}
},