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;
Related
I´ve tried retrive some info from mysql for put it in a form,and update the info.
I use ajax call in the same page,I call ajax passing the id and php return all info.
if(isset($_POST["retriveForm"])) {
$data_json =array();
$id = $_POST['retriveForm'];
$sql = "SELECT * FROM mytable WHERE Id = $id";
while ($row = mysqli_fetch_array($db->consulta($sql)) {
$data_json = array('item1' => $row['item1'],'item2' => $row['item2']) ;
}
$data_json['item_array'] = call_a_function_return_array();//this works
echo json_encode($data_json);
}
ajax call shows like this
$(document.body).on('click', '.edit' ,function(){
var id = $(this).data('id');
$.ajax({
type: "POST",
url: "is_the_same_page.php",
data: {retriveForm : id},
success: function(response) {
$('#myForm').find('input').eq(1).val(response.item1);
}
});
});
When put .val(response.item1) get anything,but if I put response the input take all values
$('#myForm').find('input').eq(1).val(response);
shows
{"item1":"item1","item2":"item2","item_array":["item_in_array1","item_in_array2"]}
I also tried
var obj = jQuery.parseJSON(response);
Try setting $.ajax() dataType options to "json"
"json": Evaluates the response as JSON and returns a JavaScript
object.
$(document.body).on("click", ".edit", function() {
var id = $(this).data("id");
$.ajax({
type: "POST",
url: "is_the_same_page.php",
dataType: "json", // set `dataType` to `"json"`
data: {
retriveForm: id
},
success: function(response) {
$("#myForm").find("input").eq(1).val(response.item1);
}
});
});
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);
},
});
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);
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
}
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.