i want to pass array which is generated by javascript..just say i have an array named vals2=('john','peter') and i want to pass this array to my php page(insert_paket_f.php).
this is my ajax code :
$.ajax({
type: "POST",
url: "insert_paket_f.php",
data: { data : vals2 },
cache: false,
//vals=('john','peter','andrea');
success: function(){
alert("OK");
}
});
insert_paket_f.php
$data1 = $_POST['data'];
$data1 = explode(",", $_POST['data']);
print_r($data1);
when i run my browser, its show empty array, and just looks like this Array ( [0] => )
how can i fix this?
thanks..
Try this:
Use join to send the javascript array as an string.
Javascript
var vals2 = ['john','peter'];
$.ajax({
type: "POST",
url: "insert_paket_f.php",
data: { data : vals2.join(',') },
cache: false,
success: function(){
alert("OK");
}
});
PHP
$data1 = $_POST['data'];
$data1 = explode(",", $_POST['data']);
print_r($data1);
Hope it helps.
Try:
$data1 = json_decode($_POST['data']);
print_r($data1);
In the Data Feild try to use variables
as
echo data: data[]=john&data[]=peter&data[]=andrea
Code:-
$.ajax({
type: "POST",
url: "insert_paket_f.php",
data: "data[]=john&data[]=peter&data[]=andrea",
cache: false,
success: function(){
alert("OK");
}
});
Is It working?
Related
I am sending checked checkboxes value to php in array.
// tag =['Apple','Mango','Tomato']
var tag = $(this).children().siblings().children().children('input[name="cb"]:checked');
var tagData = [];
$.each(tag, function() {
tagData.push($(this).val());
});
console.log(tagData);
$.ajax({
type: "POST",
url: "script.php",
data: {tag: tagData },
cache: false,
success: function(){
alert("OK");
}
});
Console.log data
(2) ["Apple", "Apple"]
0: "Apple"
1: "Apple"
length: 2__proto__: Array(0)
I'm getting this array in php like this.
$list = $_POST['tag'];
$imgTag = implode( ", ",$list);
// i want like this - $imgTag = "Apple,Mango,Tomato".
But i getting empty line in php.
Serialize your tagData using JSON.stringify while sending in ajax request. like this
$.ajax({
type: "POST",
url: "script.php",
data: {tag: JSON.stringify(tagData) },
cache: false,
success: function(){
alert("OK");
}
});
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);
What i want to do: copy all selected rows from FIRST table and insert them into SECOND table. In json im sending event type ( insert or delete) and array of IDs rows to copy.
How i can acces to this JSON data in PHP file?
JS:
var data_to_send = {
event : "accept",
ids : ids_to_accept,
}
console.log(ids_to_accept);
$.ajax({
type: "POST",
url: "request.php",
contentType: "application/json; charset=utf-8",
data: data_to_send,
success: function(response){
console.log("Dodałem rekord!");
},
});
PHP:
<?php
//include db configuration file
include_once("connect.php");
if(isset($_POST["data"])){
$data = $_POST["data"];
$ids_to_insert = array();
$ids_to_insert = $data["ids"];
$row_to_insert = $mysqli->query("SELECT * FROM oczekujace WHERE ID='".$ids_to_insert[0]."'");
$inser_row = $mysqli->query("INSERT INTO zaakceptowane(nazwa) VALUES('".$row_to_insert['nazwa']."')");
}
?>
EDIT
Ok, i fixed this. Just deleted contentType...
$.ajax({
type: "POST",
url: "request.php",
//dataType : "json",
//contentType: "application/json; charset=utf-8",
data: {data : data_to_send},
success: function(response){
console.log(response);
console.log("Dodałem rekord!");
},
});
You can use json_decode() function. Its return php array which you can use to insert data in mysql. To read more about json_decode() visit this link.
http://php.net/manual/en/function.json-decode.php
In AJAX use dataType: 'json',
var data_to_send = {
event : "accept",
ids : ids_to_accept,
}
console.log(ids_to_accept);
$.ajax({
type: "POST",
url: "request.php",
dataType: 'json',
contentType: "application/json; charset=utf-8",
data: data_to_send,
success: function(response){
console.log("Dodałem rekord!");
},
});
And in your PHP File use json_decode()
include_once("connect.php");
if($_POST){
$data = json_decode($_POST);
//manipulate $data
$ids_to_insert = array();
$ids_to_insert = $data["ids"];
$row_to_insert = $mysqli->query("SELECT * FROM oczekujace WHERE ID='".$ids_to_insert[0]."'");
$inser_row = $mysqli->query("INSERT INTO zaakceptowane(nazwa) VALUES('".$row_to_insert['nazwa']."')");
}
It will work as you desire.
$_POST['data'] is undefined, because its not present in data_to_send.
You have to either access the posted elements directly in $_POST:
$event = $_POST["event"]);
$ids_to_insert = $_POST["ids"];
or you can change the JS part and provide the data element:
$.ajax({
type: "POST",
url: "request.php",
data: {
"data": data_to_send,
},
success: function(response){
console.log("Dodałem rekord!");
}
});
no need for json_decode, jQuery already converts the data object into a urlencoded parameter string, which PHP in turn converts into an array.
I want to build a graph in jqchart where i need to get two arrays
Now i want to perform operation as given below.Which is giving error ofcourse.
html
$.ajax(
{
type: "GET",
url: "customer_coverage.php",
data: {id:id},
contentType: "application/json",
dataType: "json",
success: function (data21,data22) {
initChart2(data21,data22);
}
});
function initChart2(data21,data22) {
$('#jqChart2').jqChart({
series: [
{
type: 'column',
title: 'no of days ',
data:data21,
},
{
type: 'column',
title: 'no of days ',
data:data22,
},
]
});
}
heres PHP code
echo json_encode($arr1);
echo json_encode($arr2);
So any one has idea of how to do it?
no need to echo json encode two times....merge the array and send the data.......
echo json_encode(array('result1'=>$arr1,'result2'=>$arr2));
and get data by
initChart2(data.result1,data.result2);
See if you are able to produce two object arrays of json then you can try with this:
var data21,data22;
$.ajax({
type: "GET",
url: "customer_coverage.php",
data: {id:id},
contentType: "application/json",
dataType: "json",
success: function (data) {
$.each(data, function(i, item){
data21 = item.data21;
data22 = item.data22;
});
initChart2(data21,data22);
}
});
and i am supposing if you are able to produce this:
[
{
"data21": {
.........
},
"data22": {
........
}
}
]
You cannot get multiple object like that. For a JSON object, you will need to have single object. So what you can do is, create a wrapper object put those two array inside it.
So basically, your php code will be:
<?php
$arr= array();
$arr['arr1'] = $arr1;
$arr['arr2'] = $arr2;
echo json_encode($arr);
?>
So now you will have single main array and so single JSON object.
On JS side, you will get single data. Little Modification will be
$.ajax(
{
type: "GET",
url: "customer_coverage.php",
data: {id:id},
contentType: "application/json",
dataType: "json",
success: function (data) {
var data21=data['arr1'];
var data22=data['arr2'];
initChart2(data21,data22);
}
});
This should work.
You need to combine both array using array_merge().
Example
$response = array();
$response = array_merge($arr1,$arr2);
echo json_encode($response);
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¶m2=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.