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);
Related
I have 2 ajax is an array and single char:
var jsonEncode = JSON.stringify(TableData); --> output: [{"name":"Ristha","age":"30"},{"name":"Niken","age":"25"}]
var code = $('#mutiplearray-code_reg').val(); --> output: 1RF46TA
How to send ajax post when I use 2 data like that:
$.ajax({
type: "POST",
data: "pTableData=" + jsonEncode + "code1=" + code,
success: function(msg){
// alert(msg);
},
});
When I get using in my controller:
$tableData = stripcslashes($_POST['pTableData']);
$tableData = json_decode($tableData, true);
$name1 = $tableData['name'];
$age1 = $tableData['age'];
$code1 = $_POST['code1'];
It's have error dev tool undefined code1 and pTableData?? What I'm do wrong with use multiple data in my ajax?
When I'm just using post data one of them is work correctly
Pass data as json. You passed the data as string.
$.ajax({
type: "POST",
data: {pTableData: jsonEncode, code1: code},
success: function(msg){
// alert(msg);
},
});
$.ajax({
type: "POST",
data:{'pTableData':jsonEncode,'code1':code},
success: function(msg){
// alert(msg);
},
});
I am sending and retrieving some data with this ajax call and saving result in localstorage like this:
$.ajax({
url: "list.php",
data: {values: values},
dataType: "json",
success: function(result){
var dataToStore = JSON.stringify(result);
localStorage.setItem('key', dataToStore);
}
});
Then I am retrieving it in a separate PHP document like this and trying to add it to a PHP variable. I think the problem occurs because when I console.log, it logs 10 times or so. And I can't echo it in PHP. How do I pass it correctly?
<script>
var localData = JSON.parse(localStorage.getItem('key'));
$.each(localData, function(key, value){
console.log("This is the data that is stored", localData)
$.ajax({
type: 'post',
data: {localData},
dataType: "json",
success: function(result){
console.log(result)
}
});
</script>
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = implode(", ", $user_id);
?>
You are causing an asynchronous functionality of ajax() real pain by calling it in a loop
Why dont you use join() to join items with ", " in js like what you do in php
<script>
var localData = JSON.parse(localStorage.getItem('key')).join(", ");
$.ajax({
type: 'post',
data: {localData},
dataType: "json",
success: function(result){
console.log(result)
}
});
</script>
<?php
$user_id = isset($_POST['localData'])?$_POST['localData']:"";
$verdier = $user_id;
?>
You Should also cast user_id as an (int) if user_id need to be a single value and int
$verdier = (int) $user_id;
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 am sending some data with ajax, and as a response i get multidimensional array.
$.ajax({
type: "POST",
url: "/slideshow/list.php",
data: imageId,
success: function(data){
imagesList = data;
console.log(imagesList);
curentImage = imagesList[0];
}
});
Response, data looks like this. This is what i get on console.log(imagesList):
I am using php, and the response is provided like this <?php echo json_encode($data) ?>
[
[1,487124,"<img src=\"http:\/\/example.com\/images\/1\/487124.jpg\" \/>","http:\/\/example.com\/photos\/salle-a-manger---mineral\/649518","Title 1"],
[2,732924,"<img src=\"http:\/\/example.com\/images\/1\/732924.jpg\"\/>","http:\/\/example.com\/photos\/salle-a-manger---","Title 2"],
[3,341649,"<img src=\"http:\/\/example.com\/images\/2\/341649.jpg\"\/>","http:\/\/example.com\/photos\/salle-a-manger---","Title 3"]
]
If i try to access the first array with imagesList[0] it only shows [
How can i access the first or second array, or values inside of them?
specify the dataType in ajax request
$.ajax({
type: "POST",
url: "/slideshow/list.php",
data: imageId,
dataType:"json",
success: function(data){
$.each(data,function(key,value){
console.log('key:'+key+", value:"+value);
//do your stuff
});
}
});
Use this
var obj = $.parseJSON(data);
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.