how do I get my ajax data into a php array? - php

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.

Related

Decode a multipart array from jQuery to PHP via ajax

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

JSON matching data and using data

I've only every used json to fetch data to use on pages or set as variables. But now I would like to search json for a matching name then fetch its views from the json
[{"id":1,"name":"Pale","description":"This is a description","url":"http://domain.com//1/pale","views":2212,"createdBy":{"name":"Bill Lumbergh","url":"http://domain.com"},"createdOn":"2013-10-24T22:54:34.183"},
Above is a little example and using the below code only console.logs the entire json which has about 20 id's
$.getJSON( "content.php", { name: 'Pale' } ,function(data){
console.log(data);
});
$.ajax({
url: 'content.php',
dataType: "json",
success: function (data) {
$.each(data, function(k,v){
if (v.name == theme){
console.log(v.views);
}
});
}
});
The Object you put in the code is the one you are passing to the Server, not receiving. {name:'Pale'} is being sent to the server. If you want the name from the JSON file, it's like:
$.getJSON('content.php', function(data){
console.log(data.name);
});
However, if my guess is correct try the following:
$.getJSON('content.php', function(data){
var ary = data.arrayThatHoldsYourObjects, store;
$.each(ary, function(i, v){
if(v.name === 'Pale'){
store = v.views;
}
});
});
store now holds v.views.

Send data from Javascript to PHP and use PHP's response as variable in JS

I have checked around, but can't seem to figure out how this is done.
I would like to send form data to PHP to have it processed and inserted into a database (this is working).
Then I would like to send a variable ($selected_moid) back from PHP to a JavaScript function (the same one if possible) so that it can be used again.
function submit_data() {
"use strict";
$.post('insert.php', $('#formName').formSerialize());
$.get('add_host.cgi?moid='.$selected_moid.');
}
Here is my latest attempt, but still getting errors:
PHP:
$get_moid = "
SELECT ID FROM nagios.view_all_monitored_objects
WHERE CoID='$company'
AND MoTypeID='$type'
AND MoName='$name'
AND DNS='$name.$selected_shortname.mon'
AND IP='$ip'
";
while($MonitoredObjectID = mysql_fetch_row($get_moid)){
//Sets MonitoredObjectID for added/edited device.
$Response = $MonitoredObjectID;
if ($logon_choice = '1') {
$Response = $Response'&'$logon_id;
$Response = $Response'&'$logon_pwd;
}
}
echo json_encode($response);
JS:
function submit_data(action, formName) {
"use strict";
$.ajax({
cache: false,
type: 'POST',
url: 'library/plugins/' + action + '.php',
data: $('#' + formName).serialize(),
success: function (response) {
// PROCESS DATA HERE
var resp = $.parseJSON(response);
$.get('/nagios/cgi-bin/add_host.cgi', {moid: resp });
alert('success!');
},
error: function (response) {
//PROCESS HERE FOR FAILURE
alert('failure 'response);
}
});
}
I am going out on a limb on this since your question is not 100% clear. First of all, Javascript AJAX calls are asynchronous, meaning both the $.get and $.post will be call almost simultaneously.
If you are trying to get the response from one and using it in a second call, then you need to nest them in the success function. Since you are using jQuery, take a look at their API to see the arguments your AJAX call can handle (http://api.jquery.com/jQuery.post/)
$.post('insert.php', $('#formName').formSerialize(),function(data){
$.get('add_host.cgi?moid='+data);
});
In your PHP script, after you have updated the database and everything, just echo the data want. Javascript will take the text and put it in the data variable in the success function.
You need to use a callback function to get the returned value.
function submit_data(action, formName) {
"use strict";
$.post('insert.php', $('#' + formName).formSerialize(), function (selected_moid) {
$.get('add_host.cgi', {moid: selected_moid });
});
}
$("ID OF THE SUBMIT BUTTON").click(function() {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data: $("ID HERE OF THE FORM").serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
return false; //This stops the Button from Actually Preforming
});
Now for the Php
<?php
start_session(); <-- This will make it share the same Session Princables
//error check and soforth use $_POST[] to get everything
$Response = array('success'=>true, 'VAR'=>'DATA'); <--- Success
$Response = array('success'=>false, 'VAR'=>'DATA'); <--- fails
echo json_encode($Response);
?>
I forgot to Mention, this is using JavaScript/jQuery, and ajax to do this.
Example of this as a Function
Var Form_Data = THIS IS THE DATA OF THE FORM;
function YOUR FUNCTION HERE(VARS HERE) {
$.ajax({
cache: false,
type: 'POST',
url: 'FILE IN HERE FOR PROCESSING',
data:Form_Data.serialize(),
success: function(data) {
// PROCESS DATA HERE
},
error: function(data) {
//PROCESS HERE FOR FAILURE
}
});
}
Now you could use this as the Button Click which would also function :3

Sending back multiple results from PHP via AJAX

i have setup some ajax, which i am just testing now, pretty much the idea behind it is to send some data from dropdown boxes to a php script, do some calculations and then return the result, it does it well and returns the result, but now rather than just sending back one result and outputting that, i want to send back multiple results and output them, i am able to send multiple data to the php script, so i am sure i can send multiple back.
Anyway it only sends the first result back and not the rest.
Here is the AJAX
<script>
$("document").ready(function (){
$(".add_extension").change(function(){
var m = document.getElementById('meter_square');
var meter_square = m.options[m.selectedIndex].value;
var s = document.getElementById('story_height');
var story_height = s.options[s.selectedIndex].value;
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
statusCode: {
200: function (result, result2)
{
$("#expected_gain").html(result.value);
$("#house_price").html(result2.value2);
}
}
});
})
});
</script>
And here is the php script
<?php
$meter_square = $_GET["meter_square"];
$story_height = $_GET["story_height"];
$result = $meter_square + $story_height;
$result2 = $meter_square * $story_height;
echo json_encode(array("value" => $result, "value2" => $result2));
?>
You can see that i have already tried to give it a go from what i thought might work, if you need any other code or want me to remove the code i added which doesn't work, then let me know.
Thanks for all and any help
You're only going to receive one response object:
function (response) {
$("#expected_gain").html(response.value);
$("#house_price").html(response.value2);
}
Try this. Think it will help. No need to use status codes if u gonna use only success case
$.ajax({
type: "GET",
url: "script.php",
data: { meter_square: meter_square, story_height: story_height },
dataType: "json",
success: function(data){
$("#expected_gain").html(data.value);
$("#house_price").html(data.value2);
}
});

Retrieve JSON Data with AJAX

Im trying to retrieve some data from JSON object which holds location information such as streetname, postcode etc. But nothing is being retrieved when i try and put it in my div. Can anybody see where im going wrong with this?
This is my ajax code to request and retrieve the data
var criterion = document.getElementById("address").value;
$.ajax({
url: 'process.php',
type: 'GET',
data: 'address='+ criterion,
success: function(data)
{
$('#txtHint').html(data);
$.each(data, function(i,value)
{
var str = "Postcode: ";
str += value.postcode;
$('#txtHint').html(str);
});
//alert("Postcode: " + data.postcode);
},
error: function(e)
{
//called when there is an error
console.log(e.message);
alert("error");
}
});
When this is run in the broswer is just says "Postcode: undefined".
This is the php code to select the data from the database.
$sql="SELECT * FROM carparktest WHERE postcode LIKE '".$search."%'";
$result = mysql_query($sql);
while($r = mysql_fetch_assoc($result)) $rows[] = $r;
echo json_encode($rows), "\n"; //Puts each row onto a new line in the json data
You are missing the data type:
$.ajax({
dataType: 'json'
})
You can use also the $.getJSON
EDIT: example of JSON
$.getJSON('process.php', { address: criterion } function(data) {
//do what you need with the data
alert(data);
}).error(function() { alert("error"); });
Just look at what your code is doing.
First, put the data directly into the #txtHint box.
Then, for each data element, create the string "Postcode: "+value.postcode (without even checking if value.postcode exists - it probably doesn't) and overwrite the html in #txtHint with it.
End result: the script is doing exactly what you told it to do.
Remove that loop thing, and see what you get.
Does your JSON data represent multiple rows containing the same object structure? Please alert the data object in your success function and post it so we can help you debug it.
Use the
dataType: 'json'
param in your ajax call
or use $.getJSON() Which will automatically convert JSON data into a JS object.
You can also convert the JSON response into JS object yourself using $.parseJSON() inside success callback like this
data = $.parseJSON(data);
This works for me on your site:
function showCarPark(){
var criterion = $('#address').val();
// Assuming this does something, it's yours ;)
codeAddress(criterion);
$.ajax({
url: 'process.php',
type: 'GET',
dataType: 'json',
data: {
address: criterion
},
success: function(data)
{
$("#txtHint").html("");
$.each(data, function(k,v)
{
$("#txtHint").append("Postcode: " + v.postcode + "<br/>");
});
},
error: function(e)
{
alert(e.message);
}
});
}

Categories