Ive finally managed to get this array build and sent to my PHP function via ajax however, I dont seem to be able to decode it / var_dump produces nothing in the response panel on success.
My arrays:
var data = JSON.stringify({
newEmailForm: newEmailForm,
properties: properties
});
Which produces this:
{"newEmailForm":[["coda#knoppys.co.uk","sikjdhf","Youe message here"]],"properties":[["31466","asdasd","asdads"],["31440","asdasd","asdad"]]}
My ajax function which is posting over the following array.
jQuery(function(){
jQuery.ajax({
url: siteUrl,
type:'POST',
action: 'elegantSendEmail',
data:data,
dataType:'json',
success:function(result){
console.log(result); //This returns nothing, not even 0
}
});
});
My PHP function. If i simply echo hello world then it works.
add_action( 'wp_ajax_elegantSendEmail', 'elegantSendEmail' );
function elegantSendEmail() {
$array = json_decode($_POST('data'), true);
var_dump($array);
wp_die();
}
You're not posting the data as form-encoded, so it won't be in $_POST. It will be sitting in the input buffer.
$your_json = file_get_contents('php://input');
$your_array = json_decode($your_json, true);
If you want to access the sent data in you php code through $_POST('data') you would want to send it in the data key
jQuery.ajax({
url: siteUrl,
type:'POST',
action: 'elegantSendEmail',
data: { data: data },
dataType:'json',
success:function(result){
console.log(result); //This returns nothing, not even 0
}
});
Related
I need to pass a json object from JS to PHP, and it will pass, but the result is an empty array.
Ajax request in 'adopt.php':
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {'info': info},
success: function(data){
console.log(data);
}
});
ajax.php code:
if(isset($_POST['info'])){
$_SESSION['array'] = $_POST['info'];
}
back in adopt.php, later:
if(isset($_SESSION['array'])){
$arr = $_SESSION['array'];
echo "console.log('information: ' + $arr);";
}
in both of the console.logs, it returns an empty object. Does anybody know what could be causing this? (i've tried just passing the json without stringifying it, but it throws a jquery error whenever i do this.)
Try below code i think you miss return ajax response
adopt.php
<script>
var info = JSON.stringify(filteredArray);
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {info: info},
success: function(data){
console.log(data);
}
});
</script>
ajax.php
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(["result" => "success"]);
}
To get the response data from PHP, you need to echo your data to return it to the browser.
In your ajax.php:
if (isset($_POST['info'])) {
$_SESSION['array'] = $_POST['info'];
echo json_encode(['result' => $_SESSION['array']]);
}
Your ajax.php is not returning any data.To get data at the time of success you need to echo the data you want to display on success of your ajax.
These are my code:
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
$("#myModalLabel").html(data);
}
});
stay.preventDefault();
});
And the success data result below:
$result1 = "code is invalid";
$result2 = "promo unavailable";
How can I select these and retrieve it?
This is what I did below but now working.
$("#myModalLabel").html(data->result1);
JavaScript uses dot syntax for accessing object properties, so...
$("#myModalLabel").html(data.result1);
I'll also add that you want to make sure the page at promo/code_validate prints out a JSON response, as that is how data will become an object ($.ajax is intelligent about how to parse the server's response, see the link below). So your code_validate page might look something like this:
{
"result1": "code is invalid",
"result2": "promo unavailable"
}
http://api.jquery.com/jquery.ajax/
Do this
Function controller
function code_validate()
{
echo json_encode(array('result1'=>'Code is invalid',
'result2'=>'Promo not available');
}
Javascript
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
var mydata = JSON.parse(data);
console.log(mydata.result1);
console.log(mydata.result1);
}
});
stay.preventDefault();
});
You must return it as JSON.
Goodluck meyt
Vincent, add the dataType paramater to your ajax call, setting it to 'json'. Then just parse the response to convert it to an object so that you can access the variables easily, e.g.
in AJAX call:
dataType: "json"
in success function:
var obj = jquery.parseJSON(data);
console.log(obj);//echo the object to the console
console.log(obj.result1);//echo the result1 property only, for example
The simplest way to do what you want is create a php associative array of your values then json encode the array and echo the resulting string like this:
$response = ["result1"=>"code is invalid", "result2"=>"promo unavailable"];
echo json_encode($response);
Then on the client side, access them like this
$("#promo_form").submit(function(stay){
$.ajax ({
type: "post",
url: "<?=base_url()?>promo/code_validate",
data: $("#promo_form").serialize(),
success: function(data){
$("#modal-1").html(data.result1);
$("#modal-2").html(data.result2);
}
});
stay.preventDefault();
});
I am trying to receive and print json with this php code:
<?php
$data = json_decode(file_get_contents('php://input'), true);
print_r($data);
?>
I am not receiving or printing any data. But if i use this ajax:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script>
(function($){
function processForm( e ){
$.ajax({
url:'http://mydyndns:8010/has/input_parameters_startReg.php',
dataType: 'json',
type: 'POST',
contentType: 'application/json',
data: JSON.stringify({ DeviceID: 23, ForceReg: 0, StartTime: "10/06/2015 17:45"}),
success: function (data) {
},
error: function (e) {
alert(e.responseText);
},
});
e.preventDefault();
}
$('#my-form').submit( processForm );
})(jQuery);
it is working, and i get the posted data printed in my browser. How can i alter my php so the direct hitting from browser will give me the result the ajax gives?
Function parse_str will do the job in combination with $_SERVER['QUERY_STRING']
<?php
parse_str($_SERVER['QUERY_STRING'], $output);
$json = json_encode($output);
echo $json;
?>
I don't think you'll be able to fetch it using GET because php://input seems to only read POST data. If you want to be able to use the GET data, you can refer to the $_GET global:
print_r($_GET);
Note that you can also use $_POST in place of php://input, but here's a question/answer on here that talks about that some:
PHP "php://input" vs $_POST
EDIT: Oops, I see this was answered while I was taking my sweet time.
The Ajax function below sends data from a page to the same page where it is interpreted by PHP.
Using Firebug we can see that the data is sent, however it is not received by the PHP page. If we change it to a $.get function and $_GET the data in PHP then it works.
Why does it not work with $.post and $_POST
$.ajax({
type: "POST",
url: 'http://www.example.com/page-in-question',
data: obj,
success: function(data){ alert(data)},
dataType: 'json'
});
if there is a problem, it probably in your php page.
Try to browse the php page directly in the browser and check what is your output.
If you need some inputs from post just change it to the GET in order to debug
try this
var sname = $("#sname").val();
var lname = $("#lname").val();
var html = $.ajax({
type: "POST",
url: "ajax.class.php",
data: "sname=" + sname +"&lname="+ lname ,
async: false
}).responseText;
if(html)
{
alert(html);
return false;
}
else
{
alert(html);
return true;
}
alax.class.php
<php
echo $_REQUEST['sname'];
echo $_REQUEST['sname'];
?>
Ajax on same page will not work to show data via POST etc because, PHP has already run that's why you would typically use the external page to process your data and then use ajax to grab the response.
example
success: function(){
$('#responseDiv').text(data);
}
You are posting the data... Check if the target is returning some data or not.
if it returns some data then only you can see the data otherwise not.
add both success and error.. so that you can get what exactly
success: function( data,textStatus,jqXHR ){
console.log(data);//if it returns any data
console.log(textStatus);//or alert(textStatus);
}
error: function( jqXHR,textStatus,errorThrown ){
console.log("There is some error");
console.log(errorThrown);
}
I have the following data in a JS script:
$("#holdSave").live('click', function () {
var arr = {};
var cnt = 0;
$('#holdTable tbody tr').each(function () {
arr[cnt] = {
buyer: $(this).find('#tableBuyer').html(),
sku: $(this).find('#tableSku').html(),
isbn: $(this).find('#tableISBN').html(),
cost: $(this).find('#tableCost').val(),
csmt: $(this).find('#tableConsignment').val(),
hold: $(this).find('#tableHold').val()
};
cnt++;
}); //end of holdtable tbody function
console.log(arr);
$.ajax({
type: "POST",
url: "holdSave.php",
dataType: "json",
data: {
data: arr
},
success: function (data) {
} // end of success function
}); // end of ajax call
}); // end of holdSave event
I need to send this to a php file for updating the db and emailing that the update was done. My console.log(arr); shows the objects when I run it in firebug, but I can't get any of the information on the php side. Here is what I have for php code:
$data = $_POST['data'];
print_r($data); die;
At this point I am just trying to verify that there is info being sent over. My print_r($data); returns nothing.
Can anyone point me in the right direction please?
dataType: "json" means you are expecting to retrieve json data in your request not what you are sending.
If you want to send a json string to be retrieved by $_POST['data'] use
data: {data: JSON.stringify(arr)},
Use the json_encode() and json_decode() methods
Use the next way:
data = {key1: 'value1', key2: 'value2'};
$.post('holdSave.php', data, function(response) {
alert(response);
});
Note: haven't tested it, make sure to look for parse errors.