PHP: How to get non-form data from ajax - javascript

I'm trying to get data from a user interface to PHP.
In JS, I have:
var myPostData=JSON.stringify({'categoria':valor,'fluxo':fluxo});
$.ajax({
url:'data.php',
type:'post',
data:myPostData,
dataType: "json",
});
Where valor and fluxo are variables.
And in PHP:
if (isset($_POST['categoria'])){
$fluxo=$_POST['fluxo'];
$categoria=$_POST['categoria'];
echo("Fluxo ".$fluxo);
echo("categoria ".$categoria);
}else{
echo "nada";
}
But I can't get the data to be processed by PHP. I always get 'nada' in return...
Thanks in advance for any help!

Instead of transforming the data to a JSON string, just add it as a plain Javascript object:
var myPostData={'categoria':valor,'fluxo':fluxo};
$.ajax({
url:'data.php',
type:'post',
data:myPostData,
dataType: "json",
});
Also as pointed out in comments, you are accessing the POST variable by $_POST['valor'], when you are sending it as $_POST['categoria'].

Related

Sending AJAX post request to PHP

So here is my AJAX code using JQuery:
$('#button-upload').on('click', function(){
if( sendSMSArr.length > 0 ){
$.ajax({
url: 'manager/smsendr4.php',
type: 'POST',
dataType: 'json',
data: {'distribution': sendSMSArr},
success: function(response){
}
});
}
});
The request isn't registered in the network.
Secondly, I'm not sure how can I collect this data with PHP using $_POST.
You seem to be a php newbie. Here is a snippet of code you can use to retrive the ajax data.
Here is the link to the documentation about the global variable $_POST I suggest you to read it.
Another useful link about the predefined variables in php
JS code:
$('#button-upload').on('click', function(event){
event.preventDefault();
if( sendSMSArr.length > 0 ){
$.ajax({
url: 'manager/smsendr4.php',
type: 'POST',
dataType: 'json',
data: {'distribution': sendSMSArr},
success: function(response){
console.log(response);
}
});
}
});
PHP:
<?php
if(isset($_POST['distribution'])){
# I've added a sanitization filter, but you can omit it if you don't need to pass the data to a database.
$dist = filter_var($_POST['distribution'], FILTER_SANITIZE_STRING);
# put your logics here after you got the distribution $_POST variable value.
}
?>

How to pass json object values to php dinamically?

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

Return only a json object to ajax caller

I'd like to return/access just an array on my success callback.
But I only get the whole html page.
$.ajax({
'URL': 'getData.php',
success:function(data){
alert(data); //Whole html file
}
})
getData.php
<?php
//Feed the array with database content
echo json_encode( $columns );
?>
How may I access the just the content of $columns
Obs1: My php file contains ONLY php code, 100%.
This is what is printed with alert above:
Your script is has HTML which cannot be parsed so make sure it returns only json string.
I know what do you mean, you can parse the json in javascript which was sent by PHP using JSON.parse(string);
Make sure your php doesn't return any other string or HTML other than encoded json.
Here is your modified JS, It should work as intended, You can check your desired output in browser console.
$.ajax({
'URL': 'getData.php',
success:function(data){
data = JSON.parse(data);
console.log(data);
alert(data); //Whole html file
}
})
I think that you have to set the dataType, and put url without single quotes.
Try to do this...
$.ajax({
type: 'GET',
url: 'getData.php',
dataType: 'json',
success: function (data) {
$.each(data, function(index, element) {
/* Operate with each array row */
});
}
});

Making Key Value pair for the form elements in JavaScript

I have a module where the forms created are dynamic. So the number of inputs can defer always. Also, the array key can also defer.
My current method of posting form is this:
name = form_options[option_1] value = 1
On submitting the form using POST, I get the form as array in $_POST, which looks like this.
form_options(
option_1 => 1
)
But, now I am trying to implement the same thing using AJAX. So, I would need a common module to get all form values.
I found a way to do it.
var objectResult = $('#options_form').serializeArray();
console.log(objectResult);
This gives me a result like this:
0: Object
name: "form_options[option_1]"
value: "1"
How can parse this result to get an array like $_POST array, which I can send as data in AJAX.
P.S: All the form elements have name field as form_options[key]
You should use this for get post data in PHP file.
// You can use like this
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: "POST", // Enter Request type GET/POST
url: 'action.php', // Enter your ajax file URL here,
dataType: 'json', // If you are using dataType JSON then in php file use die( json_encode($resultArray) );
data: objectResult, // Put your object here
beforeSend: function(){
alert('before');
},
error: function(data) {
console.log(data);
},
success: function(response){
console.log(response);
}
});
// In php file get values like this way
$_POST['form_options']
try like this,
In JQuery:
var objectResult = $('#options_form').serializeArray();
$.ajax({
type: 'POST',
url: 'yoururl'',
data: objectResult ,
success:function(data){
alert(data);
}
});
In your php:
<?php echo var_dump($_POST);?>
You can use jquery serialize with ajax directly, there is no need to use serializeArray:
$.ajax({
type:"post",
url:"formHandleSkript.php",
data: $("#options_form").serialize(),
success: function(response){
$(".result").html(response);
}
});
For more information see http://api.jquery.com/serialize/

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

Categories

Resources