Ajax is not working properly - php

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

Related

How to pass an associative array to a PHP file using ajax

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

Return JSON from PHP to ajax on button click

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

How to send json to php via ajax?

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/

AJAX success function not executing

I'm trying to create a simple AJAX call for testing, but have encountered a problem. I have nested in my AJAX call a success function which should pop an alert message but it doesn't. Checking firebug, the POST is successful and responds with "A20" (without quotations). Is there something wrong in my code?
index.php (view)
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="init.js"></script>
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<button id="your_button">Push me</button>
</body>
</html>
init.js
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: {"data": json_data},
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
posted.php
$category = $_POST['data']['category'];
$tsize = $_POST['data']['size'];
echo ($category);
echo ($size);
Try this -
$(function() {
$('#your_button').bind("click", function() {
var json_data = {"category": "A", "size": "20"};
$.ajax({
url: "posted.php",
dataType: "json",
type: "POST",
cache: false,
data: json_data,
success: function (data) {
if (!data.error) {
alert('k');
} else {
alert('error!');
}
}
});
});
});
Posted.php
$category = $_POST['category'];
$tsize = $_POST['size'];
//echo ($category);
//echo ($tsize);
echo json_encode($_POST);
Your want json data but you were not echoing json data
this is not right:
data: {"data": json_data}
do like this:
data: {data: json_data}
You need to set proper headers in your PHP and send a valid json response from PHP file. Add these lines to your PHP
header('Access-Control-Allow-Origin: *');
header('Content-type: application/json');
and echo back some valid json from it like echo '{"auth":"true","error":"false"}';
First you are using two jquery libraries, remove any one of them.
Second replace data: {"data": json_data}, with data: json_data,.
Third on posted.php use $category = $_POST['category'] and $tsize = $_POST['size'];.
Hope it will help you.

Trouble in ajax php to find palce use pincode

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>

Categories