Post php form jquery ajax - php

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));
}

Related

sending array via ajax to 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.

Magento Ajax Request - how to correctly pass data?

Since couple of weeks(two) started my adventure with Magento. So far I've learned a little but have a problem how to send data using Ajax (jQuery).
$(document).ready(function(){
var total = $(this).find(\"input[class=tramp]:checked\").length;
$(\".caret input[type='checkbox']\").change(function(){
if($(this).is(':checked')){
var value= true;
}else{
var value = false;
}
var brand = $(this).data('brand');
data = {brand: brand, value: value}
$.ajax({
data: data,
url: 'checkbox/ajax/index',
method: 'POST',
success: function(result){
console.log(data, total);
}});
});
});
This is my Ajax, so as you can see trying to send brand and value. AjaxController.php looks like this:
class Amber_Checkbox_AjaxController extends Mage_Core_Controller_Front_Action {
public function indexAction()
{
$brand = Mage::app()->getRequest()->getPost('brand', 'value');// not sure or I should use data?
if($brand )
{
....
$this->getResponse()->setBody($brand);
echo $brand;
...
}
}
}
remove \"
$(document).ready(function(){
var total = $(this).find("input[class=tramp]:checked").length;
$(".caret input[type='checkbox']").change(function(){
if($(this).is(':checked')){
var value= true;
}else{
var value = false;
}
var brand = $(this).data('brand');
data = {brand: brand, value: value}
$.ajax({
data: data,
url: 'checkbox/ajax/index',
method: 'POST',
success: function(result){
console.log(data, total);
}});
});
});
remove \", $ replace with jQuery and pass absolute URL Mage::getUrl('checkbox/ajax/index');
$.ajax({
data: data,
url: '<?php echo Mage::getUrl("checkbox/ajax/index"); ?>',
method: 'POST',
success: function(result){
console.log(data, total);
}});

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 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