No data response when sending ajax request to php - javascript

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

Related

Pass php array to Ajax variable

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

POST 400 error, ajax request

Why cant I save this, I get 400 (Bad Request),
and on headers response i get The CSRF token could not be verified.
$(document).ready(function() {
$("a#copylink").click(function (e) {
e.preventDefault();
var data = $('#campaign-form').serialize();
$.ajax(
{
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
data: data,
success: function(data){
alert(data);
}
}
)
});
});
on backend:
public function actionCampaignSave()
{
var_dump($_POST);
}
You can pass the [headers] parameter in your ajax call like this.
$.ajax({
url : 'campaignsave',
method : 'POST',,
headers : {
'X-CSRF-TOKEN' : $('input[name="token"]').val()
}
dataType : 'json',
data : data,
success : function(response) {
console.log(response);
}
});
Just make sure you've place {!! csrf_field() !!} on your [view] blade template to append the $(input[name="token"); html tag to get the token value to get the CSRF token as well. Hope this helps
Pass csrf token using headers property on ajax
$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
method: 'POST',
url: 'campaignsave',
headers: { 'X-CSRF-TOKEN': 'token' }
data: data,
success: function(data){
alert(data);
}
});
Try this it may help you
$.ajax({
type: "POST",
url: 'campaignsave',
data: {test : data},
success: function(data) {
alert(data);
}
});

JS array send to php is returning as empty [duplicate]

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

Retrieving objects from JSON using PHP

I need to send some data stored in IndexedDB to server for some back-end manipulation. The needed data is fetched to a variable payLoad in javascript using JSON.stringify().
payLoad = "[{"synch":0,"id":-1,"name":"Tester","email":"test#example.com","created":"2014-08-20T07:56:44.201Z"}]";
$.ajax({
type: "POST",
url: "process.php",
data: payLoad, // NOTE CHANGE HERE
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
alert(msg);
},
error: function(msg) {
alert('error');
}
});
Can I parse this JSON data to a PHP class?
This way, you're just sending JSON raw in the body. Try this:
$data = json_decode(file_get_contents('php://input'));
If, on the other hand, you send data with this:
data: { data: payLoad },
Then you can simply do
$data = json_decode($_POST['data']);

How to get the PHP var after Jquery $.ajax

I use $.ajax to send some data to testajax.phpenter code here where data are processing. Result of this proces is link. How to get access to this? I think about sessions or cookies. Set in session $test and get access in another files.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: console.log('success');
data: { json : jsonObj }
});
In testajax.php I have someting like this
echo "PDF: <a href=images/test.pdf>$dir.pdf</a>";
$test = "PDF: <a href=images/test.pdf>$dir.pdf</a>";
How to get the $test or output the echo after call $.ajax
You can use success' function to get request from PHP.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'html',
data: { json : jsonObj }
success: function(data) {
var request = data;
console.log(data);
$('#link_container').html(data);
}
});
Your console now holds PDF: <a href=images/test.pdf>($dir content).pdf</a>.
Also the variable request holds the same result that you can use anywhere in the script.
Result is appended to #link_container.
Use the success() method for display the result.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
success: function (data){ // <= define handler for manupulate the response
$('#result').html(data);
}
data: { json : jsonObj }
});
Use below code It may help you.
$.ajax({
url: 'testajax.php',
type: 'post',
dataType: 'json',
data: { json : jsonObj },
onSuccess: successFunc,
onFailure: failureFunc
});
function successFunc(response){
alert(response);
}
function failureFunc(response){
alert("Call is failed" );
alert(response);
}

Categories

Resources