How to retrieve $_POST variable from jquery serializearray() - php

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

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']);

jsonp, jQuery & PHP to make cross-domain ajax call

http://serverA.com/list.php:
html:
<form id="myform">
<input id="inputfield" name="view">
</form>
js:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: inputdata,
dataType: 'jsonp'
});
});
http://serverB.com/detail.php
php:
<?php
$view = $_GET['callback'].'('.json_encode(name) .')';
?>
html:
<h4><?php echo $view; ?></h4>
what the code does is:
from serverA, assign a value "ocean-view" to an input field, submit this form to serverB, and display this value in a h4 tag.
I couldn't quite figure out how to write the server-side code to output the value, even though I have found the following posts.
this and this.
Any kind of help is appreciated.
UPDATE:
I used YQL to help to see the jsonp callback response, here is the json structure:
callback({
"query": {
"count": 1,
"created": "2013-07-29T13:01:12Z",
"lang": "en-US",
"results": {
"h3": {
"class": "mytitle",
"content": "Example"
}
}
}
});
Actually You are very close to success... just read these points.
Whenever you are making an ajax request the browser sends a hit on ajax URL with respected parameters and details. On respected URL PHP code executes. It can return data in some format. It can not return data in directly PHP variable.
Formats are:
text/html
json
xml
......
Mainly for cross domain requests we use JSONP.
And it means PHP script will return data in JSON.
So you will just echo your json_encode in directly script. That will be the response of your ajax request.
Now when you have got the data in ajax function, then jQuery uses success: function(response){ } where you response will come.
So variable response will contain JSON.
You can access JSON and put data in any tag by using jQuery selector.
$().html(response.);
These thing can be analyzed in any browser in debug console. That what is requested and what is returned.
even you can use Firebug in Mozilla to inspect ajax request.
So you will do three changes.
In Ajax function write a success function:
var inputdata = $('#inputfield').val('ocean-view');
$('#myform').submit(function(e) {
e.preventDefault();
$.ajax({
type: 'GET',
url: 'http://serverB.com/detail.php',
data: "inputdata="+inputdata,
dataType: 'jsonp',
success:function(response){
// response will be json type so access it
// print ur json in html tag like resposne is {"data":23}
$(<jquery selector>).html(reponse.data);
}
});
});
<?php
// echo this
$inputdata = $_GET['inputdata'];
// perform you logic ,
// make an array to encode it in json
echo $_GET['callback'].'('.json_encode($responseArr) .')';
?>
and remove PHP code from h4 tag.

How to submit an object of data via POST, not ajax

My data looks like this, it's just an object, with two objects in it (each representing the data of a form).
Object {x__sf: Object, x__mx: Object}
x__mx: Object
country_id: "1"
input1: ""
input2: ""
...
x__sf: Object
...
I think I'll have to make a temporary form in memory and submit that? I'm not sure a safe way of looping through my data and adding hidden fields to the temporary form. Is there a function for this? Or better way?
I want to do this, but have it actually submit the page, because there's redirect logic serverside.
$.post('/whatever.php', data);
But what is the problem with the following approach?
Server side:
<?php
// do some stuff
print "/redirect/to.php";
?>
Client side:
$.post("/whatever.php", data, function(data) {
location.href = data;
});
Or even more advanced:
Server side:
<?php
// do some stuff
header("Content-Type: application/json");
print json_encode(array(
"success" => "/redirect/to.php"
));
?>
Client side:
$.post("/whatever.php", data, function(data) {
if (data.success) {
location.href = data.success;
}
}, "json");
Don't bother looping.... do something like this:
$('form').submit(function() {
alert($(this).serialize());
return false;
});
Or in you're case:
var data = $("#idOfForm").serialize();
You just want to stringify your data before you send it:
$.post('/whatever.php', JSON.stringify(data));
On the server side, you need to use the PHP json_decode() function:
json_decode(http_get_request_body());

send a multidimensional array to 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

JavaScript variable when sending data via jQuery $.post() function

I have a problem when I want to send input data via jQuery's $.post. I have this input:
<input id="mydata" value='<?php echo $data; ?>' >
and I want to send its data via jQuery's $.post() function.
This $.post function runs, but it does't send anything:
var the_data = $('#mydata').val();
//alert(the_data); has correct data!!
$.post("http://php/server", the_data , function(data){
alert(data);
}, "html");
But this one sends data correctly:
$.post("http://php/server", <?php echo $data; ?> , function(data){}, "html");
I should use input for saving data and method 2 isn't suitable for me.
The data needs to be an object.
var the_data = {
mydata: $('#mydata').val()
};
You can access this in your PHP with $_POST['mydata'].

Categories