I'm trying to send an array from Javascript to PHP.
function wishlist_save(arr){
$.ajax({
type: "POST",
url: "from.php?type=customers",
data: {info: JSON.stringify(arr) },
success: function(){
}
});
}
The array is set this way:
function getAll(){
var info = [];
var i = 0;
$(".desc").each(function(){
var value = $(this).text();
var qtt = $(this).attr('alt');
info[i] = [];
info[i]['desc'] = value;
info[i]['qtt'] = qtt;
i++;
});
return info;
}
If I output (with console.log(getAll())) the array in javascript I get the right values in Chrome Console:
[Array[0], Array[0], Array[0]]
->0: Array[0]
desc: 'John'
alt: 'Good'
->1: Array[0]
desc: 'Obama'
alt: 'Great'
But in PHP (from.php?type=customers) I can't figure out how to get those values..
$arr = json_decode($_POST['info']);
ChromePhp::log($arr[0]['desc']); // returns null
What am I doing wrong?
Solved.
The problem was on JSON.stringify(arr), which in some way didn't send properly the array to PHP.
So, all I needed was to adapt the function that retrieves the array:
var info = [];
info.push({desc: value, qtt: qtt });
Besides that, the AJAX only now need:
data: {info: arr },
And PHP:
Related
I'm trying to pass my JS array to PHP array and all of the solutions that I have found here is useless or I can integrate these solutions to my problem.
Javascript
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
PHP
function ekleme(){
if($_POST['siparisListe']){
$liste = $_POST['siparisListe'];
echo $liste;
}
}
instead of this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
splitListe = JSON.stringify(splitListe);
$.post("menu.php",{'siparisListe[]': splitListe});
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
modify you code in to this
$('#siparisButon').click(function(){
var splitListe = $('#siparis-block span').text();
splitListe = splitListe.split("- ");
var input_data = new FormData();
$.each(splitListe,function(index,value){
input_data.append("siparisListe["+index+"]",value)
});
$.ajax({
url: "menu.php",
data: input_data,
type: "POST",
success: function(data) {
$("#passwordMatch").html(data);
},
error: function(data) {}
})
// I have a div that shows the result of PHP function and it says undefined index.
$('#fonksiyon').show();
})
Remove the [] from the POST field name and pass it an array (jQuery will JSON encode it for you).
$('#siparisButon').click(function() {
let splitListe = ($('#siparis-block span').text() || '').split('- ');
if (splitListe) {
$.post("menu.php", { siparisListe: splitListe });
$('#fonksiyon').show();
}
});
Then in your PHP to verify:
function ekleme() {
if ($liste = $_POST['siparisListe']) {
var_dump($liste);
}
echo 'No $liste array in POST.';
}
In the following code i am not able to filter entry.AllLinks.
The code is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
}
It does not filter and when i hover cursor over AllLinks in entry.AllLinks it is undefined.
Value of entry is coming as:
[{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}]
You can use Array.filter to filter the array as per the values you require.
let arr = [{"AllLinks":"Link9","LinkURL":"http://www.Link9.com"},{"AllLinks":"Link6","LinkURL":"http://www.Link6.com"}] ;
arr = arr.filter(function(elem) {
return elem.AllLinks !== 'Link9';
});
console.log(arr);
I have a form and i wanted specific elements of the form which I got and stored the values in an array.
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var item_name = miniform.elements['itemId'].value;
var quantity = miniform.elements['quantityId'].value;
var amount = miniform.elements['amountId'].value;
var total = amount * quantity;
var cart = ["Item: ",item_name,"Quantity: ",quantity,"Amount: ",amount,"Total: ",total];
I would then like to convert this array into a JSON object and send it to a php file through ajax but its not working. Here is my ajax code:
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.stringify(cart),
success: function(){
console.log('Message Sent');
}
});
What could be the problem??
look the comma, it should be {"key":value, "key":value..} not {"key":,value, "key":,value..}
var cart = {"Item" : item_name, "Quantity" : quantity, "Amount" : amount, "Total" : total};
you are doing wrong .
please use this way
var cart = {"Item ":item_name,"Quantity ":quantity,"Amount ":amount,"Total ":total};
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data: JSON.parse(cart),
success: function(){
console.log('Message Sent');
}
});
If you want to post the array Then you can use this way.
cart = [];
cart[0] = item_name;
cart[1] = quantity;
cart[2] = amount;
cart[3] = total;
$.ajax({
url: url,
type: type,
Content-Type:'application/JSON',
data:{cart:cart},
success: function(){
console.log('Message Sent');
}
});
Don't build it manually
Instead of building your Object or Array manually, which is prone to errors, do it like this:
Object
// Define your empty Object
var cart = {};
// Assign its properties
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = amount * quantity;
Array
Or if you prefer to have an array:
// Define your empty array
var cart = [];
// Assign its properties
cart['item_name'] = miniform.elements['itemId'].value;
cart['quantity'] = miniform.elements['quantityId'].value;
cart['amount'] = miniform.elements['amountId'].value;
cart['total'] = amount * quantity;
Now you have your cart Object or Array ready and you can call JSON.stringify on it:
JSON.stringify(cart);
You could just send the entire form using formdata(). Is there a reason you don't?
Anyway, it doesn't work because you are not creating a json object, but a normal array. There's a difference. You can actually just put the json directly into the ajax call and you don't have to stringify it.
var cart = {};
cart['Item'] = item_name;
cart['Quantity'] = quantity;
cart['Amount'] = amount;
cart['Total'] = total;
$.ajax({
url: 'https://www.google.com',
type: "POST",
//Datatype causes it to automatically become json and will expect json back
//return json back from php through json_encode($myArray);
dataType: "json",
data: cart,
success: function() {
alert('Message Sent');
}
});
in short: You used the wrong braces :)
I just changed it to an easier way of managing objects. The problem with your previous object was that it was built wrong. Should be something like:
var cart = {"Item":item_name,"Quantity": quantity,"Amount":amount,"Total":total};
I found a solution to my problem and I combined some your responses to find the answer.
$('#miniform').on('submit',function(){
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
var cart = {};
cart.item_name = miniform.elements['itemId'].value;
cart.quantity = miniform.elements['quantityId'].value;
cart.amount = miniform.elements['amountId'].value;
cart.total = cart.amount * cart.quantity;
var jsonString = JSON.stringify(cart);
$.ajax({
url: url,
type: type,
data:{data:jsonString},
success: function(){
console.log('Email Sent');
},
error: function(error){
throw new Error('Did not work');
}
});
return false;
});
I am trying to send data from form to PHP file using JavaScript. PHP file pushes this data to database. For now, almost all works well but I have a problem with array from getElementsByClassName. After sending to database I can see only "Array" but no values of this array.
Here's a JS:
function przekaz_form($wejscie) {
var datas = document.formularz.datas.value;
var klient = document.formularz.firma.value;
var comment = document.formularz.comment.value;
var collect = document.getElementsByClassName($wejscie);
var datan = document.formularz.datan.value;
var items = new Array();
for(var i = 0; i < collect.length; i++) {
items.push(collect.item(i).value);
}
jQuery.ajax({
url: 'addtobase.php',
type: 'post',
data:{
devices: items,
datas: datas,
klient: klient,
comment: comment,
datan: datan
},
success: function(output) {
alert('Success');
}
});
}
One way to do this is:
$inputData = json_decode(file_get_contents('php://input'));
Once you have the $inputData variable you can access the data in the JSON by:
$devices = (!is_null($inputData) && property_exists($inputData, "devices")) ? strip_tags($inputData->{"devices"}) : 0;
You should also try to better format the JSON : http://json.org/example
I want to get some values out of TinyMCE textboxes, along with IDs. Then post these via ajax to the server.
jQuery 1.4 and JSON library are loaded
var send_data = [];
$('.contact_check').each(function(i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts[' + this_id + '][message]');
var content = addslashes(msgbox.getContent());
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});
var encoded = JSON.stringify(send_data);
$.ajax({
type: 'POST',
url: 'http://localhost/test.php',
data: encoded,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function() {
alert('jay');
}
});
Firstly,
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
does not seem to work. It says send_data[i] undefined. I've also tried:
send_data[this_id] = escape(content);
That does not seem to work either. The JSON string returns as []. What am I doing wrong?
You're not really making a multi-dimensional array. You're making an array of objects. Either way, before you can set an attribute or array element of something at send_data[i], you have to make send_data[i] be something.
send_data[i] = {};
send_data[i]['id'] = this_id;
send_data[i]['content'] = escape(content);
or, better:
send_data[i] = {
id: this_id,
content: escape(content)
};
You have to make each send_data[i] an object first:
$('.contact_check').each(function (i, item) {
var this_id = $(item).attr('id');
var msgbox = tinyMCE.get('contacts['+this_id+'][message]');
var content = addslashes(msgbox.getContent());
send_data[i] = {};
send_data[i]["id"] = this_id;
send_data[i]["content"] = escape(content);
});