send a multidimensional array to php - php

I have an unknown number of inputs and i want to write them in a database. I tried some different ways but nothing worked. I dont know the number of the inputs, so i need something like a multidimensional array
javascript:
var temp=new Array();
var obj;
$("#mitarbFuktionen fieldset").each(function(){
i=$(this).parent().children().index($(this));
if ($(this).hasClass("New")){
temp[0]='New';
temp[1]=$("legend",this).text();
//.....
obj+=JSON.stringify(temp)
}else if ($(this).hasClass("Remove")){
temp[0]='Remove';
temp[1]=$("legend",this).text();
//.....
obj=$.toJSON(temp);
}
})
$.post("ajax/MitarbSave.php",{
anrede:$('input[name="neuMitarbAnrede"]:checked').val(),
titel:$('#neuMitarbTitel').val(),
nation:$('#neuMitarbNat').val(),
//.....
'kom[]': obj
}, function(data){
alert(data);
})
PHP:
$output= json_decode($_POST["kom"], true);
echo var_dump($output);

Just to provide an answer to my comment:
$(document).ready(function()
{
var test = [];
test.push('a');
test.push('b');
$.post('ajax/script.php',
{
Param : test
},
function(resp)
{
}, 'json');
});
jQuery will automatically convert an array when passed as an param to an Ajax request, to a multi-dimensional array.

You could also just build an object, an pass that:
var obj={};
$("#mitarbFuktionen fieldset").each(function(){
var i=$(this).index();
obj[i]={};
obj[i][$(this).is(".New") ? 'New :' : 'Remove :'] = $("legend", this).text();
});
$.post("ajax/MitarbSave.php",{
anrede:$('input[name="neuMitarbAnrede"]:checked').val(),
titel:$('#neuMitarbTitel').val(),
nation:$('#neuMitarbNat').val(),
kom: obj
}, function(data){
alert(data);
})​;​

just add the array to your input fields in HTML like:
<input type="text" name="neuMitarb[NUMBER][anrede]">
<input type="text" name="neuMitarb[NUMBER][titel]">
//...
So you let html create your array. Submitting your form like regular form submit with ajax

Related

Submit Form Array Via AJAX

I have a form which I would like to submit via Ajax, however, part of it contains an array. I am having difficulty passing this array via Ajax. An example of my Ajax is below, where I would usually pass the form entry data via how it is below after data (one: $('#one').val()) where I would have one row of this for each field.
Now I have a new set of fields, where the information needs to be passed through as an array. I have tried using serialize and formData -- var fd = new FormData("#form") -- and so far either just this array has been passed through, or nothing from the form is passed through, or just the array is not passed through.
Can anyone please point me in the right direction?
$("#form").submit(
function() {
if (confirm('Are you sure you want to edit this?')) {
$("#formMessages").removeClass().addClass('alert alert-info').html(
'<img src="images/loading.gif" /> Validating....').fadeIn(500);
$.ajax({
url: $("#form").attr('action'),
dataType: 'json',
type: 'POST',
data: {
one: $('#one').val(),
two: $('#two').val()
},
success: function(data){
//success stuff would be here
}
});
}
return false;
});
Thanks.
You could try using :
var dataSend = {};
dataSend['one'] = $('#one').val();
dataSend['two'] = $('#two').val();
dataSend['three'] = $('#three').val();
then in the ajax
data: {dataSend:dataSend}
You can gather data in php with json:
$json = json_encode($_POST['dataSend']);
$json = json_decode($json);
print_r($json);
To see output.
Edit:
You can gather data in php like below:
$one = $json->{'one'};
$two = $json->{'two'};
Have you tried this:
Written in JavaScript:
your_array = JSON.stringify(your_array);
And in PHP:
$array = json_encode($_POST['array']);

Display JSON Data in HTML using Laravel 4

Please help me with my problem in displaying JSON data into my view..
my script is:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
$.each(data, function(index, element) {
firstnameID.val(element.first_name);
});
});
});
and my JSON reply is:
{"id":7,"first_name":"John","last_name":"Doe"}
the thing is when i tried to:
alert(element.first_name);
it says UNDEFINED, but when I:
alert(element);
it gives me the value of the last name which is Doe.. my question is how can I then access the other values like the ID and the first name..
EDITED:
this is my route:
Route::get('api/dropdown', function(){
$input = Input::get('option');
$supllier = Supplier::find($input);
returnResponse::json($supllier->select(array('id','first_name','last_name'))
->find($input));
});
Please help me with this one, This is my first time using JSON so im a bit confuse on how this works.
Best Regards
-Melvn
Why are you using each? This should work:
$('#supplierId').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
var firstnameID = $('#firstnameID');
firstnameID.val(data.first_name);
});
});
Ok, give this a try..
Explicitly state that what you're expecting back from the server is JSON using the dataType option in get().
$('#supplierId').change(function()
{
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data)
{
var firstnameID = $('#firstnameID');
$.each(data, function(index, element)
{
firstnameID.val(element.first_name);
});
},
'json' // <<< this is the dataType
);
});
Now you should be able to access the data using the dot syntax:
console.log("last_name: " + element.last_name);
console.log("first_name: " + element.first_name);
console.log("id: " + element.id);
I would add another few lines, just to check that you're getting back what you expect to see:
console.log("NEW ELEMENT"); // << indicator in the console for your reference
console.log(element); // << the whole "element"

Nothing's in $_POST. Is there something wrong with my code?

I am fairly new to JavaScript and PHP, and it's the first time to encounter and use JSON. I think my AJAX request is fine, but even so, the $_POST array is empty.
Here is the AJAX call:
$( "#submit" ).click( function() {
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data',
get_experience_data()
);
submit_basic.done( function(data) {
alert(data); // for debugging purposes
});
});
And this is the function that takes the data from a table:
function get_experience_data() {
var temp, data_exp = [];
$( "#exptable tbody tr" ).each( function() {
temp = {
company: $(this).find('td').eq(0).html(),
position: $(this).find('td').eq(1).html(),
datestart: $(this).find('td').eq(2).html(),
dateend: $(this).find('td').eq(3).html(),
description: $(this).find('td').eq(4).html()
};
data_exp = data_exp.concat(temp);
});
return data_exp;
}
And for reference, the destination controller function that only prints the $_POST array (by the way I am using CodeIgniter):
public function pass_basic_data() {
var_dump($_POST);
}
Can you please pinpoint the error I've made, since I can't find it. Thanks a lot!
UPDATE: I am getting this message in particular:
array(1) {
["undefined"] =>
string(0) ""
}
UPDATE:
Thanks for all the help guys! I already solved it. It made me dance all around the room.
I wrapped the return value in a {name : value} pair.
$( "#submit" ).click( function() {
var post_vars = get_experience_data();
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data',
{object: post_vars}
);
submit_basic.done( function(data) {
alert(data); // for debugging purposes
});
});
I would suggest doing the following for a start :
var submit_basic = $.post('index.php/submit_data/pass_basic_data', get_experience_data());
Try this:
var submit_basic = $.post('index.php/submit_data/pass_basic_data', get_experience_data());
// you need to add parentheses here --------------------------------------------------^
When you pass a function to $.post() it assumes it is a callback that is to be called after the response is received. What you want to do is call the function and pass it's return value in to $.post().
By the way, this line:
data_exp = data_exp.concat(temp);
could be replaced with:
data_exp.push(temp);
No need to be creating a new array every time if you're just adding a value to the end.
You need to execute the method get_experience_data, otherwise you are passing the function not executing it
try troubleshooting the actual jquery, not the php part.
but heres a suggestion:
var post_vars = get_experience_data();
var submit_basic = $.post( 'index.php/submit_data/pass_basic_data', post_vars );
here is a conclusion to my previous answer plus the comments, but im still not sure if you could stingify arrays in arrays..
var submit_basic = $.ajax({
type: "POST",
url: 'index.php/submit_data/pass_basic_data',
dataType: 'json',
async: false,
data: JSON.stringify(get_experience_data()),
success: function (response) {
alert(response);
}
});
UPDATE:
modify your get_experience_data function according to this jsfiddle script
like this:
temp = '{ ';
temp+= '"company":"' +$(this).find('td').eq(0).html()+ '", ';
temp+= '"position":"' +$(this).find('td').eq(1).html()+ '", ';
temp+= '"datestart":"' +$(this).find('td').eq(2).html()+ '", ';
temp+= '"dateend":"' +$(this).find('td').eq(3).html()+ '", ';
temp+= '"description":"' +$(this).find('td').eq(4).html()+ '"';
temp+= ' }';

How to retrieve $_POST variable from jquery serializearray()

I have a problem in retrieving the $_POST data from jquery serializeArray();. I tried to for loop the $_POST to get the data but failed.
This is my JavaScript code:
function update_cart(){
var fields = $(':input').serializeArray();
console.log(fields);
var url = "update_cart.php";
$.post(url, {fields:fields}, function(data) {
alert(data);
}, "html");
return false;
}
In my PHP code :
var_dump($_POST);
The result is this:
array(1) {["fields"]=> string(15) "[object Object]"}
So, can anyone please teach me how to access the $_POST data?
You don't need to nest your serialized object; that seems to be what's causing the error. Just set your post call to:
$.post(url, fields, function(data) {
alert(data);
}, "html");
That should work; you might also want to change from using serializeArray to using serialize.
Once this is properly configured, if you have:
<input name="foo" value="bar" />
It can be accessed as:
$_POST["foo"]; //bar

JSON returned as individual string and not objects

I am using Codeigniter and trying to use the jQuery autocomplete with it. I am also using #Phil Sturgeon client rest library for Codeigniter because I am getting the autocomplete data from netflix. I am return correct JSON and I can access the first element with
response(data.autocomplete.autocomplete_item[0].title.short);
but when I loop through the results
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short)
}
it acts like a string. Lets say the result is "Swingers", it will return:
Object.value = s
Object.value = w
Object.value = i
and so on.
the js:
$("#movies").autocomplete({
source: function(request, response) {
$.ajax({
url: "<?php echo site_url();?>/welcome/search",
dataType: "JSON",
type:"POST",
data: {
q: request.term
},
success: function(data) {
for (var i in data.autocomplete.autocomplete_item) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
}
});
}
}).data("autocomplete")._renderItem = function(ul, item) {
//console.log(item);
$(ul).attr('id', 'search-autocomplete');
return $("<li class=\""+item.type+"\"></li>").data( "item.autocomplete", item ).append(""+item.title+"").appendTo(ul);
};
the controller:
public function search(){
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// set var equal to results
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'));
//$this->rest->debug();
//$json_data = $this->load->view('nice',$data,true);
//return $json_data;
echo json_encode($netflix_query);
}
the json return
{"autocomplete":
{"autocomplete_item":[
{"title":{"short":"The Strawberry Shortcake Movie: Sky's the Limit"}},
{"title":{"short":"Futurama the Movie: Bender's Big Score"}},
{"title":{"short":"Daffy Duck's Movie: Fantastic Island"}}
...
any ideas?
thanks.
there are some console logs with the return
the url
in, as you've noticed, doesn't do what you'd like with arrays. Use $.each
As far as I know, for (property in object) means that you want to access each of its properties rather than accessing them via the index. If you want to access them via the index, you probably want to use the standard for loop.
for (i = 0; i <= 10; i++) {
response(data.autocomplete.autocomplete_item[i].title.short);
}
or if you still want to use your code, try this:
for (i in data.autocomplete.autocomplete_item) {
response(i.title.short);
}
I haven't test them yet but I think you have the idea.
ok I figured out the correct format that I need to send to the autocomplete response method:
the view
$("#movies").autocomplete({
minLength: 2,
source: function(request, response) {
$.post("<?php echo base_url();?>welcome/search", {q: request.term},
function(data){
//console.log(data);
response(data);
}, 'json');
}
});
the controller:
$search = $this->input->post('q');
// Run some setup
$this->rest->initialize(array('server' => 'http://api.netflix.com/'));
// Pull in an array
$netflix_query = $this->rest->get('catalog/titles/autocomplete', array('oauth_consumer_key'=>$this->consumer_key,'term'=> $search,'output'=>'json'),'json');
$json = array();
foreach($netflix_query->autocomplete->autocomplete_item as $item){
$temp = array("label" => $item->title->short);
array_push($json,$temp);
}
echo json_encode($json);
what was needed was to send back to the view an array of objects. Thank you guys for all your answers and help!!

Categories