How to pass mutiple values from ajax to php file - php

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
}

Related

How to POST jQuery variable through ajax to external PHP SQL script and return values

I'm trying to pass a jQuery variable (var datastring), that is a string, through ajax to the external drug_scripts.php file that echos out the value. I can get it to work if I set the data to a numerical value, however if I set it to the variable it returns NULL.
I've set data: ({dataSTring: dataString}) -- returns NULL.
Setting data: ({name: 123}) --- returns 123
AJAX:
var dataString = '<?php print $DF_NAME1; ?>';
$.ajax({
url: "/wp-content/themes/Avada-Child-Theme/assets/php/drug_scripts.php",
type:"POST",
dataType: 'json',
data: ({dataString: 125}),
success: function(data){
console.log(data);
}
});
PHP:
$userInput = $_POST['dataString'];
echo $userInput;
Again, the current state returns 123. If you were to set data to data: (dataString) it returns NULL.
I will assume $DF_NAME1 is defined as something like <?php $DF_NAME1 = 'name'; ?> (which you will get somewhere, like the database)
Then:
<script>var dataString = "<?=$DF_NAME1?>";</script>
<script>
$( document ).ready(function() {
var dataToSend = 'dataString=' + dataString;
$.ajax({
url: "/wp-content/themes/Avada-Child-Theme/assets/php/drug_scripts.php",
type:"POST",
dataType: 'json',
data: dataToSend,
success: function(data){
console.log(data);
}
});
});
</script>
The PHP file:
<?php
$userInput = $_POST['dataString'];
echo json_encode($userInput);
?>
You need both ... attribute name and attribute value
....
type:"POST",
dataType: 'json',
data: ({attribute_name:'attribute_value'}),
....
in your case
....
type:"POST",
dataType: 'json',
data: ({dataString : dataString }),
....
in $_POST['dataString'] you should obtain the content of the var dataString
Try this it works as I have rewritten the code for you.
In the script below, You can see that I just alert the dataString variable to see if it has any value. if the alert is empty, it means you are not passing any value to the datastring variable.
I have also tested it with variable data string set to NancyMooree which I commented
<html><head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
//var dataString = 'NancyMoore';
var dataString = '<?php echo $DF_NAME1; ?>';
// check that datastring has value in it by alerting it
alert(dataString);
var datasend = "dataString ="+ dataString ;
$.ajax({
type:'POST',
url:'/wp-content/themes/Avada-Child-Theme/assets/php/drug_scripts.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(data){
console.log(data);
$('#listresult').fadeIn('slow').prepend(data);
}
});
});
</script>
</head>
<body>
<div id="listresult"> </div>
</body>
</html>
php
<?php
$userInput = $_POST['dataString'];
echo $userInput;
?>

Localstorage to PHP variable

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;

serializeArray not sending the data

This is a sample of the php and javascript.
<form id="image-comment" method="post" action="includes/insert_image_comment.php">
<textarea id="comment-area" name="comment-area"></textarea>
</form>
// javascript
$("#image-comment").submit(function(event) {
event.preventDefault();
var action_url = event.currentTarget.action;
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({imageid: id});
$.ajax({
url: action_url,
type: 'post',
data: params,
success: function(data) {
alert(data);
}
});
});
// insert_image_comment.php
echo $get_image = $_POST['imageid'];
$comment = $_POST['comment-area'];
When echoing $_POST['imageid'] i get an error 'Undefined index: imageid'.
When echoing $_POST['comment-area'] it's ok.
Why one works and the other not?
Thanks
Try to use the format that serializeArray uses: Example:
$("#image-comment").submit(function(event) {
event.preventDefault();
var id = 4;
var params = $("#image-comment").serializeArray();
params.push({name: 'imageid', value: id}); // this one
$.ajax({
url: document.URL,
type: 'POST',
data: params,
success: function(data) {
alert(data);
}
});
});

How to use jquery VALUE in an ajax success function

I cannot use value div name in fourth-last line
I want to use div name in Ajax function in $("divname").html(data);
$('.edit').click(function() {
var object = $(this);
var rowvalue = object.attr('id');
var rowvalue_array = rowvalue.split('_');
var id = rowvalue_array[1];
var comment = $('#comment_'+id).val();
var divname = '#'+id;
var varData = 'id='+id+'&comment='+comment;
console.log(varData);
$.ajax ({
type: "POST",
url: "edit_field.php",
data: varData,
success: function(data) {
$("divname").html(data);
}
});
return false;
});
Use the following code..
$.ajax ({
type: "POST",
url: "edit_field.php",
data: varData,
success: function(data) {
$(divname).html(data);
}
});
Please replace your line as below :
$(divname).html(data);
remove quata (")
divname is variable
or you can use as below :
$("#"+id).html(data);
Try this:
$.ajax ({
type: "POST",
url: "edit_field.php",
data: varData,
success: function() {
$("divname").html($(this).data);
}
});
Why are you accessing the element by id when u have the element.....try
$(object).html(data);

Retrieving serialize data in a PHP file called using AJAX

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.

Categories