How to pass json object values to php dinamically? - javascript

Hi I'm newbie in JSON and Ajax and my question is probably quite stupid but when learning, also the stupid questions are fundamental.
I need to pass two parameters via Ajax (giorno and periodo),
for example
'giorno' = 2017-05-10 and
'periodo' = 2:
$.ajax({
type:'POST',
data: JSON.stringify({
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
}),
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
The JSON object passed perfectly and the result in Firebug Console is:
{"giorno":"2017-05-10","periodo":"2"}
If I try to manually copy and paste the object on the php page like this:
<?
$json = '{"giorno":"2017-05-10","periodo":"2"}'; //pasted manually
$json = json_decode($json, TRUE);
$giorno = $json['giorno'];
$periodo = $json['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
the two echoes show me the values. OK!
My problem start and stop here. I'm not able to bring the JSON object to be decoded.
I'm quite sure is a stupid solution but I don't know how to do that.
I need to create a function that wrap the Ajax call and then call the function in json_decode??
PS
I also tried to simply get the values with "$_POST['giorno']" etc.. instead of using JSON but without success.
Can someone help me please? Thank you for your patience.
UPDATE 10/05/2017
Hi I've followed your suggestions so I tried one time more to simplify the code like this:
$('input:radio[name=periodo]').change(function() {
var giorno = document.getElementById("dataselezionata").value; // from datepicker
var periodo = $('input:radio[name=periodo]:checked').val(); // from radio button
var post_data = ("giorno="+giorno+"&periodo="+periodo);
$.ajax({
type:'GET',
data: post_data,
url:"http://www.rinnovipatenti.com/prenota/prenotazione.php",
});
if (this.value == '1') {
$('#orario').show();
$('#orari-mattina').show();
$('#orari-pomeriggio').hide();
}
else if (this.value == '2') {
$('#orario').show();
$('#orari-pomeriggio').show();
$('#orari-mattina').hide();
}
using GET method instead of the POST one and in the PHP page prenotazione.php the code now is:
<?
$giorno = $_GET['giorno'];
$periodo = $_GET['periodo'];
echo"$giorno";
echo"$periodo";
?>
In Firebug console the parameters are ok
giorno 2017-05-10
periodo 2
the formatted link is:
http://www.rinnovipatenti.com/prenota/prenotazione.php?giorno=2017-05-10&periodo=2
the html console preview works correctly but the page don't.
I'm in the corner!
Is very strange. I have only one doubt: can I send data by GET/POST method to the same page where the data are collected?
In other word can the page foo.php send data to foo.php like a cycle without refresh?
And the ajax call could be wrapped inside the .change function or must be outside?

$.post( "http://www.rinnovipatenti.com/index2.php?a=prenotazione", {
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
} );
you do not need to stringify your JSON
on PHP side you just use
$giorno = $_POST['giorno'];
$periodo = $_POST['periodo'];
to get the values
you can use the following function. you have it already. it worked fine for me.
$('input:radio[name=periodo]').change(function() {
var giorno = '2017-05-15';
var periodo = '2';
$.post( 'http://www.rinnovipatenti.com/index2.php?a=prenotazione', {
giorno: giorno,
periodo: periodo
});
/*....*/
});

Method 2
You don't have to stringify the JSON object
$.ajax({
type:'POST',
data: {
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
},
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
So you php code will be like this
<?
$giorno = $_POST['giorno'];
$periodo = $_POST['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>
Method 2
If you want to stringify the JSON object then put it in a key
$.ajax({
type:'POST',
data: 'data='+JSON.stringify({
giorno: $('#dataselezionata').val(),
periodo: $('input:radio[name=periodo]:checked').val()
}),
contentType: "application/json; charset=utf-8",
dataType : 'json',
url:'http://www.rinnovipatenti.com/index2.php?a=prenotazione'
});
So you php code will be like this
<?
$json = $_POST['data'];
$json = json_decode($json, TRUE);
$giorno = $json['giorno'];
$periodo = $json['periodo'];
echo"$giorno"; //2017-05-10
echo"$periodo"; //2
?>

When you send application/json payload to php to access that payload use:
$json = json_decode(file_get_contents('php://input'), TRUE);
As mentioned in other comments and answers if you stay with $.ajax default form encoding and don't json stringify the data then use $_POST

Related

How to can I print an array transferred from javascript to php from $_POST

I am trying to transfer a javascript array to a php array and I used the following code in my php file to do so:
var rowArr=[];
var currow=$(this.closest('tr'));
var col1=currow.find('td:eq(0)').text();
rowArr.push(col1);
var col2=currow.find('td:eq(1)').text();
rowArr.push(col2);
var col3=currow.find('td:eq(2)').text();
rowArr.push(col3);
var myJSONText = JSON.stringify( rowArr );
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function() {
alert("Success");
}
});
so when I run this code, I get the success alert but I am not seeing any of the array elements being printed out. I am also not getting any error messages.Here is my jsonRecieve.php:
<?php
$rowAr=$_POST['emps'];
print_r($rowAr);
?>
is there a way to verify that it has been transferred? I don't believe it has but if it hasn't can someone help?
Seems you need to decode the json string with json_decode() to get your emps value on the server side and to alert the server response need to send something from the server. Let's debug this way-
ON JS
$.ajax({
type: "POST",
url: "jsonRecieve.php",
data: { emps : myJSONText},
success: function(data) {
alert(data); // alert your data to see that returns from server
}
ON PHP
<?php
$rowAr=$_POST['emps'];
$array = json_decode($rowAr,1); // 2nd params 1 means decode as an array
print_r($array);
die('response from the server');
?>

AJAX not coming up a success even though its updating the database

My php is updating the table but not refreshing in javascript have tried several different ways of doing this and nothing is working.
PHP
$sql = "UPDATE INTOXDM.ASTP_FORM SET SUPERVISOR_EID = '".$newSuper."' WHERE FORMID = '".$formId."'";
$row = $xdm->fetch($sql);
$return["color"] = $row['APPRENTICE_SIGNATURE'];
$return["json"] = json_encode($return);
echo json_encode($return);
?>
Javascipt
var data = {
"formId": formID,
"newSuper": newSuper
};
data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
success: function() {
location.reload();
}
});
I'd start by modifing the code like this:
var data = {
"formId": formID,
"newSuper": newSuper
};
// No need for serialization here,
// the 'data' parameter of jQuery.ajax accepts JS object
// data = $.param(data);
$.ajax({
type: "POST",
dataType: "json",
url: "src/GetInfo.php",
data: data,
// As suggested by Rocket Hazmat, try to add an error callback here
error: function(jQueryXHR, textStatus, errorMessage) {
console.log("Something went wrong " + errorMessage);
},
success: function(jsonResponse) {
// Try to reference the location object from document/window
// wd = document or window as seen here http://stackoverflow.com/questions/2624111/preferred-method-to-reload-page-with-javascript
// Also watch out, usually browsers require a user confirmation before reloading if the page contains POST data
// One of these should be fine
wd.location.assign(wd.location.href) : go to the URL
wd.location.replace(wd.location.href) : go to the URL and replace previous page in history
wd.location.reload(<true/false/blank>) : reload page from server/cache/cache
}
});
Also, this might be a shot in the dark but the parameter dataType gave me problems sometime in the past, so if you are sure about the json returned by your php script, you could use the eval function to jsonify the response
$.ajax({
...
// Remove data type
// dataType: "json",
...
success: function(plainTextResponse) {
// Eval response, NOT SAFE! But working
var jsonResponse = eval('('+ plainTextResponse +')');
...
}
});
Your ajax is expecting json data and your php is sending malformed json string. Send a correct json string and your script will work fine.
Your php json_encode should be like this:
$data = json_encode($return);
echo $data;

Ajax Error Potentially Due to Incorrect Data Object Being Passed

Hi I am new to ajax and I am attempting to pass a Json to a Database, but I am not that far yet. Currently I am attempting to be verified that the data I am passing is being done successfully. However, I always drop into the ajax error method. I will upload my code and the way the data looks and then the error.
Thank you for your help!
<script>
function updateTable()
{
alert("Do i try to update table?");
document.getElementById("testLand").innerHTML = "Post Json";
//echo new table values for ID = x
}
function popupClick (){
var popupObj = {};
popupObj["Verified_By"] = $('#popupVBy').val();
popupObj["Date_Verified"] = $('#popupDV').val();
popupObj["Comments"] = $('#popupC').val();
popupObj["Notes"] = $('#popupN').val();
var popupString = JSON.stringify(popupObj);
alert(popupString);
$.ajax({
type: "POST",
dataType: "json",
url: "popupAjax.php",
data: popupObj,
cache: false,
success: function(data)
{
alert("Success");
updateTable();
},
error: function(data)
{
alert("there was an error in the ajax");
alert(JSON.stringify(data));
}
});
}
</script>
JSON Being Passed shown in var popupString:
Error:
popupAjax.php file (warning it's testy)
<?php
echo "Testing tests are testy";
?>
You are specifying the dataType as json. But this is the returned data type, not the type of the data you are sending.
You are returning html / text so you can just remove the dataType line:
type: "POST",
url: "popupAjax.php",
If you do want to return json, you need to build your datastructure on the server-side and send it at the end. In your test-case it would just be:
echo json_encode("Testing tests are testy");
But you could send a nested object or array as well.
As an additional note, you can use .serialize() on your form (if you use a form...) so that jQuery automatically builds an object that you can send in the ajax method. Then you don't have to do that manually.

Getting PHP variable to jquery script file by AJAX call

So basically i have two files. 1 is my php file and it creates tables with some variables when it's called, and second file is jquery script file that makes that call. My script file:
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
$('#results').html(data);
}
});
and it works fine by printing my results.
My php file is echoing data that should be printed in my results div.
Question is how to get some PHP data variables and be able to use them in my jquery file without actually echoing them ??
Like i said in my comment to your question, a way to do that is by echoing the variables on a script tag, so you can access in javascript.
<script>
var PHPVariables;
PHPVariables.VariableName1 = '<?=$phpVariableName1?>';
PHPVariables.VariableName2 = '<?=$phpVariableName2?>';
PHPVariables.VariableName3 = '<?=$phpVariableName2?>';
</script>
And you could use those values accessing PHPVariables.VariableName1 on the javascript.
You can do this by echoing all the data you want like so peiceofdata§anotherpeice§onemorepeice§anotherpeice then you can use php's explode function and use § for the "exploding char" this will make an array of all the above data like this somedata[0] = peiceofdata somedata[1] = anotherpeice and so on.
the explode function is used like this
explode('§', $somestringofinfoyouwanttoturnintoanarray);
you can then echo the relevent data like so
echo data[0];
which in this case wiill echo the text peiceofdata.
write this type of code in ajax file
var data =array('name'=>'steve', date=>'18-3-2014');
echo jsonencode(data);
//ajax call in this manner
$.ajax({
type: 'POST',
data: pass data array,
url: ajaxfile url,
success: function(data) {
var data = $.parseJSON(data);
$('#name').html(data.name);
$('#date').html(data.date);
}
});
Use json format, and in this json add your data variables :
PHP :
$arr = array('var1' => $var1, 'var2' => $var2, 'var3' => $var3);
echo json_encode($arr);
Javascript :
$.ajax({
type: 'POST',
data: ({p:2,ank : ankieta,wybrane:wybrane}),
url: 'zestawienia_db.php',
success: function(data) {
data = JSON && JSON.parse(data) || $.parseJSON(data);
$('#results1').html(data.var1);
$('#results2').html(data.var2);
}
});

Array from javascript to php with Ajax - Mootools

Actually i'm developing a timetable selector. Well now i'mt trying to send the values to the miscrosoft sql server database.
I'm using mootools, and i'm doing a request as Ajax to pass all values from javascript to php. My problem is that if i send each value individually, it is very slow. So i'm trying to send every values in a javascript object.
var myRequest = new Request.HTML({
url: "index.php?pagina=2087&",
method: "post",
data: 'transfer='+artigos_sessao,
onSuccess: function(responseTree, responseElements, responseHTML, responseJavaScript){
<?php saveData(); ?>
},
}).send();
artigos_sessao is my object with this format {'key':{'id':value,'sessao':value},...}.
And in PHP side i'm doing this
$array= $_POST['transfer'];
echo $array;
But always my $array variable is empty.
What i'm doing wrong?
Thanks.
You can pass a object into the data field of the Request. So my suggestion is to remove parameters from the url and just pass everything as a object in the data:
var myRequest = new Request.HTML({
url: "index.php",
method: "post",
data: {
'pagina': 2087,
'transfer': artigos_sessao
},
onSuccess: function (responseTree, responseElements, responseHTML, responseJavaScript) {
<? php saveData(); ?> // this code is not in your question, i supose you have javascript here hopefully :)
},
}).send();

Categories

Resources