I have a simple php file that decode my json string, passed with ajax, and stamp the result, but I can't keep the $_POST variable, why???
I try to inspect with fireBug and I can see that the POST request is sent correctly, when the php script is called, he respond Noooooooob to me, it seem any POST variable is set.
All I want is to have my array =)
JSON String generated by JSON.stringify:
[
{
"id":21,
"children":[
{
"id":196
},
{
"id":195
},
{
"id":49
},
{
"id":194
}
]
},
{
"id":29,
"children":[
{
"id":184
},
{
"id":152
}
]
},
...
]
JavaScript
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
save_categories.php
<?php
if(isset($_POST['categories'])) {
$json = $_POST['categories'];
var_dump(json_decode($json, true));
} else {
echo "Noooooooob";
}
?>
Your code works if you remove dataType: 'json', just tested it.
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
data: {'categories': tmp},
success: function(msg) {
alert(msg);
}
});
});
it's work for me you can try this.
JavaScript
$('#save').click(function() {
$.ajax({
type: 'POST',
contentType: 'application/json',
url: 'save_categories.php',
dataType: 'json',
data: JSON.stringify({'categories': $('.dd').nestable('serialize')}),
success: function(msg) {
alert(msg);
}
});
});
you need to write the below code on save_categories.php
$_POST is pre-populated with form data.
To get JSON data (or any raw input), use php://input.
$json = json_decode(file_get_contents("php://input"));
$categories = $json->categories;
dataType is json, so jQuery posts this:
{"categories":"[{\"id\":21,\"children\":[{\"id\":196},{\"id\":195},{\"id\":49},{\"id\":194}]},{\"id\":29,\"children\":[{\"id\":184},{\"id\":152}]},...]"}
This is not standard urlencoded, so $_POST is empty.
You can set data to your complex structure, and jQuery will correctly encode it:
$('#save').click(function() {
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: $('.dd').nestable('serialize'),
success: function(msg) {
alert(msg);
}
});
});
And in php: $categories = json_decode(file_get_contents('php://stdin'));
Try this:
$('#save').click(function() {
var tmp = JSON.stringify($('.dd').nestable('serialize'));
// tmp value: [{"id":21,"children":[{"id":196},{"id":195},{"id":49},{"id":194}]},{"id":29,"children":[{"id":184},{"id":152}]},...]
$.ajax({
type: 'POST',
url: 'save_categories.php',
dataType: 'json',
data: 'categories=' + encodeURIComponent(tmp),
success: function(msg) {
alert(msg);
}
});
});
I changed just this line:
data: 'categories=' + encodeURIComponent(tmp),
because thats the way, how you have to write data there. I tested it, its working...
Related
Here is the partial code from the remove PHP file:
if($action == 'trackings_get') {
$result = $trackings->get(getCourierSlugByID($GLOBALS['tracking_id']), $GLOBALS['tracking_id']);
$result_history = $result['data']['tracking']['checkpoints'];
echo json_encode($result_history);
// debugging
//pretty_print($result_history);
}
Here is the JS from the remote site i am trying to call the data for:
$.ajax({
url: '/login/tracking.php',
type: 'POST',
dataType: "json",
data: {
action: action,
tracking_id: tracking_id
},
success: function(json){
//debug
alert(JSON.stringify(json));
}
});
try this
function test(){
$.ajax({
url: 'url',
type: 'POST',
dataType: "json",
data: {
action: action,
tracking_id: tracking_id
},
success: function(json){
}
});
}
i try this code in inspect element in this page https://tracking.ambientlounge.com/
function test(){
$.ajax({
url: 'your url',
type: 'POST',
dataType: "json",
data: {
action: "action",
tracking_id: "tracking_id"
},
success: function(json){
//debug
console.log(json);
}
});
}
result is array . dont need JSON.stringify .
I Am trying to send value from ajax to php and retrieve it just to test that everything is work, when i click in a button to test i got error and alert('Failed') Appears , how can i fix it in order to get success? thanks
Ajax :
var a = "test";
$.ajax({
url: "search.php",
dataType: "json",
data: a ,
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
})
PHP :
<?php
$pictures = "img1";
echo json_encode($pictures);
?>
I refined your code slightly and it works.
var a = "test";
$.ajax({
type: 'POST',
url: 'search.php',
data: 'a=' + a,
dataType: 'json',
cache: false,
success: function (result) {
alert('Successful');
},
error: function (result) {
alert('Failed');
}
});
If you're requesting a JSON, use the $.getJSON from jQuery, it's aready parse the JSON into a JSON object for you.
Seems that you're not return an actual JSON from server, maybe this is what is causing the error.
If you're seeing the 'Failed' message probably the problem is a 500 error which is a server error.
Try this code above.
Javascript:
var a = "test";
$.getJSON("search.php", {
a: a
}, function (json) {
console.log(json);
});
PHP:
<?php
$pictures = ["img1"];
echo json_encode($pictures);
The only way to this not work, is if you have a huge mistake on you webserver configuration.
Your ajax is wrong, it should be:
var a = "test";
$.ajax({
type: "POST",
url: "search.php",
dataType: "json",
data: {a:a},
success: function(data) {
alert('Successfully');
},
error: function(data) {
alert('Failed');
}
});
I have written a php script:
cch.php:
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
json_encode($array);
$stmtcheck->close();
And jquery for submitting form is
recover.php:
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function()
{
}
});
});
The script is returning more than one variable and the returned data should be in JSON format.
How do I read the data in jQuery?
$("#formUnlock").submit(function(e)
{
e.preventDefault();
$.ajax(
{
url: '../scripts/cch.php',
method: 'POST',
data: $(#formUnlock).serialize(),
dataType: 'JSON',
success: function(data) //parameter missing
{
var json = $.parseJSON(data);
console.log(json);
//in console you will get the result response
}
});
});
Hello your php code should echo the JSON output like this:
<?php
$stmtcheck = $mysqli->prepare("SELECT id,email,location FROM members WHERE email=? AND unlock_code=?");
$stmtcheck->bind_param("si", $_SESSION['unlockemail'], $_POST['code']);
$stmtcheck->execute();
$stmtcheck->bind_result($id,$email,$location);
$stmtcheck->fetch();
$array=array($id,$email,$location);
$stmtcheck->close();
echo json_encode($array);
?>
Now, in your javascript, you can use JSON.parse method to get the JSON.
Also, specifying your response type as JSON will automatically return a JSON object.
$("#formUnlock").submit(function (e) {
e.preventDefault();
$.ajax({
url: '../scripts/cch.php',
method: 'POST',
data: $('#formUnlock').serialize(),
dataType: 'JSON',
success: function (json_string) {
var res = JSON.parse(json_string);
console.log(res);//This should output your JSON in console..
}
});
});
i want to post an array from java script to php by ajax. But i don't know how do that, especially send it to php function like controller class. Correct me if i'm wrong, this is my java script source, as a function to send an array :
<script>
function send(){
var obj = JSON.stringify(array);
window.location.href = "post.php?q=" + obj;
}
</script>
i was try, but still fail. really need help..
As described in the JQuery API documentation, you can use
var rootPath="http://example.com/"
var jsonData = $.toJSON({ q: array });
var urlWS = rootPath + "post.php";
$.ajax({
url: urlWS,
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: jsonData,
success: function(result) {
// do something here with returned result
}
});
var array= [];
array[0] = 'hi';
array[1] = 'hello';
$.ajax({
url: 'http://something.com/post.php',
data: {array: array},
type: 'POST'
});
try like this,
var data_to_send = $.serialize(array);
$.ajax({
type: "POST",
url: 'post.php',
data: data_to_send,
success: function(msg){
}
});
or
you can pass as json like below,
$.ajax({
type: "POST",
url: 'post.php',
dataType: "json",
data: {result:JSON.stringify(array)},
success: function(msg){
}
});
var arr = <?php echo json_encode($postdata); ?>;
ajax: {
url:"post.php"
type: "POST",
data: {dataarr: arr},
complete: function (jqXHR, textStatus) {
}
You can try this .this will work
example
ajax code:
$.ajax({
url: 'save.php',
data: {data: yourdata},
type: 'POST',
dataType: 'json', // you will get return json data
success:function(result){
// to do result from php file
}
});
PHP Code:
$data['something'] = "value";
echo json_encode($data);
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);
}