I've this type of array in JS:
[{
websitetype: "onepager"
}, {
layout: "provided"
}, {
layout_provided: "wireframes"
}, {
languages: "single"
}, {
client_name: "dasda"
}, {
client_email: "asdasd#asdasd.fr"
}, {
client_conditions: "on"
}, {
client_newsletter: "on"
}]
How can I send it through Ajax ?
What I tried is:
$.ajax({
type: 'POST',
url: 'assets/send.php',
data: {datas},
success: function(response) { },
});
This is what I would like to get in PHP:
[datas] => Array
(
[websitetype] => onepager
[layout] => provided
[layout_provided] => wireframes
[languages] => single
[client_name] => dasda
[client_email] => asdasd#asdasd.fr
[client_conditions] => on
[client_newsletter] => on
)
What I'm missing here please ?
Thanks.
The first thing you should do is reduce that array into an object matching the format you want
const dataObject = Object.fromEntries(datas.flatMap(o => Object.entries(o)))
This looks like the following
{
"websitetype": "onepager",
"layout": "provided",
"layout_provided": "wireframes",
"languages": "single",
"client_name": "dasda",
"client_email": "asdasd#asdasd.fr",
"client_conditions": "on",
"client_newsletter": "on"
}
You then have two options for posting it to PHP
Send it as raw JSON
$.ajax({
method: "POST",
url: "assets/send.php",
contentType: "application/json",
data: JSON.stringify(dataObject),
processData: false
})
Then read and parse the JSON in PHP
$datas = json_decode(file_get_contents("php://input"), true);
// example
echo $datas["websitetype"]; // "onepager"
Alternatively, let jQuery format the data as an associative PHP array
$.ajax({
method: "POST",
url: "assets/send.php",
data: {
datas: dataObject
}
})
This will post an application/x-www-form-urlencoded request body of
datas%5Bwebsitetype%5D=onepager&datas%5Blayout%5D=provided&datas%5Blayout_provided%5D=wireframes&datas%5Blanguages%5D=single&datas%5Bclient_name%5D=dasda&datas%5Bclient_email%5D=asdasd%40asdasd.fr&datas%5Bclient_conditions%5D=on&datas%5Bclient_newsletter%5D=on
PHP can read this as an array via $_POST
print_r($_POST['datas']);
Results in
Array
(
[websitetype] => onepager
[layout] => provided
[layout_provided] => wireframes
[languages] => single
[client_name] => dasda
[client_email] => asdasd#asdasd.fr
[client_conditions] => on
[client_newsletter] => on
)
Encode your data string into JSON.
const datas = [{
websitetype: "onepager"
}, {
layout: "provided"
}, {
layout_provided: "wireframes"
}, {
languages: "single"
}, {
client_name: "dasda"
}, {
client_email: "asdasd#asdasd.fr"
}, {
client_conditions: "on"
}, {
client_newsletter: "on"
}]
const jsonString = JSON.stringify(datas)
$.ajax({
type: 'POST',
url: 'assets/send.php',
data: { datas: jsonString },
success: function(response) { },
});
In your PHP:
$data = json_decode(stripslashes($_POST['datas']));
// here i would like use foreach:
foreach($datas as $data){
echo $data;
}
Related
This question already has answers here:
Javascript - Counting duplicates in object array and storing the count as a new object
(3 answers)
Closed 3 years ago.
What's the best way to get duplicates in an array of hashes with strings and count number of appearances.
If I have this array of hashes
const data = [
{
url: 'https://app.mywebsite.net/endpoint1',
method: 'POST'
},
{
url: 'https://app.mywebsite.net/endpoint2',
method: 'POST'
},
{
url: 'https://app.mywebsite.net/endpoint1',
method: 'POST'
}
]
And I want to get the hashes that are duplicated and the amount of times they appear like
{
url: 'https://app.mywebsite.net/endpoint1',
method: 'POST',
count: 2
},
{
url: 'https://app.mywebsite.net/endpoint2',
method: 'POST',
count: 1
},
Javascript - Counting duplicates in object array and storing the count as a new object
You can use Array.reduce for that :
const data = [
{
url: "https://app.mywebsite.net/endpoint1",
method: "POST"
},
{
url: "https://app.mywebsite.net/endpoint2",
method: "POST"
},
{
url: "https://app.mywebsite.net/endpoint1",
method: "POST"
}
];
const result = data.reduce((all, curr) => {
const ndx = all.findIndex(e => e.url === curr.url);
if (ndx > -1) {
all[ndx].count += 1;
} else {
all.push({ url: curr.url, count: 1 });
}
return all;
}, []);
console.log(result)
Like #Taki mentions, you can use the Array.prototype.reduce() method.
const frequencies = arr =>
Object.values(
arr.reduce((obj, { url, method }) => {
obj[url] = obj[url] || { url, method, count: 0 }
obj[url].count += 1
return obj
}, {})
)
const data = [
{
url: 'https://app.mywebsite.net/endpoint1',
method: 'POST',
},
{
url: 'https://app.mywebsite.net/endpoint2',
method: 'POST',
},
{
url: 'https://app.mywebsite.net/endpoint1',
method: 'POST',
},
]
const result = frequencies(data)
console.log(result)
Using with reduce (or forEach) will simplify.
const data = [
{
url: "https://app.mywebsite.net/endpoint1",
method: "POST"
},
{
url: "https://app.mywebsite.net/endpoint2",
method: "POST"
},
{
url: "https://app.mywebsite.net/endpoint1",
method: "POST"
}
];
const updated = data.reduce(
(acc, curr) =>
Object.assign(acc, {
[curr.url]:
curr.url in acc
? { ...acc[curr.url], count: acc[curr.url].count + 1 }
: { ...curr, count: 1 }
}),
{}
);
console.log(updated);
I'm trying to implement the EasyAutoComplete plugin on a field based on the value filled in another field, using ajax requests.
I have a customerid field and when it's value changes, I want the productname field to show all products related to that customerid using the EasyAutoComplete plugin.
Here is what I have so far:
$('#customerid').on('change',function() {
var products2 = {
url: function(phrase) {
return "database/FetchCustomerProducts.php";
},
ajaxSettings: {
dataType: "json",
method: "POST",
data: {
dataType: "json"
}
},
preparePostData: function(data) {
data.phrase = $("#customerid").val();
return data;
},
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(products2);
});
Contents of FetchCustomerProducts.php:
if(!empty($_POST["customerid"])){
$products = $app['database']->Select('products', 'customerid', $_POST['customerid']);
echo json_encode(['data' => $products]);
}
However it's not working. The code is based on the 'Ajax POST' example found on this page.
you can using element select category add is class "check_catogory"
after using event click element select get value is option, continue send id to ajax and in file php, you can get $_POST['id'] or $_GET['id'], select find database,after echo json_encode
$("#customerid").change(function(){
var id = $(this).val();
if(id!=""){
$.ajax({
url:"database/FetchCustomerProducts.php",
type:"POST",
data:{id:id},
dataType: "json",
cache:false,
success:function(result){
var options = {
data:result,
getValue: "name",
list: {
onSelectItemEvent: function() {
var value = $("#productname").getSelectedItemData().id;
$("#productid").val(value).trigger("change");
},
match: {
enabled: true
}
}
};
$("#productname").easyAutocomplete(options);
}
})
}
});
Aplication is built on Yii2 with using Kartik's star-rating widget. Js code have an error:
Image with error in console:
Code:
<?php
$js = <<<JS
function (event, value, caption) {
$.ajax({
type: 'GET',
url: '/rating/update-rating',
data: {
points: value,
post_id: $post->id
},
success: function(res) {
$(event.currentTarget).rating('update', res);
},
error: function(e) {
console.log(e);
}
});
}
JS;
$this->registerJs($js);
echo StarRating::widget([
'name' => $post->post_rate,
'value' => isset($post->rating[0]['dec_avg']) ? $post->rating[0]['dec_avg'] : 0,
'pluginOptions' => [ ... ]
'pluginEvents' => [
'rating:change' => $js,
],
You forgot to add a name for your js function:
function functionName(event, value, caption) {
$.ajax({
type: 'GET',
url: '/rating/update-rating',
data: {
points: value,
post_id: $post - > id
},
success: function(res) {
$(event.currentTarget).rating('update', res);
},
error: function(e) {
console.log(e);
}
});
}
i want to send a multidimensional array to PHP from JQuery AJAX, but it is receiving in PHP like this
Array
(
[recordid] => 38
[locations] => [object Object],[object Object]
)
i must be doing some stupid mistake. here is the code.
it gets records from a table and send to PHP
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
locations = locations.toString();
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: { recordid: recordid,locations:locations },
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
and this is the PHP function where i am receiving the data:
function saveSearchedLocations(){
print_r($_POST);
}
Use JSON.stringify() instead of toString() like so:
Change your AJAX call to this:
$(document).on('click','.savenow',function(){
recordid = $(this).data('id');
locations = [];
$('.selectrec').each(function () {
parent = $(this).parent().parent();
name = parent.find('td').eq(5);
address = parent.find('td').eq(6);
lat = parent.find('td').eq(1);
lng = parent.find('td').eq(2);
row = [name,address,lat,lng];
locations.push(row);
});
ajaxData = { recordid : recordid,locations : locations }
$.ajax({
type: "POST",
url:'/record/saveSearchedLocations',
data: JSON.stringify(ajaxData),
dataType: 'json',
success: function (data) {
console.log(data);
},
error:function(data){
alert("something went wrong, please try again.");
}
});
});
JSON.stringify() converts your array to an actual json string as opposed to Array.prototype.toString() which joins your array (one level) using a comma as separator.
Take this answer as a reference:
I think you need to use JSON.stringify(selectedData) in order to use it on the serverside.
jQuery:
var obj = { 'risk_cat': risk_cat, 'risk_type': risk_type };
selectedData.push(obj);
$.post('serive.php', { DTO: JSON.stringify(selectedData) },
function(data){ /* handle response, */ });
service.php:
header('Content-type: application/json');
header('Cache-Control: no-cache, must-revalidate');
$foo = json_decode($_POST['DTO']);
$arr = array('a' => 1, 'b' => 2, 'c' => 3, 'd' => 4, 'e' => 5); //example data
echo json_encode($arr);
This should get you started. In your ajax reponse, alert(data.a) would be alerting "1"
sendAjax = function() {
var data = {
foo: 123,
bar: 456,
rows: [{
column1: 'hello',
column2: 'hola',
column3: 'bonjour',
}, {
column1: 'goodbye',
column2: 'hasta luego',
column3: 'au revoir',
}, ],
test1: {
test2: {
test3: 'baz'
}
}
};
$.ajax({
type: 'post',
cache: false,
url: './ajax/',
data: data
});
}
When the button is clicked, the following structured data shows up in PHP's $_POST variable:
Array
(
[foo] => 123[bar] => 456[rows] => Array(
[0] => Array(
[column1] => hello[column2] => hola[column3] => bonjour
)
[1] => Array(
[column1] => goodbye[column2] => hasta luego[column3] => au revoir
)
)
[test1] => Array(
[test2] => Array(
[test3] => baz
)
)
)
This will only work with jQuery 1.4.0+. Otherwise jQuery simply calls .toString() on the nested array at key "rows" and nested object at key "test1", and they get passed to PHP with the useless values "[object Object
here is the link u can check here
https://www.zulius.com/how-to/send-multidimensional-arrays-php-with-jquery-ajax/
Put your data in a form and send form data with serializeArray()
I'm adding the feature like in Solgema Fullcalendar - http://plone.org/products/solgema.fullcalendar/releases/2.1.2
(selecting and showing events with checkboxes selection)
My eventSourses look like:
eventSources: [
...
{
url: '/admin_schedule/get_schedule_db_recurring_events_on_daysweek/',//"<?echo $data_path?>",
type: 'GET',
data: {sch_teacher_id: sch_teacher_id},
backgroundColor: 'red',
}
],
And I want implement checkboxes for "filtering" events by teachers, checked in checkboxes. For beginning make just one checkbox (later make foreach cover)
<div class="box">
<?php
$js = 'onClick="rerender_schedule()"';
echo form_checkbox('teacher', 'vika', FALSE, $js)." Vika";
?>
</div>
By this code as I think, fullcalendar must call rerender_schedule() function which filters data from eventSource with vika's sch_teacher_id
If somebody could help with rerender_schedule() function, I will be thankful, because not good in ajax.
EDIT: (thanks to tocallaghan!). It's just a beginning right now.
My 3 checkboxes:
$data = array(
'name' => 'teacher',
'class' => 'teacher',
'id' => 'teacher',
'value' => '128',
'checked' => FALSE,
'style' => 'margin:10px',
);
echo form_checkbox($data); echo "Вика";
$data = array(
'name' => 'teacher',
'class' => 'teacher',
'id' => 'teacher2',
'value' => '111',
'checked' => FALSE,
'style' => 'margin:10px',
);
echo form_checkbox($data); echo "Вася";
$data = array(
'name' => 'teacher',
'class' => 'teacher',
'id' => 'teacher3',
'value' => '1',
'checked' => FALSE,
'style' => 'margin:10px',
);
echo form_checkbox($data); echo "Саша";
ajax on change them:
$('.teacher').change(function (event) {
events1.data.sch_teacher_id = $(this).val();
events2.data.sch_teacher_id = $(this).val();
events3.data.sch_teacher_id = $(this).val();
$calendar.fullCalendar('refetchEvents');
});
vars for eventSourses:
var events1 = {
url: 'url1',
type: 'GET',
data: {sch_teacher_id: $('#teacher').val() },
success: function (response) {
return response;
}
};
var events2 = {
url: 'url2',
type: 'GET',
data: {sch_teacher_id: $('#teacher').val() },
backgroundColor: 'green',
success: function (response) {
return response;
}
};
var events3 = {
url: 'url3',
type: 'GET',
data: { sch_teacher_id: $('#teacher').val() },
backgroundColor: 'red',
success: function (response) {
return response;
}
};
my eventSources call
eventSources: [
events1,
events2,
events3
],
You need refetchEvents , but be careful to update you data parameter before calling (otherwise it will remain the initially set value)
$('.CheckBoxClass').change(function () {
events.data.sch_teacher_id = $(this).val();
$('#calendar').fullCalendar('refetchEvents');
});
Edit: code to declare events object:
var events = {
url: 'url',
type: 'GET',
data: { Id: $('#divId').val() },
success: function (response) {
return response;
}
};
$('#calendar').fullCalendar({
events: events
});