passing arrays in jquery post request not working - javascript

im trying to pass javascript arrays in a jquery .post, but it's not showing on the page. What am i doing wrong? i see that my arrays are filled, but the data is not showing on the page post. The console log shows the p element also i dont know why it's doing that.
jquery code:
$("#submitboeking").click(function(event) {
event.preventDefault();
//Cursisten
var voornamen = [];
var achternamen = [];
var geslachten = [];
var geboortedata = [];
$("[id^='txtCursistVoornaam']").each(function() {
voornamen.push($(this).val());
});
$("[id^='txtCursistAchternaam']").each(function() {
achternamen.push($(this).val());
});
$("[id^='radCursistGeslacht']:checked").each(function() {
geslachten.push($(this).val());
});
$("[id^='txtCursistGeboortedatum']").each(function() {
geboortedata.push($(this).val());
});
// console.log(voornamen);
// console.log(achternamen);
// console.log(geslachten);
// console.log(geboortedata);
$.post('/wp-content/themes/tweb/processboeking.php',
{
voornamen: voornamen,
geslachten: geslachten,
voornamen: voornamen,
achternamen: achternamen,
geboortedata: geboortedata,
})
.done(function(data)
{
console.log(data)
$('#overzichtboeking').html(data);
}).fail(function(data) {
alert(response.responseText);
});
var li_count = $('.nav-tabs li').length;
var current_active = $('.nav-tabs li.active').index();
if (current_active < li_count) {
$('.nav-tabs li.active').next('li').find('a').attr('data-toggle', 'tab').tab('show');
var txt = $(".oplselect option:selected").text();
var val = $(".oplselect option:selected").val();
$('.showoplnaam').html('Uw selectie: ' + txt);
}
});
console.log data:
Array
(
[voornamen] => Array
(
[0] => G.F.
)
[geslachten] => Array
(
[0] => Dhr.
)
[achternamen] => Array
(
[0] => martens
)
[geboortedata] => Array
(
[0] => 25-10-1993
)
)
<p id="overzichtboeking"></p>
processboeking.php
<?php
include '/home/vhosts/tweb.nl/httpdocs/wp-content/themes/tweb/db/dbcon.php';
print_r($_POST);
?>
<p id="overzichtboeking"></p>

Get complete form data as array and json stringify it.
var formData = JSON.stringify($("#myForm").serializeArray());
You can use it later in ajax. Or if you are not using ajax; put it in hidden textarea and pass to server. If this data is passed as json string via normal form data then you have to decode it using json_decode. You'll then get all data in an array.
$.ajax({
type: "POST",
url: "serverUrl",
data: formData,
success: function(){},
dataType: "json",
contentType : "application/json"
});
Taken from this stackoverflow post: How to send a JSON object using html form data
To go from JSON input on the server side, take a look at this article for converting back to a PHP array: https://www.dyn-web.com/tutorials/php-js/json/decode.php

Related

Deserialize JSON data and trim off the name and return only values

I have a JSON data loaded from database using AJAX, it has name and value pair after serializing using JavaScriptSerializer, but I need to use it without the names, only the values is needed, how can I serialize the same data without the names
AJAX CALL
$.ajax({
url: 'RhemaServices.asmx/GetMapData',
type: 'POST',
dataType: 'json',
contentType: "application/json; charset-utf-8",
success: function (data) {
},
error: function (err) {
console.log(err)
},
complete: function () {
}
});
JSON data returned
[{"Code":"af","Total":16.63},{"Code":"al","Total":11.58},{"Code":"ve","Total":285.21},{"Code":"vn","Total":101.99}]
I need to re-serialize this data to get the below maybe looping through the data to read only the values
[{"af":"16.63","al":"11.58","ve":"285.21","vn":"101.99"}]
This is what I am trying to do with the AJAX JSON data, but its not working
var datas = [];
data.map(function (item) {
var newdata = item.Code + ":" + item.Total;
datas.push({ newdata });
})
Since your requested data is an object, I suggest you use forEach instead of map and create your properties as such:
let data = [{"Code":"af","Total":16.63},{"Code":"al","Total":11.58},{"Code":"ve","Total":285.21},{"Code":"vn","Total":101.99}];
var datas = {};
data.forEach(item => datas[item.Code] = item.Total);
console.log(datas);
// {"af":16.63,"al":11.58,"ve":285.21,"vn":101.99}
Is data coming all together as a single string? Then it's as simple as
var datas;
...
success: function (data) {
datas = JSON.parse(data);
}
Not sure what you mean by trim off the name ,only values - but you can do with the JavaScript object whatever you want

Iterate loop in php associative array using Jquery

I have PHP associative array and I use JQuery AJAX to get the result array but my problem is when that result is pass to jquery and use looping to extract each Sequence,Percent and Date then that extracted data will store to new Jquery Array for data manipulation purposes. Please see my sample code so far.
sample code PHP ARRAY:
$Sequence=array(
array("Seq1","20%"),
array("Seq2","40%"),
array("Seq3","60%"),
array("Seq4","80%"),
array("Seq5","100%")
);
****For loop here****
$ResultArray[$arrayIndex]=array(
'Sequence' => $Sequence[$arrayIndex][0],
'Percent' => $Sequence[$arrayIndex][1],
'Date' => $row['exactDate']
);
echo json_encode($ResultArray); // then pass result array to jquery
JQUERY :
$(document).ready(function(){
var ListOfSequence = []
var ListOfPercentage = [];
var ListOfDates = [];
$("#button").click(function(){
var _WOID = $('#txtWOID').val();
$.ajax({
url:'getStatus.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(output){
//here is where the problem begin
for (var key in output) {
if (output.hasOwnProperty(key)) {
//here where extracted data will store to designated array
ListOfSequence.push(key);//<---store extracted Sequence
ListOfPercentage.push(key);//<---store percentage
ListOfDates.push(output[key]);//<---store dates
}
}
ListOfPercentage.reverse();
console.log(ListOfPercentage);
console.log(ListOfDates);
console.log(ListofSequence);
}
});
});
});
and here's the console.log:
Thank you in advance
Since you are already using jQuery you could use $.each() :
$(document).ready(function(){
var ListOfSequence = []
var ListOfPercentage = [];
var ListOfDates = [];
$("#button").click(function(){
var _WOID = $('#txtWOID').val();
$.ajax({
url:'getStatus.php',
type:'POST',
data:{id:_WOID},
dataType:'json',
success:function(json){
$.each(json, function(index, object){
ListOfSequence.push(object.Sequence);
ListOfPercentage.push(object.Percent);
ListOfDates.push(object.Date);
});
}
});
});
});
You should set the json response header before sending the content to the browser like so:
header('Content-type: application/json');
die(json_encode($ResultArray);)

Passing object array via jquery ajax to php not working

I am trying to create an associative array with the record id as the key and order as the value. I then want to pass this via ajax to php where I will foreach through the array and update the records. But it is not working I seem to be getting null at json_decode($_REQUEST['orderArray'], true);
Whats wrong with the code:
jquery :
//Make project task table rows sortable
$('#Task_table tbody').sortable({
items: "tr:not(.disable_sort)",//disable sortable on header row
helper: fixHelperModified, //call helper function
update: function(event, ui) {
var order = {};//create object
$('#Task_table tr').each(function(){//loop through rows
var id = $(this).children('td:first-child').find(".order_number").attr("rel");
var order_number = $(this).children('td:first-child').find(".order_number").val();
//fill object array with keys(task->id) and values (task->order_number)
order[id] = order_number;
});
//convert array to json
var jsonArray = JSON.stringify(order);
//prepare POST data
var dataString = { 'orderArray':jsonArray };
$.ajax({
type: "POST",
url: "index.php?module=Project&action=update_order",
data: dataString,
success: function() {
// location.reload();
}
});
}
});
this sends via post:
orderArray {"4b0df1da-8b2d-7776-0026-52d0b3cefbfa":"3","161699ae-6db0-43d6-e85b-52ca07767b0f":"1","8da4cfc3-b56d-12da-e34c-52d09ed0b310":"2"}
The php:
//updates the order of the tasks
function action_update_order(){
//create object/array from json data
$orderArray = json_decode($_REQUEST['orderArray'], true);
var_dump($orderArray);
foreach($orderArray as $id => $order_number){
$GLOBALS['log']->fatal('order: '.$order_number[$id]);
$task = new ProjectTask();
$task->retrieve($id);
$task->order_number = $order_number;
$task->save();
}
}
As I said I cant seem to foreach through the result of the jasondecode. Also hard to debug as its ajax.
can you try change this
var dataString = { 'orderArray':jsonArray };
to
var dataString = { 'orderArray': order };
For some reason JSON.stringify(order) is adding the Html entity version of " to my string so I need to use htmlspecialchars_decode(); in my php first before json_decode. It seems to work.

Json stringify double quotes

I can't seem to get around this issue... Json I'm trying to pass to an MVC Controller keeps coming out like this
"\"{MaterialQuantity: { MaterialID :18, Quantity:1}}\""
This is the code that generates it:
function CreateJsonForQuantities() {
var inputs = $('input[name=MaterialQuantity]');
var total = inputs.length;
var data = "";
inputs.each(function (index) {
data = data + $(this).val();
if (index != total -1)
data = data + ',';
});
return data;
}
And this is the hidden which it reads data from (of course this is auto-generated as well)
<input name="MaterialQuantity" type="hidden" value="{MaterialQuantity: { MaterialID :12, Quantity:5}}" />
What am I doing wrong?
UPDATE
Ok so now I'm properly getting json object and my ajax requests looks like this. Problem now is that it does pass proper objects but all values are null in the controller action :(
var form_data = CreateJsonForNorm();
var quantity_data = CreateJsonForQuantities();
var data = { norm: form_data, mqvm: quantity_data };
$.ajax({
type: "POST",
url: form.attr("action"),
data: data,
success: function () {
location.href = "#Url.Action("Index")";
('#addDialog').dialog("close");
},
error: function () {
alert("Error");
}
});
Try using JSON.stringify(data) in your request

How to convert simple form submit to ajax call;

I have a form with input field which can be accessed like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
and earlier call was
document.forms["algoForm"].submit();
and form was
<form name="algoForm" method="post" action="run.do">
It all run fine
Now I wanted convert it to the ajax call so that I can use the returned data from java code on the same page. So I used soemthing like
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
var data = 'algorithm = ' + algorithm + '&input = ' + input;
$.ajax(
{
url: "run.do",
type: "POST",
data: data,
success: onSuccess(tableData)
{ //line 75
alert(tableData);
}
}
);
However the above code doesn't run. Please help me make it run
Let's use jQuery's serialize to get the data out of the form and then use the jQuery's ajax function to send the data to the server:
var data = $("form[name=algoForm]").serialize();
$.ajax({
url: "run.do",
type: "POST",
data: data,
success: function(tableData){
alert(tableData);
}
});
data expects a literal object, so you need:
var data = {
'algorithm': algorithm,
'input': input
};
Instead of retrieving all the parameter value and then sending them separately (which can be done server side as well, using below code), Use this:
var $form = $("#divId").closest('form');
data = $form.serializeArray();
jqxhr = $.post("SERVLET_URL', data )
.success(function() {
if(jqxhr.responseText != ""){
//on response
}
});
}
divId is id of the div containing this form.
This code will send all the form parameters to your servlet. Now you can use request.getParameter in your servlet to get all the individual fields value on your servlet.
You can easily convert above jquery post to jquery ajax.
Hope this helps :)
// patching FORM - the style of data handling on server can remain untouched
$("#my-form").on("submit", function(evt) {
var data = {};
var $form = $(evt.target);
var arr = $form.serializeArray(); // an array of all form items
for (var i=0; i<arr.length; i++) { // transforming the array to object
data[arr[i].name] = arr[i].value;
}
data.return_type = "json"; // optional identifier - you can handle it on server and respond with JSON instead of HTML output
$.ajax({
url: $form.attr('action') || document.URL, // server script from form action attribute or document URL (if action is empty or not specified)
type: $form.attr('method') || 'get', // method by form method or GET if not specified
dataType: 'json', // we expect JSON in response
data: data // object with all form items
}).done(function(respond) {
console.log("data handled on server - response:", respond);
// your code (after saving)
}).fail(function(){
alert("Server connection failed!");
});
return false; // suppress default submit action
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
I don't know how but this one runs well,
var algorithm = document.forms["algoForm"]["algorithm"].value;
var input = document.forms["algoForm"]["input"].value;
$.post('run.do', {
algorithm : algorithm,
input : input
}, function(data) {
alert(data);
}
);

Categories