I have an JSON format string which I want to add like a parameter to atach to a post request.
I'm trying to do the reques, when I do the request I get this error from my web service:
#0 /opt/assets/WS/ws.php(48): Slim\Slim::handleErrors(8, 'Trying to get p...', '/opt/assets/WS/...', 48, Array)
#1 [internal function]: {closure}()
#2 /opt/assets/WS/vendor/slim/slim/Slim/Route.php(468): call_user_func_array(Object(Closure), Array)
#3 /opt/assets/WS/vendor/slim/slim/Slim/Slim.php(1357): Slim\Route->dispatch()
#4 /opt/assets/WS/vendor/slim/slim/Slim/Middleware/Flash.php(85): Slim\Slim->call()
#5 /opt/assets/WS/vendor/slim/slim/Slim/Middleware/MethodOverride.php(92): Slim\Middleware\Flash->call()
#6 /opt/assets/WS/vendor/slim/slim/Slim/Middleware/PrettyExceptions.php(67): Slim\Middleware\MethodOverride->call()
#7 /opt/assets/WS/vendor/slim/slim/Slim/Slim.php(1302): Slim\Middleware\PrettyExceptions->call()
#8 /opt/assets/WS/ws.php(59): Slim\Slim->run()
#9 {main}
It's like the request doesn't contains a real JSON object. How can I transform it? I did some tricks but seems doesn't work.
That's my script:
assets.controller('AfegirTipusActiusCtrl', function ($scope, $http){
// Camps formulari text pla
/* $scope.nomAtribut = "<input type='text' name='firstname'>";
$scope.mida = "<input type='number' name='firstname'>";
$scope.obligatori = "<input type='checkbox' name='vehicle' value='yes'>"; */
// Construeix combo
$http.get('http://10.0.203.73/WS/ws.php/getCombo/1').success(function(data) {
$scope.options = data;
});
$scope.atributs = [];
$scope.addRow = function(){
var newRow = {
nomAtribut: "",
tipus: "",
mida: "",
prioritat: "",
obligatori: "",
observacions: ""
}
$scope.atributs.push(newRow);
}
/* $scope.addField = function() {
$scope.atributs.push(newRow);
};*/
$scope.prioritat = $scope.atributs.length;
// Envia atributs a WS
$scope.sendRow = function(){
var d = "{'nomAtribut': 'marca','tipus': 'String','mida': '15','prioritat': '1','obligatori': 'No'}";
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", angular.toJson(d)).success(function(data){
$scope.status = data;
})
}
});
Edit:
Also I add the php Slim function which parse the request:
$app->post('/tipusactius/alta', function () use ($app) {
$json = $app->request->getBody();
header("Content-Type: application/json");
$json_decode = json_decode($json); // $json_decode conte l'bjecte format a partir del json del request
echo $json_decode->{'tipus'};
// $sql = "INSERt INTO atributs_actiu (nomAtribut, midaAtribut, tipus_actius_idtipus_actius, atributObligatori, ordre, tipusAtributs_idTipus, observacions
// , combo_idcombo, combo_codi) values ('".$json_decode->{'nomAtribut'}."', '".$json_decode->{'mida'}."', 1, '0', 1, 1, 'atribut de prova', 1, 1)";
$sql = "INSERt INTO atributs_actiu (nomAtribut, midaAtribut, tipus_actius_idtipus_actius, atributObligatori, ordre, tipusAtributs_idTipus, observacions
, combo_idcombo, combo_codi) values ('".$json_decode->{'nomAtribut'}."', '3', 1, '0', 1, 1, 'atribut de prova', 1, 1)";
$mysqli=getDB();
$result = $mysqli->query($sql);
});
Solved:
Like #vidriduch told:
$scope.sendRow = function() {
var d = {
'nomAtribut': 'marca',
'tipus': 'String',
'mida': '15',
'prioritat': '1',
'obligatori': 'No'
};
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", angular.toJson(d)).success(function(data) {
$scope.status = data;
})};
angular.toJson Serializes input into a JSON-formatted string
https://docs.angularjs.org/api/ng/function/angular.toJson
in your case you are serializing string ...
your code could look like this:
$scope.sendRow = function() {
var d = {
'nomAtribut': 'marca',
'tipus': 'String',
'mida': '15',
'prioritat': '1',
'obligatori': 'No'
};
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", angular.toJson(d)).success(function(data) {
$scope.status = data;
})};
If you want to convert a JSON string to JavaScript object, you should use the angular.fromJson() method.
Also, make sure to convert your single quotes ' to double quotes " in your JSON:
// ' becomes " in your string
var d = '{"nomAtribut": "marca","tipus": "String","mida": "15","prioritat": "1","obligatori": "No"}';
$http.post("http://10.0.203.73/WS/ws.php/tipusactius/alta", angular.fromJson(d))
.success(function(data){
$scope.status = data;
}
Make sure your JSON argument not locked by arbitrary reference.
Assigning a JSON string to a variable and passing it directly will work here.
Related
I'm trying to pass my JS array to PHP array and all of the solutions that I have found here is useless or I can integrate these solutions to my problem.
Javascript
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
PHP
function ekleme(){
if($_POST['siparisListe']){
$liste = $_POST['siparisListe'];
echo $liste;
}
}
instead of this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
modify you code in to this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
var input_data = new FormData();
$.each(splitListe,function(index,value){
input_data.append("siparisListe["+index+"]",value)
});
$.ajax({
url: "menu.php",
data: input_data,
type: "POST",
success: function(data) {
$("#passwordMatch").html(data);
},
error: function(data) {}
})
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
Remove the [] from the POST field name and pass it an array (jQuery will JSON encode it for you).
$('#siparisButon').click(function() {
let splitListe = ($('#siparis-block span').text() || '').split('- ');
if (splitListe) {
$.post("menu.php", { siparisListe: splitListe });
$('#fonksiyon').show();
}
});
Then in your PHP to verify:
function ekleme() {
if ($liste = $_POST['siparisListe']) {
var_dump($liste);
}
echo 'No $liste array in POST.';
}
I want to send in ajax array in js, get it in php as an array and insert into with sql.
My ajax call looks like:
jQuery("#Save").click(function () {
$(".linesView").each(function () {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if(window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = json_encode([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": data }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
The PHP code that needs to get the ajax call and add the data (by sql insert) looks like:
if(isset($_POST['action_name','data'])) {
$action_name = $_POST['action_name'];
$data=json_decode($_POST['data']);
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}
The accountid coming from the top of the page, I already do delete action and it works fine, so the accountid is ok. All others, I don't know.
I tried to do encode and then decode. I am not sure if the syntax is right. Anyway if I didn't write elegant code, please show me how it needs to look. Maybe i need to take each param from the data and not to call data[x]?
Use JSON.stringify()
var data = ([category,date,amount,repeated,note]);
$.post("AjaxHandler.php", { "action_name": action_name, "data": JSON.stringify(data) }, function () {
//$("#ExpensesId_" + id).css('display', 'none');
});
Encode the data array to JSON string using JSON.stringify() in javascript. At server side use json_decode() to decode the data.
jQuery:
jQuery("#Save").click(function() {
$(".linesView").each(function() {
var action_name = "";
if (window.current_category === "Expenses") {
action_name = "Save_Expenses"
} else if (window.current_category === "Incomes") {
action_name = "Save_Incomes"
}
var line_id = $(this).attr("id").substring(5);
var category = $("#CategoryValue_" + line_id).html();
var date = $("#DateValue_" + line_id).html();
var amount = $("#AmountValue_" + line_id).val();
var repeated = $("#RepeatedValue_" + line_id).html();
var note = $("#NoteValue_" + line_id).val();
var data = JSON.stringify([category, date, amount, repeated, note]);
//-----------------^--- Array to JSON string
$.post("AjaxHandler.php", {
"action_name": action_name,
"data": data
}, function() {
//$("#ExpensesId_" + id).css('display', 'none');
});
});
});
PHP :
if(isset($_POST['action_name','data'])){
$action_name = $_POST['action_name'];
$data=json_decode(json_decode($_POST['data']));
//-----^--- decoding JSON string
$query = mysql_query("INSERT INTO Expenses (accountid, category, date, amount, repeated) VALUES ('$accountid', '$data[0]', '$data[1]', '$data[2]', '0')");
}
I used this Code to send a form + a variable to a php-script.
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos }).done(function (data) {
alert(data);
});
}
now the PHP-Code:
$data = $_POST['infos'];
echo $data;
returns: formfield1=value1&formfield2=value2&formfield3=value3&test
All values are in this variable...
But how i can use them seperatly with PHP?
For example:
$data = $_POST['formfield1'];
didn't worked :(
Use jQuery's serializeArray(). It will return you with array of objects that contain 2 properties: name and value. You can then parse it and pass it as data.
It could look like this
var formdata = = $('form').serializeArray();
var infos = { };
for (var i = 0; i < formdata.length; i++) {
infos[formdata[i].name] = formdata[i].value;
}
// To add separate values, simply add them to the `infos`
infos.newItem = "new value";
$.post("ajax.php", infos).done(function (data) {
alert(data);
});
Then in PHP, you'll retrieve values using $_POST["formfield1"].
Try to explode them with -
$data = $_POST['infos'];
$form_data = explode('&', $data);
$posted_data = array();
foreach ($form_data as $value) {
list($key, $val) = explode('=', $value);
$posted_data[$key] = $val;
}
var_dump($posted_data);
You can use the parse_str method to convert the query string into an array.
In your case, you can do something like this:
parse_str($_POST['infos'], $data); // $data['formfield1'], $data['formfield2'], $data['formfield3'] have the values you need
More details here: http://php.net/manual/en/function.parse-str.php
// here is the jquery part
function upload() {
var test = "test";
var infos = $('form').serialize() + '&' + test;
$.post("ajax.php", { infos: infos },function (data) {
alert(data); // the fetched values are alerted here.
});
}
//the php part is here
$data = $_POST['infos'];
$field_seperator='&';
$val_seperator='=';
$form_data_val=explode($field_seperator,$data);
foreach($form_data_val AS $form_vals){
$vals=explode($val_seperator,$form_vals);
echo $vals[1];// here the value fields of every form field and the test is fetched.
}
try this .
This code is working fine my concern is its output
Javascript side
function AjaxRetrieve()
{
var rid = document.getElementById('trg').value;
$.get('includes/getChat.php?chat='+uid + '&rid=' + rid + '&name=' + user,function(data)
{
$("#clog").html(data);
});
}
PHP side
$sql6="SELECT msgid FROM thread WHERE combination1=:msgids OR combination2=:submsgids LIMIT 1";
$msg_id = $con4->prepare($sql6);
$msg_id->bindParam(':msgids', $comb, PDO::PARAM_STR);
$msg_id->bindParam(':submsgids', $comb, PDO::PARAM_STR);
$msg_id->execute();
$msgd = $msg_id->fetchColumn();
$tbpre = $msgd;
$sql7 = "SELECT * FROM ".$tbpre."chat_conversation WHERE msgid=:chat";
$stmt7=$con3->prepare($sql7);
$stmt7->bindValue( 'chat', $msgd, PDO::PARAM_STR);
$stmt7->execute();
$rows = $stmt7->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($rows);
the output looks like this:
[{"msgid":"1","message_content":"asd","username":"ab","message_time":"2014-04-02 13:58:03","recipient":"cd"}]
how can I display the JSON result similar to this:
1
asd
ab
2014-04-02
cs
You can use the json dataType in jQuery, then stringify the object with indentation using JSON.stringify and output it in pre tags to keep the spaces and newlines
function AjaxRetrieve(){
var rid = document.getElementById('trg').value,
data = {chat : uid, rid : rid, name : user};
$.get('includes/getChat.php', data, function(result) {
var pre = $('<pre />', {text : JSON.stringify(result, undefined, 4)})
$("#clog").html(pre);
}, 'json');
}
FIDDLE
or to just output a list of the values
function AjaxRetrieve() {
var rid = document.getElementById('trg').value,
data = {chat: uid, rid: rid, name: user};
$.get('includes/getChat.php', data, function (result) {
var res = $([]);
$.each(result[0], function(key, value) {
res = res.add($('<div />', {text : value}));
});
$("#clog").html(res);
}, 'json');
}
Parse response on client side, and display it.
$.get('includes/getChat.php?chat='+uid + '&rid=' + rid + '&name=' + user,function(data){
var obj = JSON.parse(data);
var temp = obj[0].msgid + "<br>"+ obj[0].message_content + "<br>"+ obj[0].username + "<br>"+ obj[0].message_time + "<br>"+ obj[0].recipient;
$("#clog").html(temp);
});
PHP 5.4 offers the JSON_PRETTY_PRINT option for use with the json_encode() call.
Below is the link:
http://php.net/manual/en/function.json-encode.php
<?php
$json_string = json_encode($data, JSON_PRETTY_PRINT);
I actually have this array var checked_rls= ['24','56'];
var checked_rls = []
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls.push($(this).val());
});
and then I tried to pass it using AJAX
$.ajax(
{
type :"POST",
url : "sale_ajax.php",
data:
{
rls : checked_rls,
rls_date : $("#rls_date").val()
},
success: function(msg)
{
alert('saved successfully');
},
error: function()
{
alert("Failure");
}
});
and then i received the array in sale_ajax.php file like this $cont = $_POST['rls'];
Now the problem is that I can run this array in a forEach function, but when I tried to implode this array into a string it only returns one value.
For e.g. in this scenario I passed 24,56 and when I tried to implode(",",$cont); it only returns the very first value, 24:
var_dump($cont) output is
array(2){[0]=>string(2) "24" [1]=>string(2) "56"}
and the php code is:
if(isset($_POST['rls']))
{
$rls_date = $_POST['rls_date'];
$cont = $_POST['rls'];
$rls_cont_sold = implode(",",$cont);
$rls_insert = mysql_query("INSERT INTO release_details (release_date, cont_sold_id) VALUES (STR_TO_DATE('$rls_date', '%d-%m-%Y'), '$rls_cont_sold')")or die(mysql_error());
$id = mysql_insert_id();
foreach($cont as $val)
{
$cont_sold_update = "UPDATE cont_sold SET release_details_id = '$id' WHERE cont_sold_id = '$val'";
$insert = mysql_query($cont_sold_update)or die(mysql_error());
}
}
and the var_dump($_POST) is
array(2){
["rls"]=>(array(2){[0]=>string(2) "24" [1]=>string(2) "56"})
["rls_date"]=>string(10) "10-04-2015"
}
What is actually happening in this condition?
Thank you
Put below code in click event of chk_count element:-
$("input[name='chk_cont[]']").click(function(){
var checked_rls = [];
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls.push($(this).val());
});
});
Rather than passing passing an array why don't you pass a string itself, it will reduce your number of steps.
var checked_rls = "";
$("input[name='chk_cont[]']:checked").each(function ()
{
checked_rls += $(this).val()+",";
});