I have this ajax works fine :
$.ajax({
url: "../../../controller/ctrl.test.php",
success:function(expirytime){
alert(expirytime);
}
});
but when I need to send data to server and add this lines, then it won't alert the expirytime again :
$.ajax({
url: "../../../controller/ctrl.test.php",
type: 'POST',
contentType:'application/json',
data: JSON.stringify(data),
dataType:'json',
success:function(expirytime){
alert(expirytime);
}
});
please note that data is json data. and I have it on above those codes. so, it's not empty. I just wondering why by adding POST mechanism into my first ajax cause alert(expirytime); stop working?
what's wrong with my code? thank you
update : for this test purpose, there's nothing in PHP file, but just echo-ing date and time
<?php
$date = '2016/04/30 00:00:00';
echo $date;
?>
Since you have dataType: 'json', jQuery expects the response from PHP to be valid JSON. But
echo $date;
is not returning valid JSON. When jQuery calls JSON.parse() on that response it gets an error, so the success function is not called.
Change that line to:
echo json_encode($date);
and it should work. Or change dataType: 'json' to dataType: 'text'.
Try This
$.ajax({
url: "../../../controller/ctrl.test.php",
type: 'POST',
data: { JSON.stringify(data) },
dataType: 'json',
success:function(expirytime){
alert(expirytime);
}
});
Related
The output consists of the complete JSON, which is:
{reply:"Login success"}
The expected output is only the value for the key 'reply' ,
Login success
The required code:
HTML
<div id="resp" style="color:red;"></div>
JS AJAX JQUERY
$.ajax({
url: 'tt.php',
method: 'POST',
data: {'pass': pass , 'uname':uname},
success: function(data) {
document.getElementById("resp").innerHTML = data;
}
});
PHP
$data['reply'] = "Login Success";
echo json_encode($data);
Solutions tried to print the necessary data
data[0]
data[1]
data[reply]
data.reply
data["reply"]
The PHP code you show us is not outputting what you say your expected output should be but, you can tell the AJAX call to expect JSON to be returned by adding dataType: 'JSON', to the properties of the call.
Then you can address the reply as data.reply
$.ajax({
url: 'tt.php',
method: 'POST',
dataType: 'JSON', // added this line
data: {'pass': pass , 'uname':uname},
success: function(data) {
// then you can address the reply like this
document.getElementById("resp").innerHTML = data.reply;
}
});
I have object in javascript and I need send this object to php using ajax.
I can "just send" this object, but my problem is that I need send object value types exactly as they are and not everything as string: meaning NULL as NULL, boolean values as boolean and so on...
Trying this:
var js_object= <?php echo json_encode( array("a"=>NULL, "b"=>TRUE, "C"=>1.1) ); ?>;
$.ajax({
type: "POST",
url: "some.php",
dataType: "json",
data: JSON.stringify(js_object),
contentType: "application/json; charset=UTF-8",
success: function(msg){
}
});
but this does not sends data to server at all. and not gives any error also. where I am wrong ?
There is nothing wrong with your code.
I've just add a snippet with post query to httpbin.org:
$.ajax({
type: 'POST',
url: '//httpbin.org/post',
data: JSON.stringify({name: 'test', 'null': null, 'true': true}),
success: onSuccess,
error: onError,
dataType: 'json',
contentType: 'application/json; charset=UTF-8'
});
function onSuccess(data){
// data is parsed json response
console.log('Request copy:', data.json);
console.log('Full response', data);
}
function onError(xhr) {
console.log(xhr.status, xhr.responseText);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
Server side sample script:
<?php
$json = file_get_contents('php://input');
$data = json_decode($json, true);
header('Content-type: application/json');
echo json_encode($data);
Goal: Serialize data, send them in HTTP POST request using AJAX, proceed data in PHP (and answer)
Problem: PHP $_POST variable seems to be empty
JS/AJAX
var postData = [cmd, data];
alert(postData = JSON.stringify(postData));
$.ajax({
url: "./backendTag.php",
type: "post",
data: postData,
dataType: 'json',
success: function (response) {
alert(response); // Empty
//logToServerConsole(JSON.parse(response));
},
error: function(jqXHR, textStatus, errorThrown) {
logToServerConsole("E3"); // Communication Error
console.log(textStatus, errorThrown);
}
});
PHP
<?php echo json_encode($_POST);
The reason for the same is probably because you are not posting properly in javascript. Before i add the codes, let me add a couple of tips on how to debug in these situations.
First is, you check if the request is properly formed. Inspect the network in browser dev tools.
Second method could be to use var_dump on $_POST to list out all the post parameters and check if they have been recieved in PHP
Now as far as the code goes
here is the javascript
$.ajax({
method: "POST",
url: "url.php",
data: { name: "John Doe", age: "19" }
}).done(function( msg ) {
alert(msg);
});
and in php you can simply check using
<?php
print $_POST["name"];
?>
which would work perfectly. Notice how the data in javascript is a list, while from what you wrote seems to be json string
Apparently we can't pass an array directly after serializing him. The following code resolved the problem. (Split array)
data = JSON.stringify(data);
var JSONdata = {"cmd" : cmd, "data" : data};
$.ajax({
url: "./backendTag.php",
type: "post",
data: JSONata,
dataType: 'json',
/* Handlers hidden*/
});
JSON content won't be parsed to the $_POST globals. If you want to reach them, try to get from php://input with:
file_get_contents('php://input')
And I suggest giving the content-type during the ajax request:
contentType: 'application/json',
If it's not working, try to set the data as a string, with JSON.Stringify, like the following:
data: JSON.stringify(postData)
I have a function that includes an AJAX to send a JSON object retrieved from localStorage. For some reason, in my PHP script, it never shows anything in the $_POST variable, despite me being pretty sure the AJAX call goes through successfully. My code is as follows:
The javascript:
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
dataType: 'json',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
The php script:
if(isset($_POST['answers'])){
$obj = json_decode($_POST['answers']);
print_r ($obj);
}
Any help as to why this isn't working would be greatly appreciated. Thank you.
I've tried all of the options given so far, and nothing seems to be working. I'm at a total loss.
For those asking, the finalResult variable is structured as:
[{"answer":0,"elapsed_time":1378,"stimulus_id":"8","task_id":1},{"answer":1,"elapsed_time":157,"stimulus_id":"2","task_id":1},{"answer":1,"elapsed_time":169,"stimulus_id":"1","task_id":1}, etc....
dataType: 'json' requires that what you output in PHP (data accepted in success section) must be valid json.
So valid json will be in PHP:
if(isset($_POST['answers'])){
echo $_POST['answers'];
}
No need to decode it, it is json string already. No var_dump, no print_r
I would remove the dataType property in your Ajax request and modify the structure of your data :
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: 'answers='&finalResults,
success: function(data){
console.log(data);
console.log('Success');
}
})
And in a second time I would test what I receive on PHP side :
if(isset($_POST['answers'])){
var_dump(json_encode($_POST['answers']));
}
Remove dataType: 'json', if you sending with JSON.stringify
JS.
function processResults(){
var finalResults = localStorage.getItem('results');
finalResults = JSON.stringify(finalResults);
$.ajax({
type: 'POST',
url: '../DB_add.php',
data: {'answers': finalResults},
success: function(data){
console.log(data);
console.log('Success');
}
})
}
PHP CODE:
if (!empty($_REQUEST['answers'])) {
$answers = json_decode(stripslashes($request['answers']));
var_dump($answers);
}
I want to run the first ajax call when it has completed run the function "saveToFile()" and after that has been completed run the second ajax call. Doesn't seem to work as coded. I'm fairly new to ajax so am struggling a little with this one.
// save composition to database
$.ajax({
type: "POST",
url: "_inc/save_to_db.php",
data: {jsonStr: canvasStr},
success: function(data) {
// this saves the comp to the _comps folder on the server as a jpeg file (firth.js)
saveToFile();
$.ajax({
type: "POST".
url: "_inc/generate_thumbnail.php",
data: {imgFile: "<?php echo $_SESSION['UserID'] ?>_<?php echo $_SESSION['CompID'] ?>.jpg"},
});
}
});
Works for me: http://jsbin.com/upujur/2/edit
The problem might be with the dot instead of comma in this line:
type: "POST".
Are you using a JavaScript console like FireBug or Developer Tools to debug your program?
You could make the saveToFile function take as parameter a callback which will be executed once the AJAX call it performs is finished. For example:
$.ajax({
type: "POST",
url: "_inc/save_to_db.php",
data: {jsonStr: canvasStr},
success: function(data) {
// this saves the comp to the _comps folder on the server as a jpeg file (firth.js)
saveToFile(function(result) {
$.ajax({
type: "POST",
url: "_inc/generate_thumbnail.php",
data: {imgFile: "<?php echo $_SESSION['UserID'] ?>_<?php echo $_SESSION['CompID'] ?>.jpg"},
});
});
}
});
and your saveToFile function may now look like that:
function saveToFile(successCallback) {
$.ajax({
url: ...,
type: ...,
data: ...,
success: successCallback
});
}