Retrieving serialize data in a PHP file called using AJAX - php

Form sending AJAX code:
var str = $("form").serialize();
alert(str);
// var uns=#unserialize(str);
//alert(uns);
$.ajax({
type: "POST",
url: "update.php",
data: "box1="+str,
success: function(value)
{
$("#data").html(value);
}
HTML Form:
<form>
<input type=checkbox name=box[] value='1'/><input type=checkbox name=box[] value='2'/>
</form>
In my PHP:
$box=$_POST['box1'];
How can I access each of the box variable values in PHP side?

Your js should be like this:
var str = $("form").serializeArray();
$.ajax({
type: "POST",
url: "update.php",
data: str,
success: function(value) {
$("#data").html(value);
}
});
With php you should loop your result array.
$box = $_POST['box'];
foreach ($box as $x) {
echo $x;
}
Edit:
You have to use serializeArray function in jQuery. Then it will work with this code.

Provided that your server is receiving a string that looks something like this
$("form").serialize();
"param1=someVal&param2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array modeled how you would expect. Note this works also with HTML arrays.
See the following for more information: http://www.php.net/manual/en/function.parse-str.php
Hope that's helpful. Good luck!

your JS should be like this -
var str = $( "form" ).serializeArray();
var postData = new FormData();
$.each(str, function(i, val) {
postData.append(val.name, val.value);
});
$.ajax({
type: "POST",
data: postData,
url: action,
cache: false,
contentType: false,
processData: false,
success: function(data){
alert(data);
}
});
Now do this in your php script -
print_r($_POST);
you will get all form data in alert box.

$data = array();
foreach(explode('&', $_POST[data]) as $value)
{
$value1 = explode('=', $value);
$data[$value1[0]] = validateInput($value1[1]);
}
var_dump($data['box']);

your data in php will contain a string like this
field1=value1&field2=value2&....
so you can get your value1 using $_POST['field1] , value2 with $_POST['field2']

Change
data: "box1="+str,
into
data: str,
serialize() will produce a string like: input1=value1&input2=value2. So in your php you can access each value with, for instance $value1 = $_PHP['input1'];

values=$("#edituser_form").serialize();//alert(values);
$.ajax({
url: 'ajax/ajax_call.php',
type: 'POST',
dataType:"json",
data: values,
success: function(){
alert("success");
},
error: function(){
alert("failure");
}
});

$box=$_POST['box'];
and $box is an array.

Related

Can't post JSON variable with AJAX to PHP

In the first document I added a JSON string filled with numbers to localstorage like this:
$.ajax({
url: "oyvind_liste.php",
data: {aktuelle_verdier: aktuelle_verdier},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}});
Then in another document I am trying to post the JSON string retrieved from local storage like this:
<script>
var data = JSON.parse(localStorage.getItem('key'));
var localData = data.join(", ");
$.ajax({
type: 'post',
data: {localData: localData},
url: '',
dataType: "json",
success: function(result){
console.log(result)
}});
</script>
The PHP on the same page as the post tries to fetch the data like this:
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$values = json_decode($user_id);
var_dump($values);
?>
When I run var_dump I get Array(), so in essence it doesn't post anything. Anyone know whats going wrong?
You don't need to use JSON when sending an array in an object argument to $.ajax. Just put the array there, and jQuery will URL-encode it.
var data = JSON.parse(localStorage.getItem('key'));
$.ajax({
type: "post",
data: { localData: data },
...
});
Then in PHP you can do:
$values = isset($_POST['localData']) ? $_POST['localData'] : array();
var_dump($values);
You can also send JSON this way:
var json_string = localStorage.getItem('key');
$.ajax({
type: "post",
data: { localData: json_string},
...
});
then in PHP do:
$values = json_decode(isset($_POST['localData']) ? $_POST['localData'] : '[]');
var_dump($values);

jQuery + php file upload. Pass multiple parameters

How to pass extra variables through $.ajax to post.php?
My first variable is
var form_data = new FormData($(this)[0])
I can pass it alone, but if I want to add another variable and make an array
data {
"form_data": form_data,
"name": "hello"
}
it does't work.
My current code:
$(document).ready(function() {
$("form#data").submit(function(){
var form_data = new FormData($(this)[0]);
$.ajax({
url: 'post.php',
type: 'POST',
data: form_data,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
return false;
});
});
<div id="result"></div>
<form id="data" method="post" enctype="multipart/form-data">
<input name="file" type="file" />
<button>Submit</button>
</form>
Try this. The formData object has a method append. We're going to use that instead. We're going to append the file under the name file. In PHP access it with $_FILES['file']. Now for the array or object that you want to add to it. Use JSON.stringify on it to turn it into a string. We append the JSON string and add it to the name 'object'. To access the JSON in PHP json_decode($_POST['object']) will turn it into an object.
Fiddle
$(function(){
$("form#data").submit(function (e) {
e.preventDefault();
var form_data = new FormData(),
o = {};
o.name = 'Adam';
o.arr = ['test', 213];
form_data.append('file', $('input[name="file"]', this)[0].files[0]);
form_data.append('object', JSON.stringify(o));
$.ajax({
url: '/info/',
type: 'POST',
data: form_data,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
return false;
});
});
I would JSON.stringify it then json_decode when you get it back in PHP
var data = JSON.stringify({ /* object */ });
Then in your php
$data = json_decode(....);
Try to define a new bariable
var name = "hello";
and then insert it into $.ajax data
$.ajax({
url: 'post.php',
type: 'POST',
data: "form_data="+form_data+"&name="+name,
success: function (data) {
$('#result').html(data);
},
contentType: false,
processData: false
});
I never test this script, but there's no matter to check it out :D

How to pass mutiple values from ajax to php file

I have 3 values stored in 3 seperate DIV tags and i want it to pass via ajax to php file. I have working code and stuck in passing all values to php file. Any ideas hoe to do it.
This is my js code:
$('#button').click(function(){
var slider_value = $('#slider_value').text();
var slider1_value = $('#slider1_value').text();
var slider2_value = $('#slider2_value').text();
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: 'slider_value='+slider_value,
success: function(data){
$('#test').html(data);
}
});
});
and this it my php file:
<?php
if (isset($_POST['slider_value'])||($_POST['slider1_value'])){
echo $slider_value = $_POST['slider_value'];
echo $slider1_value = $_POST['slider1_value'];
}?>
Values are seperated by & as in a URL:
data: 'slider_value='+slider_value+'&slider1_value='+slider1_value+'&slider2_value='+slider2_value,
jQuery Code:
$('#button').click(function(){
var slider_value = $('#slider_value').text();
var slider1_value = $('#slider1_value').text();
var slider2_value = $('#slider2_value').text();
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: {var1: slider_value, var2: slider1_value,var3:slider2_value },
success: function(data){
$('#test').html(data);
}
});
});
Use This php code for fetching values
<?php
echo $_POST['var1'];
echo $_POST['var2'];
echo $_POST['var3'];
?>
$('#button').click(function(){
var slider_value = $('#slider_value').text();
var slider1_value = $('#slider1_value').text();
var slider2_value = $('#slider2_value').text();
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: {slider: [slider_value, slider1_value, slider2_value]},
success: function(data){
$('#test').html(data);
}
});
});
And in php file,
<?php
if (isset($_POST['slider'])){
$slider_value = $_POST['slider'];
echo '<pre>' . print_r($slider_value) . '</pre>';
}
?>
Try,
data: 'slider_value='+slider_value+'&slider1_value='+slider1_value+'&slider2_value='+slider2_value;
OR
data:{slider_value:slider_value,slider1_value:slider1_value,slider2_value:slider2_value}
You will get more about jquery ajax here
You are only passing one div value in the datastring. Pass all the values like this:-
$('#button').click(function(){
var slider_value = $('#slider_value').text();
var slider1_value = $('#slider1_value').text();
var slider2_value = $('#slider2_value').text();
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: 'slider_value='+slider_value + '&slider1_value='+slider1_value + '&slider2_value='+slider2_value,
success: function(data){
$('#test').html(data);
}
});
});
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: {
'slider_value': slider_value,
'slider_value1': slider_value1,
'slider_value2': slider_value2
},
success: function(data){
$('#test').html(data);
}
});
});
Firstly, you could store your data differently (in an array) like so:
var slider_values = new Array();
silder_values.push($('#slider_value').text(),$('#slider_value2').text(),$('#slider_value3').text());
And then, you can simply pass this array as a data object to the ajax request like so:
$.ajax({
url:'placeDetailSend.php',
type: 'POST',
data: {'slider_values': slider_values},
success: function(data){
// Do whatever here
}
});
});
However, if you use this method, you must be sure to loop through the $_POST['slider_values'] in PHP as it is now an array not a string. This is pretty simple:
foreach($_POST['slider_values'] as $value){
// Write the current value
echo $value
}

JS AJAX sending multiple data array

I am trying to send multiple data arrays in my ajax save function.
I can do each array individually like data:hardwarePayload and it will work. If I do {hardware: hardwarePayload, service:servicePayload} I get very weird JSON output. that looks like:
hardware=%5B%7B%22hardwareName%22%3A%221%22%2C%22hardwareQuantity%22%3A%22%22%2C%22hardwareBYOD%22%3A%22%22%7D%5D&service=%5B%7B%22serviceName%22%3A%223%22%2C%22serviceQuantity%22%3A%22%22%7D%5D
I really need two arrays one hardware and one service so I can grab each one individually.
My code looks like this..
self.save = function (form) {
var hardwareModel = [];
var serviceModel = [];
ko.utils.arrayForEach(self.services(), function (service) {
serviceModel.push(ko.toJS(service));
});
ko.utils.arrayForEach(self.hardwares(), function (hardware) {
hardwareModel.push(ko.toJS(hardware));
});
//allModel.push({accountId: ko.toJS(account)});
var hardwarePayload = JSON.stringify(hardwareModel);
var servicePayload = JSON.stringify(serviceModel);
//alert(JSON.stringify(serviceModel) +JSON.stringify(allModel));
$.ajax({
url: '/orders/add',
type: 'post',
data: {hardware: hardwarePayload, service:servicePayload}, // data:hardwarePayload,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
};
You should try this
var hardwarePayload = hardwareModel;
var servicePayload = serviceModel;
var postData = {'hardware': hardwarePayload, 'service':servicePayload};
var postData = JSON.stringify(postData);
alert(postData);
$.ajax({
url: '/orders/add',
type: 'post',
data: postData,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
I think you'll be better off if you do NOT stringify your data:
$.ajax({
url: '/orders/add',
type: 'post',
data: {hardware: hardwareModel, service:serviceModel}, // data:hardwarePayload,
contentType: 'application/json',
success: function (result) {
alert(result);
}
});
(Note that I'm using the not stringified hardwareModel and serviceModel)
This way you can have jQuery handle the (json) data for the request.

send each element with class name via AJAX to php

Hi i'm using the below code to take data and send it to a php page, it works as i want it to but its only sending the first ".order" it comes across, ie. i need to send every element with class="order", would this be some sort of .each()?
$('#submit').click(function(){
var order=$('.order').html();
var dataString = 'order='+ order;
$.ajax
({
type: "POST",
url: "order.php",
data: dataString,
cache: false,
success: function(html)
{
$("#response").html(html);
}
});
});
Did this instead and it now works, bizarre!
$('#submit').live('click',function(){
var order=$('.order').text();
var dataString = 'order='+ order;
$.ajax
({
type: "POST",
url: "order.php",
data: dataString,
cache: false,
success: function(html)
{
$("#response").html(html);
}
});
});
Try var order = $('form').serialize() as explained here http://api.jquery.com/serialize/
Other than this, you must do something like:
$('.order').each(function(){
// Get values from order here... something like: order += $(this).html();
// Also, note that if '.order' are inputs you should use $(this).val() instead of $(this).html();
});
Hope it helps.
I believe this should do it:
var order=$('.order')
.map(function(){ return this.innerHtml; })
.get().join('');
var dataString = 'order='+ order;

Categories