Parse an Array of Javascript Objects using JSON and AJAX - javascript

I have an array of Javascript objects, which I convert to a string using JSON.stringify() before processing with AJAX.
On the server side, all I am trying to do is verify that the proper $_POST["flavors"] variable is set, and output it's contents. I have verified (via a simple conditional) that the $_POST["flavors"] is being set, but I don't know how to modify the ajax call (or the PHP) to properly output it's contents.
I have read on here that I (may) need to set the dataType for the $.AJAX call and/or set the header in my PHP script, but I wasn't sure if setting the header would be applicable since it is inside my functions.php file. *
(Array function)
flavors = [];
function wholesaleAJAX() {
var sizeSelect = $('form#wholesale-size-form input:checked');
if (sizeSelect.val() === 'regularBag') {
$('select[name="wholesale-flavors-regular"] option:selected').each(function() {
name = $(this).text();
qty = $(this).closest('.row').find('div.large-3 select[name="wholesale-flavors-regular-count"] option:selected').text();
flavors.push(new FlavorSelects(name, qty));
});
} else if (sizeSelect.val() === 'largeBag') {
$('select[name="wholesale-flavors-large"] option:selected').each(function() {
name = $(this).text();
qty = $(this).closest('.row').find('div.large-3 select[name="wholesale-flavors-large-count"] option:selected').text();
flavors.push(new FlavorSelects(name, qty));
});
}
(Stringify the array and process AJAX)
stringArray = JSON.stringify(flavors);
$.ajax({
type:"POST",
url: "/wp-admin/admin-ajax.php",
data: {
action: "returnHash",
flavors: stringArray
},
success:function(data){
$("#ajax").html(data);
}
});
(PHP for processing AJAX in functions.php)
function returnHash() {
if (isset($_POST["flavors"])) {
$flavors = json_decode($_POST["flavors"]);
print_r($flavors);
} else {
echo 'Not Set';
}
die();
}
add_action('wp_ajax_returnHash', 'returnHash');
add_action('wp_ajax_nopriv_returnHash', 'returnHash');

Related

JSON array to and from MySql. Saving and Looping

<?
$cl = $row["saved_json_string_column"];
?>
expecting this output from the db query to create a new array
//cl = '[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]';
cl = '<? echo $cl;?>';
// I would like to start with the saved 'cl' array and push new items to it.
skptoQarry = new Array();
//javascript function loop (not shown) generates vars and pushes to new array.
thisItem_eid = 1;
yes_no_is_this = 'No';
SkipToTartgetEID = 5;
var skptoQarry_temp = {
"ifeid" : thisItem_eid,
"ans" : yes_no_is_this,
"type" : "SkipTo",
"target" : SkipToTartgetEID
};
skptoQarry.push(skptoQarry_temp);
cl = JSON.stringify(skptoQarry); //for ajax post to php for saving
//this is what is in saved the DB via ajax post
[{"ifeid":1,"ans":"Yes","type":"SkipTo","target":"2"},{"ifeid":2,"ans":"Yes","type":"SkipTo","target":"5"}]
//...but when PHP echos it out only this comes out: cl = "[,]"
// I think i'm saving it wrong or echoing the column data the wrong way.
//read text from mysql and append where needed.
cl = $.parseJSON(cl);
jQuery.each(cl, function (i) {
jQuery.each(this, function (key, value) {
if (key == "ifeid") {
$('div').append('if this id: '+value+'<br>');
} else if (key == "ans") {
$('div').append('is: '+value+'<br>');
} else if (key == "type") {
$('div').append('then: '+value+'<br>');
} else if (key == "target") {
$('div').append('this id: '+value+'<br><br>');
}
});
});
function saveit(){
saved_logic_dialog = JSON.stringify(skptoQarry);
var posturl = "myurl?event=save&saved_logic_dialog="+saved_logic_dialog;
jQuery.ajax({
traditional: true,
type: "POST",
url: posturl,
success: function(data) {
//messages and stuff
}
});
}
//php
$loadvfsql = "SELECT `saved_logic_dialog` FROM `questions` WHERE `id` = '{$id}' ORDER BY `questions`.`question_order` ASC";
$loadv_result=mysql_query($loadvfsql);
while($rows=mysql_fetch_array($loadv_result)){
$clc = $rows['current_logic_cont'];
$cl = $rows['saved_logic_dialog'];
//more stuff
}
This will ensure your array of objects is properly encoded - jQuery will not encode the URL for you.
var posturl = "myurl?event=save&saved_logic_dialog=" + encodeURIComponent(saved_logic_dialog);
When saving to DB - check for properly escaping the value (as it will certainly contain quotes);
When echoing the value back into HTML - use htmlspecialchars($cl) to properly escape the symbols which might have special meaning in HTML.
Before using the value in JavaScript - use JSON.parse(cl) to convert from String into Array.

Getting Variables in PHP by JavaScript

I'm adding a new record in my MySql DB with javascript and I have to elaborate this function in PHP.
$(document).on('submit', '#product_form', function(event){
event.preventDefault();
//btn_action="add_pricelvl"; //Set variable to call the add new item
var valdata = $(this).serialize(); //Array with field value
var tax = $('#item_tax').val(); //checkbox tax
var taxvalue = $('#item_taxvalue').val(); //inputbox tax
var tabledets = it_det //Read the detail table
.rows()
.data();
var arr1=[];//Declare the array
var i=0;
//Put the datatable(item_details) rows in the array
for (i=0; i<tabledets.length; i++){
arr1[i]=tabledets.rows(i).data();
}
//call ajax function and send variable to php file.
$.ajax({
processData: false,
url:'item_action.php',
method:"POST",
data:{
//btn_action:btn_action,
valdata:valdata,
tax:tax,
taxvalue:taxvalue,
arr1:arr1
},
success : function(data)
{
....
}
error : function () {
....
}
})
});
<?php
if ($_POST['btn_action']=='add_pricelvl'){
$query="....."
//Getting variables by JavaScript
}
?>
I can't get any variable in my PHP file... how is that possible?
Trying to check any $_POST[variable] in the PHP File they are NULL... why?
Try removing processData: false,. That command is telling jQuery to not turn the object into a query string. If you want to use $_POST[] in your script, it will expect it to be sent over as a query string.
http://api.jquery.com/jQuery.ajax/
processData (default: true)
Type: Boolean
By default, data passed in to the data option as an object (technically, anything other than a string) will be processed and transformed into a query string, fitting to the default content-type "application/x-www-form-urlencoded". If you want to send a DOMDocument, or other non-processed data, set this option to false.
To get the body from a POST call you should use something like this
$json = file_get_contents('php://input');
$json = urldecode($json);
$obj = json_decode($json, true);
Then you can manipulate $obj variable as a regular php array.

Sending function sent data to php file by ajax

I am trying to send data to a database.php file by ajax. My Index file has a form which will collect a 4 digit input then sends to a js function which sends the data to my db file. At the moment the Db file is being called because I get a result in the console but the 4 digit key is not being sent. I expect I have done something wrong with the ajax script.
Any help please
function addCode(key) {
var code = document.forms[0].code;
if (code.value.length < 4) {
code.value = code.value + key;
}
if (code.value.length == 4) {
document.getElementById("message").style.display = "block";
setTimeout(alarm, 1000, code.value);
}
}
function alarm(code) {
$.ajax({
method: "POST",
url: "alarm.php",
data: code,
cache: false,
success: function(responseText) {
console.log(responseText) // show returned text in console
}
})
emptyCode();
}
function emptyCode() {
document.forms[0].code.value = "";
}
The issue is because you're just sending the value by itself with no key. To fix this you could provide data with an object that will be form encoded when the request is sent:
data: { code: code },
Then in your PHP code you can retrieve the posted value by its key:
$code = $_POST['code'];

jQuery AJAX send search criteria to PHP return JSON

I am trying to send a group of variables to a PHP script via AJAX.
Typically, this is what I'd do:
$('.submitSearch').on('click', function()
{
var rep = $('#rep').val();
var num = $('#num').val();
var uid = $('#uid').val();
// and so on
// then I could send each variable to a PHP script
$.post('api/summary.php', {rep: rep, num: num, // and so...}, function(data)
{
console.log(data);
});
});
That's how I'd normally do it.
But now, I am trying send all of the parameters in a single variable I calling searchCriteria, as follows:
$('.submitSearch').on('click', function()
{
var searchCriteria =
{
rep: $('#rep').val(),
num: $('#num').val(),
uid: $('#uid').val(),
// and so on...
}
// then send them to the php script
$.post('api/summary.php', searchCriteria, function(data)
{
console.log(data);
});
});
Then, in the PHP script, retrieve all of the parameters from the variable for processing:
<?php
if($_POST['searchCriteria'] == true)
{
// get the parameters
// build the query
// return JSON
}
?>
My question is: How do I get all of the parameters out of $_POST['searchCriteria'] in the PHP script?
Try wrapping it in a bigger object like this :
Javascript :
$('.submitSearch').on('click', function()
{
var searchCriteria =
{
rep: $('#rep').val(),
num: $('#num').val(),
uid: $('#uid').val(),
// and so on...
}
// then send them to the php script
$.post('api/summary.php', {searchCriteria : searchCriteria }, function(data)
{
console.log(data);
});
});
PHP :
<?php
if($_POST['searchCriteria'] == true)
{
$searchCriteria = json_decode($_POST['searchCriteria']);
// Now you can for each loop throught it for example
foreach($searchCriteria as $key => $value) {
// Do something
}
}
?>
If you want everything in a single $_POST parameter, you need to wrap in another object:
$.post('api/summary.php', {searchCriteria : searchCriteria }, function(data) {
...
});
In the PHP, you would then access them as nested arrays.
$sc = $_POST['searchCriteria']
$rep = $sc['rep'];
$num = $sc['num'];
$uid = $sc['uid'];
I'm not sure what you expect to gain by adding this extra level of wrapping.

fetch json object containing 3 arrays with ajax call and pass arrays to javascript

I have a page that creates the following output:
<script>
var JSONObject = { "groups":['1210103','1210103','1210103','1210405'],
"prices":['279,00','399,00','628,00','129,00'],
"titles":['','','','']
};
</script>
This page is called by an ajax call:
$.ajax({url:plink,success: function(result) { }
I now need to recieve the json arrays and pass them to ordinary javascript arrays.
How do I do that?
I have tried with:
result = jQuery.parseJSON(data);
mygroups = result.groups;
myprices = result.prices;
mylabels = result.titles;
Change your page so that it just produces JSON:
{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}
Note that in JSON, you must use ", not ', for quoting strings.
Have it return a Content-Type header of application/json. If for some reason you can't set the correct Content-Type header on the response, you can force jQuery to treat the response as JSON by adding dataType: 'json' to your ajax call, but it's best to use the correct content-Type.
Then in your ajax call's success callback, result will already be a deserialized object with three properties (groups, prices, titles), which will be JavaScript arrays you can work with.
Live Example | Source
You've said in the comments below that the page is a full HTML page with the embedded script tag and you have no control over it other than the contents of the script tag, because of the CMS you're using.
I strongly suggest moving to a more flexible CMS.
Until/unless you can do that, you can simply receive the page as text and then extract the JSON. Change your script tag to something like this:
<script>
var JSONObject = /*XXX_JSONSTART_XXX*/{"groups":["1210103","1210103","1210103","1210405"],
"prices":["279,00","399,00","628,00","129,00"],
"titles":["","","",""]
}/*XXX_JSONEND_XXX*/;
</script>
Note the markers. Then you can extract the JSON between the markers, and use $.parseJSON on it. Example:
(function($) {
$.ajax({
url: "http://jsbin.com/ecolok/1",
dataType: "text",
success: function(result) {
var startMarker = "/*XXX_JSONSTART_XXX*/";
var endMarker = "/*XXX_JSONEND_XXX*/";
var start, end;
start = result.indexOf(startMarker);
if (start === -1) {
display("Start marker missing");
}
else {
start += startMarker.length;
end = result.indexOf(endMarker, start);
if (end === -1) {
display("End marker missing");
}
else {
result = $.parseJSON(result.substring(start, end));
display("result.groups.length = " + result.groups.length);
display("result.prices.length = " + result.prices.length);
display("result.titles.length = " + result.titles.length);
}
}
}
});
function display(msg) {
$("<p>").html(String(msg)).appendTo(document.body);
}
})(jQuery);
Live Copy | Source

Categories

Resources