How to pass JSON object from Controller to view - php

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

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

PHP doesn't get JQuery serialize() POST parameters

I want to send a form with JQuery $.ajax, but I have a problem. It's seems that PHP cannot get serialized $_POST. It's weird because the variable elementiPost is not empty, indeed if I do console.log(parametriPost) the console show me the right content.
The weirdest thing is that PHP get parameters that I append manually to parametriPost ($_POST['data_r']) but not those of $(this).serialize()!
If I put manually a number in $ore it works fine, so the problem is not the query.
Thank you.
Here's the code:
JQuery
$('form').submit(function(e) {
e.preventDefault();
var formId = $(this).attr('id');
var data = area_get_row_date(formId);
var parametriPost = $(this).serialize() + '&data_r=' + data;
$.ajax({
url: 'insert_db.php',
method: 'POST',
async: false,
data: parametriPost,
success: function() {
// Success code
},
error: function(xhr, status, error) {
alert("Errore!");
}
});
});
PHP (insert_db.php)
$data = str_replace('_', '.', $_POST['data_r']);
$ore = $_POST['orelavorateore_2_07_2015'];
$sql = "INSERT INTO ore_lav
VALUES (NULL, 134, 4,STR_TO_DATE('" . $data . "', '%d.%m.%Y'), " . $ore . ", 1, 1)";
$results = api_store_result(api_mysql_query($sql));
This is what parametriPost contains:
lavorati_prenotati=L&periodointegrazione_3_07_2015=on&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=a&extra_field1_orelavoratechf_3_07_2015=&extra_field1_orelavorateore_3_07_2015=&extra_field2_orelavoratechf_3_07_2015=&extra_field2_orelavorateore_3_07_2015=&orenonlavoratechf_3_07_2015=&orenonlavorateore_3_07_2015=&orenonlavoratetipologia_3_07_2015=L&extra_field1_orenonlavoratechf_3_07_2015=&extra_field1_orenonlavorateore_3_07_2015=&extra_field1_orenonlavoratetipologia_3_07_2015=L&extra_field2_orenonlavoratechf_3_07_2015=&extra_field2_orenonlavorateore_3_07_2015=&extra_field2_orenonlavoratetipologia_3_07_2015=L&orenonpagateore_3_07_2015=&orenonpagatetipologia_3_07_2015=L&extra_field1_orenonpagateore_3_07_2015=&extra_field1_orenonpagatetipologia_3_07_2015=L&extra_field2_orenonpagateore_3_07_2015=&extra_field2_orenonpagatetipologia_3_07_2015=L&orelavoratechf_3_07_2015=&orelavorateore_3_07_2015=&data_r=3_07_2015
You can use this snippet to convert your form data into JSON format :
$.fn.serializeObject = function()
{
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
$("form").submit(function( event ) {
event.preventDefault();
//convert form data to JSON
var params = $(this).serializeObject();
//add a 'data_r' field with some data to our JSON
params.data_r = 'sample data';
$.ajax({
url: 'app.php',
type: 'POST',
data: JSON.stringify(params),
})
.done(function(data) {
console.log(data);
});
});
and on the PHP side :
<?php
$data = json_decode(file_get_contents('php://input'), false);
print_r($data->data_r);
?>
Now $data is an object and you can access to a specific field :
$data->data_r

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/

jQuery post not passing parameters

I have a problem with posting variable to php script and getting result back without refreshing page. php script koord.php is tested and it's working fine.
This is my js code (adresa, mjesto and coords are text input boxes):
$(document).ready(function () {
$('#coord_click').click(function () {
provjera();
});
});
function provjera() {
var adresa = $('#adresa').val();
var mjesto = $('#mjesto').val();
var puna_adresa = adresa + " " + mjesto;
$.post("koord.php", { puna_adresa: puna_adresa },function (result) {
$('#coords').val(result);
});
}
koord.php:
$puna_adresa = $_GET['puna_adresa'];
function getCoordinates($address){
$address = str_replace(" ", "+", $address);
$url = "maps.google.com/maps/api/geocode/…";
$response = file_get_contents($url);
$json = json_decode($response,TRUE);
return ($json['results'][0]['geometry']['location']['lat'].",".$json['results'][0]['geo‌​metry']['location']['lng']);
}
echo getCoordinates($puna_adresa);
Complete source code is here: http://pastebin.com/u/bradetic
Thank you!
The Jquery POST is not the problem.
Your are doing $.post(...) which means that you need to get the parameter in koord.php via $_POST, and you are using $_GET, you see the problem right?
Solution
Change $_GET['puna_adresa']; to $_POST['puna_adresa'];
or
change $.post(...) for $.get(...) in your client side.
You know the difference between POST and GET right?
When do you use POST and when do you use GET?
How should I choose between GET and POST methods in HTML forms?
You seriously need to use Jquery AJAX, here's an example:
<script>
function your_function()
{
// collect data like this
var formData = jQuery("#your_form_id").serializeArray();
jQuery.ajax({
type: "POST",
url:"your_php_page.php",
data:formData,
dataType:'json',
beforeSend: function()
{
},
success: function(resp)
{
alert(resp);
},
complete: function()
{
},
error: function(e)
{
alert('Error: ' + e);
}
});
}
</script>
And you PHP script should go like this:
$puna_adresa=$_POST['puna_adresa'];
function getCoordinates($address){
$address = str_replace(" ", "+", $address);
$url = "maps.google.com/maps/api/geocode/…;;
$response = file_get_contents($url);
return $response;
}
$response = getCoordinates($puna_adresa);
echo json_encode($response);
Can you try this,
$.post("koord.php", { puna_adresa: adresa, mjesto: mjesto }, function (result) {
$('#coords').val(result);
});
Another way:
$.post("koord.php", $( "#testform" ).serialize(), function (result) {
$('#coords').val(result);
});
Ref: http://api.jquery.com/jQuery.post/
you May try this
$.post( "koord.php", $( "#testform" ).serialize() );

send data through an array

I want to send data through an array
This transmitter code:
<script type="text/javascript">
$(function() {
$(".cat_button").click(function() {
var element = $(this);
var test = $("#cou").val();
var test2 = $("#category2").val();
var data = [
{data:test},
{data:test2}
];
if(test=='' || test2=='.....')
{
alert("fill data");
}
else
{
$("#flash").show();
$("#flash").fadeIn(400).html('<img src="http://tiggin.com/ajax-loader.gif" align="absmiddle"> <span class="loading">Loading...</span>');
$.ajax({
type: "POST",
url: "insert2.php",
data: {data: data},
cache: false,
success: function(response){
console.log(response);
}
});
}
return false;
});
});
</script>
This code reception:
print_r($_POST['data']); // dumps an array
$course = $_POST['data'][0]['data'];
$category = $_POST['data'][1]['data'];
$insert_new_cou = mysql_query("insert into course (name,cat_id) values ('$course','$category')") or die($insert_new_cou."<br/><br/>".mysql_error());
But show me the following error:
Cannot use string offset as an array
I think the solution using Jtgson but I do not know how to use it
It can be done by JSON encoding your array of objects. In the $.ajax call:
...
url: "insert2.php",
data: {data: JSON.stringify(data)},
...
On the PHP side use json_decode() to get an array of objects from the JSON string:
$data = json_decode($_POST['data']);
$course = $data[0]->data;
$category = $data[1]->data;

Categories