sending array via ajax to php - php

I want to send an array of ids for the checked checkboxes via ajax to PHP. I keep getting Undefined array key "progid". when I alert the progid in jQuery I got the correct ids. I know it is duplicated question but I really searched a lot and tried a lot of solutions nothing works.
html code:
while($row3 = $result3->fetch_assoc()) {
$courseName = $row3['courseName'];
$coursePrice = $row3['coursePrice'];
$courseId = $row3['id'];
$programList .= ' <div class="form-check">
<input type="checkbox" name="course[]" class="form-check-input" id="'.$courseId.'" value="'.$coursePrice.'">
<label class="form-check-label" for="'.$coursePrice.'">'.$courseName .' price is '.$coursePrice.'$</label>
</div>';
}
echo $programList;
jQuery code:
$('#submit').click(function() {
var progid = [];
$.each($("input[name='course[]']:checked"), function(){
progid.push($(this).attr("id"));
});
$.ajax({
type: "POST",
url: "test.php",
data: progid,
success: function(data){
console.log('success: ' + progid);
}
});
});
php code:
<?php
extract($_POST);
print_r($_POST);
echo ($_POST["progid"]);
?>
Edit:
when I send the data to the same page it does work and displays the array inside a span , but when I send it to another PHP file it doesn't work it displays the error.

Because you didn't post all the html, is it possible that your submit event is not disabled with event.preventDefault(); and the ajax is not executing?
$('#submit').click(function(e) {
e.preventDefault();
..
https://api.jquery.com/event.preventdefault/
$.ajax({
type: "POST",
url: "test.php",
data: {"progid" : progid},
success: function(data) {
console.log('success: ' + progid);
}
});

You can use JSON.stringify() for the array:
$(document).ready(function () {
$('#submit').click(function(e) {
e.preventDefault();
var progid = [];
$.each($("input[name='course[]']:checked"), function(){
progid.push($(this).attr("id"));
});
let stringifyProgid = JSON.stringify(progid);
$.ajax({
type: "POST",
url: "test.php",
data: {progid: stringifyProgid},
success: function(data){
console.log('success');
}
});
});
});
And in PHP you can get the array:
<?php
$arrProgid = json_decode($_POST["progid"]);
var_dump($arrProgid);
?>

I often do this with Multi Select form fields.
var progid = [];
$.each($("input[name='course[]']:checked"), function(){
progid.push($(this).attr("id"));
});
$.ajax({
type: "POST",
url: "ajax_post.php",
data: {
'progid[]': progid
},
success: function(data) {
}
});
Then on the PHP system the $_POST['progid'] will be an array. So all the JSON encoding and decoding others have posted is not needed.

Related

AJAX not being called when select box changed

I am using jquery to call a PHP script when a select box changes. I am able to get the ID of the select item that changes, however I get no output from the PHP script. The Javascript is
function initagents() {
$('select.agent').on('change', function() {
var id = $(this).attr("id");
console.log(id);
var data = { id: id };
$.ajax({
type: "POST",
dataType: "json",
url: "updateagent.php",
data: data
}).done(function(msg) {
console.log(msg);
});
});
}
and the PHP is
print_r ( $_POST);
Any ideas?
Please use
echo json_encode($_POST['id']);
instead of
print_r($_POST);
You have made a mistake by placing the onChange event of the select box inside function initagents().
fixed code:
$('select.agent').on('change', function() {
var id = $(this).attr("id");
console.log(id);
var data = {
id: id
};
$.ajax({
type: "POST",
dataType: "json",
url: "updateagent.php",
data: data
}).done(function(msg) {
console.log(msg);
});
});
Just try with the following code:
function getID(val) {
alert(val);
$.ajax({
type: 'POST',
url: 'post.php',
data: {
id: val
},
success: function(data) {
alert(data);
}
});
}
<select name="pks" onchange='getID(this.value);'>
<option value="1">Option1</option>
<option value="2">Option2</option>
</select>
Seems your code is correct and it should send the data to php file. But also I see that, you are not sending selected value to php script. You are posting selected element ID.
Are you trying this in a sub folder ? make sure the php file path is correct in javascript. Better if you can try with the full path. For example
url: "http://localhost/myproject/updateagent.php",

Post php form jquery ajax

i have form with input field generated from loop, ie
<form name="" method='post' action=''>
<?php
for($i=0;$i<10;$i++){
echo "<input type='text' name='data[]' class='data_cls' value='".$i."'>";
}
?>
<input type='submit' id='btn' value='save'>
i want to submit the form using jquery ajax.
$('.btn').click(function(){
var datString = "HOW TO GET THESE VALUES";
$.ajax({
url: "data_process.php",
type: "post",
data: dataString,
success: function(data) {
alert('OK');
}
});
});
You can use .serialize() jQuery method to get the form data. Like this,
$('.btn').click(function(){
var dataString = $('#FORM_ID').serialize();
//replace FORM_ID with the ID of the form.
$.ajax({
url: "data_process.php",
type: "post",
data: dataString,
success: function(data) {
alert('OK');
}
});
});
Try this:
var datString = "";
$(".data_cls")
.map(function () {
datString += $(this).val();
})
.get();
Try
var Data = {};
$('input[name=data]').each(function(i) {
Data[i] = $(this).val();
});
I think you have forgot to bind parameter in data ajax post
$('.btn').click(function(){
var datString = "'HOW TO GET THESE VALUES'";
$.ajax({
url: "data_process.php",
type: "post",
data: "'USERPARAMETR' : " dataString,
success: function(data) {
alert('OK');
}
});
});
If you not use parameter in data_process.php page. Please use it.
Please update and check
First give the form an ID or class i.e. form
<form name="" method='post' action='' id='form'>...
Then you may capture all inputs from the from using the general serialize method
<script type="text/javascript">
$(document).on("click", ".btn", function(e) {
e.preventDefault();
var datastring = $("#form").serialize();
{
$.ajax({
url: "data_process.php",
type: "post",
data: dataString,
...
And on the PHP page you will receive the data as posted
$values = $_POST['data'];
$N = count($values);
for($i=0; $i < $N; $i++)
{
$currentvalue = $values[$i];
//now this value will loop and you will do with it the way you want to
//For example
$save = mysqli_query($link, "UPDATE table SET `column` = '$currentvalue' WHERE ...") or die(mysqli_error($link));
}

refresh div after sending data to db

i have a div that shows the total sum of some products:
<div class="total-price"><?php echo (!empty($cart)) ? $cart['total'] : '0'; ?> $</div>
with ajax, i'm adding products to cart ... se the page is not reloading.
How to refresh the div after I add the product to cart?
The ajax that i'm using:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
$(".total-price").something...;
}
});
})
</script>
Thank you!
You can do something like this:
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
data: $(this).serialize(),
success: function () {
$(".success-message").slideDown().delay(5000).slideUp();
var oldPrice = $('.total-price').text() * 1;
var itemPrice = "15"; //the price that should be added
$('.total-price').text(oldPrice + itemPrice);
}
});
})
</script>
You should be returning a total basket value from your /tdt/order path.
In the PHP script you should echo some JSON data with all the required information, for example
echo json_encode(array("totalPrice" => "£10.01"));
Then you need to parse this information into your Javascript and update the pages elements;
<script>
$('#order-to-cart').submit(function (e) {
e.preventDefault();
$.ajax({
type: 'post',
url: '/tdt/order',
dataType: 'json',
data: $(this).serialize(),
success: function (data) {
$(".success-message").slideDown().delay(5000).slideUp();
$('.total-price').val(data.totalPrice);
}
});
})
</script>
The above ajax request will expect the data returned to be JSON, you will then use this to update the total-price element.
You can use something like angularjs or knockoutjs - for angular you would update your model - for knockout you would use the self.object.push(value) i.e.,
function OrderViewModel() {
var self = this;
self.myOrder = ko.observableArray([]);
self.addOrderItem = function () {
$.ajax({
type: "post",
url: "yourURL",
data: $("#YOURFORMFIELDID").serialize(),
dataType: "json",
success: function (value) {
self.myOrder.push(value);
},
headers: {
'RequestVerificationToken': '#TokenHeaderValue()'
}
});
}
}
ko.applyBindings(new orderViewModel());
</script>
</pre>

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
}

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