i need to pass an array variable to Ajax request
<?
$postData = array(
'FirstName'=>$_POST['user_name'],
'Telephone'=>$_POST['user_phone'],
'Description' =>$_POST['komment'],
'Classifierid'=>'5E0696FD-831E-E611-9426-005056BAB261'
);
$postData = json_encode($postData);?>
i need to pass $postData to ajax variable data:
$(document).ready(function () {
var postData=<?php $postData ?>;
$.ajax({
url: "http://XXXXXXXXX/api/CallBackForm",
type: "POST",
crossDomain: true,
data: I need to put $posData here,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
});
});
`
I get the $postData successfully. All the code is in one php page.
Defining $postData like :
<?php $postData = json_encode(array('FirstName'=>$_POST['user_name'])); ?>
You can send directly the Json without datatype like :
$.ajax({
url: "http://XXXXXXXXX/api/CallBackForm",
type: "POST",
crossDomain: true,
data: '<?php echo $postData; ?>',
});
Or if you have to use the dataType: 'json' and ContentType option (important for server side), you can parse the json before sending ajax like :
$.ajax({
url: "http://XXXXXXXXX/api/CallBackForm",
type: "POST",
crossDomain: true,
data: JSON.parse('<?php echo $postData; ?>'),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
});
Related
i want to send a json data to my php but there is no response when i access it to my php.
this is my ajax request
var project = {project:"A"};
var dataPost = JSON.stringify(project);
$.ajax({
url: 'fetchDate.php',
data: {myData: dataPost},
type: 'POST',
datatype:'json',
contentType: "application/json",
success: function(data) {
alert(JSON.stringify(data));
}
});
});
and this is my php where i process the request and return back the data to test
<?php header("Content-Type: application/json; charset=UTF-8");
$objProject = json_decode($_GET["myData"]);
echo json_encode($objProject->project); ?>
i'm new to ajax so please i need your help
you don't need to add the content type on your ajax since you're not actually sending json to the server.
$.ajax({
url: 'fetchDate.php',
data: {myData: project},
type: 'POST',
datatype:'json',
// contentType: "application/json",
success: function(data, status, jqXHR) {
console.log(data,status,jqXHR);
alert(JSON.stringify(data));
}
});
no need to stringify project object,
in your php just encode it to json
<?php header("Content-Type: application/json; charset=UTF-8");
$obj = $_POST['myData'];
echo json_encode($obj); ?>
you should get json string on alert
Please try change
$objProject = json_decode($_GET["myData"]);
to
$objProject = json_decode($_POST["myData"]);
because ajax type : 'POST'
$.ajax({
url: 'fetchDate.php',
data: {myData: dataPost},
type: 'POST',
datatype:'json',
contentType: "application/json",
success: function(data) {
alert(JSON.stringify(data));
}
Php does not receive a variable through $ _POST. I'm trying to pass a variable with ajax to a php page, but php takes a variable as NULL. Tell me, what is the error and how to fix it?
jquery code:
var imgPath;
$(".close_modal_clear_cover").on("click", function(e) {
imgPath = $("#cover_preview").attr('src');
$.ajax({
url: "/management/ajax_scripts/img_delete.php",
type: "POST",
data: imgPath,
async: true,
cache: false,
contentType: false,
dataType: "json",
processData: false,
success: function (returndata) {
console.log(imgPath); //url of image
console.log(returndata); // NULL
}
});
});
img_delete.php code:
if (isset($_POST['imgPath'])) {
$path= $_POST['imgPath'];
unlink($path);
$response = $path;
} else {
$response = "false";
}
echo json_encode($response);
data: imgPath should be data: {imgPath: imgPath} and you should change your $_GETs to $_POSTs in the php backend
Thanks #Reflective for the help. Having studied what data comes in img_delete.php and a little googling, I found a solution. At me for some reason contentType was specified as false, but it was necessary 'application / x-www-form-urlencoded; charset = UTF-8 '.
This is a stupid mistake, but suddenly someone with the same collided.
$(".close_modal_clear_cover").on("click", function(e) {
// imgPath = $.session.get("imgCover");
imgPath = JSON.stringify($("#cover_prewiew").attr('src'));
$.ajax({
url: "/management/ajax_scripts/img_delete.php",
type: "POST",
data: {imgPath: imgPath},
async: true,
cache: true,
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
dataType: "json",
processData: true,
success: function (returndata) {
console.log(imgPath);
console.log(returndata);
}
});
});
I need help to do something small but I don't know how to solve it.
I have a javascript file with ajax inside like this
$.ajax({
data: "mc_id="+someid,
url: "includes/getDataPrs.php",
type: "GET",
dataType: "json",
async: false,
success: function(msg){
//some function here
}
});
in getDataPrs.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
header('Content-Type: application/json');
$id = null;
$date = null;
$limit = 0;
if (isset($_GET['mc_id'])) {
$id = $_GET['mc_id'];
}
//some process here $data
echo json_encode($data);
I can get data from $_GET['mc_id'] but when I need more data and I change the parameters in javascript like this
$.ajax({
data: "{'mc_id':'"+someid+"','limit':'"+somelimit+"'}",
url: "includes/getDataPrs.php",
and then I got nothing in php $_GET['mc_id'] or $_GET['limit']
in my desperate to solve it, I put in url "includes/getDataPrs.php?mc_id=someid&limit=somelimit
any comment or suggestion I truly appreciated
thanks in advance
passing multiple variable in ajax should be like
$.ajax({
data: {mc_id: someid, limit: some_limit},
url: "includes/getDataPrs.php",
type: "GET",
dataType: "json",
async: false,
success: function(msg){
//some function here
}
});
It is always better to use data: {mc_id: someid, limit: some_limit} because it will treated like object itself.
Try using following syntax for sending data in ajax function:
...
data:{mc_id:someid,limit:somelimit},
...
Without using quotes.
Change from
data: "{'mc_id':'"+someid+"','limit':'"+somelimit+"'}",
To
data: "mc_id="+someid+"&limit="+somelimit,
Follow the below steps:
1) Replace `data: "mc_id="+someid,` with `data: { mc_id: someid},`. (required)
2) Now you can get your data in PHP file like `$_POST['mc_id']` (optional). It is better to use `type: 'POST'`in your jQuery code.
So below is your whole code:
$.ajax({
data: { mc_id: someid},
url: "includes/getDataPrs.php",
type: 'POST',
dataType: "json",
async: false,
success: function(msg){
//some function here
}});
in getDataPrs.php
<?php
include_once 'db_connect.php';
include_once 'functions.php';
sec_session_start();
header('Content-Type: application/json');
$id = null;
$date = null;
$limit = 0;
if (isset($_POST['mc_id'])) {
$id = $_POST['mc_id'];
}
//some process here $data
echo json_encode($data);
?>
You try this
$.ajax({
type: "POST",
url: "includes/getDataPrs.php",
data: {'mc_id': someid, 'limit': somelimit}.done(function (response) {
//
});
});
Im submitting Data to a php file via AJAX using POST.
It worked fine with just submitting strings, but now I wanted to submit my JS Object with JSON and decode it on PHP side.
In the console I can see, that my data is submitted correctly but on PHP side json_decode returns NULL.
I've tried the following:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(this),
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['data'];
echo json_decode($_POST['data']);
echo var_dump(json_decode($_POST['data']));
And:
this.getAbsence = function()
{
alert(JSON.stringify(this));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: {'Absence' : JSON.stringify(this)},
success : function(data){
alert(data);
}
});
}
PHP:
echo $_POST['Absence'];
echo json_decode($_POST['Absence']);
echo var_dump(json_decode($_POST['Absence']));
The alert was just to check everything is alright...
And yea usual string were echoed correctly :-)
Where you went wrong in your code in the first code is that you must have used this:
var_dump(json_decode(file_get_contents("php://input"))); //and not $_POST['data']
Quoting from PHP Manual
php://input is a read-only stream that allows you to read raw data from the request body.
Since in your case, you are submitting a JSON in the body, you have to read it from this stream. Usual method of $_POST['field_name'] wont work, because the post body is not in an URLencoded format.
In the second part, you must have used this:
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify({'Absence' : JSON.stringify(this)}),
UPDATE:
When request has a content type application/json, PHP wont parse the request and give you the JSON object in $_POST, you must parse it yourself from the raw HTTP body. The JSON string is retrieved using file_get_contents("php://input");.
If you must get that using $_POSTyou would make it:
data: {"data":JSON.stringify({'Absence' : JSON.stringify(this)})},
And then in PHP do:
$json = json_decode($_POST['data']);
Single quotes are not valid for php's json_encode, use the double quotes for both field names and values.
To me, it looks like you should reformat your AJAX object. The url-property should only be the URL for the target php-file and any data that needs to be posted should be in the form of a query-string in the data-property.
The following should work as you expected:
this.getAbsence = function() {
var strJSONData = JSON.stringify(this);
alert(strJSONData);
jQuery.ajax({
type: 'POST',
contentType: 'application/json; charset=utf-8',
url: 'ajax/selectSingle.php',
data: 'm=getAbsence&Absence=' + strJSONData,
success: function(data) {
alert(data);
}
});
}
try this
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "ajax/selectSingle.php?m=getAbsence",
data: JSON.stringify(vThis),
success : function(data){
alert(data);
}
});
}
EDIT
I think we can also do this!
var vThis = this;
this.getAbsence = function()
{
alert(JSON.stringify(vThis));
jQuery.ajax({
type: "POST",
dataType: "json",
url: "ajax/selectSingle.php?m=getAbsence",
data: vThis,
success : function(data){
alert(data);
}
});
}
and in PHP
print_r($_POST);
On PHP side try this:
$sectionValue = htmlspecialchars($_POST['sectionValue'], ENT_QUOTES);
$dataToWrite = json_decode(html_entity_decode($sectionValue, ENT_QUOTES, "utf-8" ), true);
There is a nice JSON object in console.log, but can't seem to retrieve it in controller.
function checkOut(data) {
$.ajax({
url: 'index.php?route=sale/customer/checkout&token=<?php echo $token; ?>&customer_id=<?php echo $customer_id; ?>&products=' + data,
type: 'post',
dataType: 'html',
data: 'products=' + encodeURIComponent(data),
cache: false,
beforeSend: function() {
$('.success, .warning').remove();
$('#button-checkout').attr('disabled', true);
$('#checkout').before('<div class="attention"><img src="view/image/loading.gif" alt="" /> <?php echo $text_wait; ?></div>');
},
complete: function() {
$('#button-checkout').attr('disabled', false);
$('.attention').remove();
},
success: function(html) {
console.log(data);
$('#checkout').html(html);
}
});
}
Sending data via get only seems to send a string, [object Object].
Change the dataType to json and all the html in result page disappears.
Experimented with $.parseJSON(data);, which returns null value in console.log.
What's the method to retrieve the data object so it can be json_decode($data, TRUE)d and available as a php array?
Try This
$.ajax({
url: 'index.php?route=sale/customer/checkout&token=<?php echo $token; ?>&customer_id=<?php echo $customer_id; ?>',
type: 'post',
dataType: 'json',
data: {
products: data
},
success: function (data) {
alert(data);
}
});