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

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

Related

How to pass JSON object from Controller to view

There are many threads on the subject, but I cannot find any that use PHP. I want to pass the json object to the view, where I will later update an element with the returned json object.
Here is my code:
View:
<input type="submit" class="button" name="insert" value="load"/>
<script>
jQuery(document).ready(function() {
var $ = jQuery;
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = baseUrl+"?action=load";
data = {'action': clickBtnValue};
$.post(ajaxurl, {}, function (result) {
alert(result);
});
});
});
</script>
And Controller is:
<?php
set_include_path(get_include_path().':../');
require_once('_inc/common.php');
$action = req('action');
if ($action == 'load') {
$result = parse_ini_file('test.ini');
$json = json_encode($result);
}
[UPDATE]
After the code to the answers provided, I now get an Json.parse error. So I edited my code again but the error still persists, I checked online to see if my Json is a valid json and no error on the validator.
$result = parse_ini_file($config_file);
$json = json_encode(array($result),JSON_HEX_QUOT);
var_dump($json);
header('Content-Type: application/json');
View
var request = $.ajax({
url: ajaxurl,
method: "POST",
data: {},
dataType: "json"
});
request.done(function( msg ) {console.log("d");});
request.fail(function( jqXHR, textStatus ) {console.log( "Request failed: " + textStatus );});
});
Like said above, you aren't outputting the JSON, and also you are not setting the content type. But I noticed something else, you did not assign the return type of the post request (JSON).
$.post(url, {}, function (data) {
alert(data);
}, 'JSON');
Be also sure that you encode an array and not a false value, parse_ini_file returns false when it fails.
Try this
<script>
jQuery(document).ready(function() {
var $ = jQuery;
var baseUrl = [location.protocol, '//', location.host, location.pathname].join('');
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = baseUrl+"?action=load";
data = {'action': clickBtnValue};
$.post(ajaxurl, {}, function (result) {
var json =JSON.parse(result);
console.log(json); //see in browser console
});
});
});
</script>
And Controller is:
<?php
set_include_path(get_include_path().':../');
require_once('_inc/common.php');
$action = req('action');
if ($action == 'load') {
$result = parse_ini_file('test.ini');
echo json_encode($result);
}

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/

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>

Ajax is not working properly

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

Cannot get variable to send using $.ajax({data}) to PHP

I have tried these JS code combos:
var aion_settings = [];
function aion_save_settings(){
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: function(){
return aion_settings;
},
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
and...
function aion_save_settings(){
var aion_settings = [];
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: aion_settings,
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
..and
var aion_settings = [];
function aion_save_settings(){
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:{
settings: aion_settings,
other_data: 'Other Data'
},
success:function(result){
console.log(result);
}
});
}
..and these combos with:
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:aion_settings,
success:function(result){
console.log(result);
}
});
On this JQuery page it even has this example:
var xmlDocument = [create xml document];
var xmlRequest = $.ajax({
url: "page.php",
processData: false,
data: xmlDocument
});
xmlRequest.done(handleResponse);
On the receiving side, I have this PHP code:
$app->post('/save_settings',function() use ($app){
$aion_settings=$app->request()->post();
var_dump($aion_settings);
//Save the aion_settings
if(aion_logged_in_user_super()){
global $aion_db;
if(is_array($aion_settings)) foreach($aion_settings as $setting_key => $setting){
//Get the setting's ID
$current_setting = array();
$current_setting = $aion_db->queryFirstRow("SELECT id FROM settings WHERE setting_key=%s",$setting_key);
if(!isset($current_setting['id'])) $current_setting['id']=NULL;
$aion_db->insertUpdate('settings',array(
'id'=>$current_setting['id'],
'setting_key'=>$setting_key,
'value'=>serialize($setting)
));
}
}
});
The aion_settings is setup correctly just before the $.ajax request is sent. But, the object settings is not caught on the PHP side, though other_data is caught? The last line below shows the object ready via console.log but not set via $.ajax. I'm stumped, any help?
The data parameter of your $.ajax function should have the following format:
data: {
'settings': aion_settings,
'other_data': 'Other Data'
},
This is how I fixed it:
JS Side:
function aion_save_settings(){
var aion_settings = new Object();
//Users on the Site Frontend
$('.setting-site-users').each(function(){
aion_settings[$(this).prop('id')]=$(this).is(':checked');
});
console.log(aion_settings);
$.ajax({
method:'post',
url:'/save_settings',
dataType:'json',
data:aion_settings,
success:function(result){
console.log(result);
}
});
}
PHP Side:
$app->post('/save_settings',function() use ($app){
$aion_settings=$app->request()->post();
var_dump($aion_settings);
//Save the aion_settings
if(aion_logged_in_user_super()){
global $aion_db;
if(is_array($aion_settings)) foreach($aion_settings as $setting_key => $setting){
//Get the setting's ID
$current_setting = array();
$current_setting = $aion_db->queryFirstRow("SELECT id FROM settings WHERE setting_key=%s",$setting_key);
if(!isset($current_setting['id'])) $current_setting['id']=NULL;
$aion_db->insertUpdate('settings',array(
'id'=>$current_setting['id'],
'setting_key'=>$setting_key,
'value'=>serialize($setting)
));
}
}
});
Please compare with my question above.

Categories