passing looping data through ajax data - javascript

My form contains hidden input looping.
in my case, i declare the hidden input in ajax data manually without looping.
so how to loop them in ajax data?
here's my form script
<form method="POST" name="myform">
<?php for($i=1;$i<=5;$i++) { ?>
<input type="hidden" name="data<?php echo $i; ?>" value="data<?php echo $i; ?>">
<?php } ?>
<input type='button' name='submitData' value='Submit' onClick='submitData();'>
</form>
here's my Ajax script
function submitData() {
var form = document.myform;
$.ajax({
url: 'process.php',
type: 'post',
data: {
data1 : form["data1"].value,
data2 : form["data2"].value,
data3 : form["data3"].value,
data4 : form["data4"].value,
data5 : form["data5"].value
},
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
}

Your hidden inputs have name and values,
use .serialize()
Encode a set of form elements as a string for submission
data : $('form[name=myform]').serialize()
This will return name=value pairs.
If you need {name:value}, use .each()
var formData = {}
$('form :input:hidden[name^="data"]').each(function(){
formData[this.name] = this.value;
});
And in ajax,
data : formData ,
Demo

If you're posting the whole form, you can use jQuery's .serialize() directly in your request:
$.ajax({
url: 'process.php',
type: 'post',
data: $('#myform').serialize(),
...

Also, a good way to do it is to convert the string to JSON object, and in PHP convert the string in an array:
var dataJSON = JSON.stringify({..Your form obj...});
$.ajax({
url: 'process.php',
type: 'post',
data: dataJSON,
success: function (result) {
console.log(result);
},
error: function () {
console.log("error");
}
});
process.php
$data = json_decode($_POST["data"]);
print_r($data);

Related

Passed the variable through javascript but not getting it in php?

i am passing my variable throught an AJAX request in javascript but not getting it in my php file. NOt sure where i am going wrong.?
JS code
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",});
PHP code
<?php
$module_c = $_POST['data'];
echo $module_c;
?>
You have to get the data by the name of the variable you want to get, which is m_count.
<?php
$module_c = $_POST['m_count'];
echo $module_c;
?>
EDIT:
Like suggested in the comments, change your JavaScript code to:
var build = {
m_count : (document.getElementById('count').value)
}
$.ajax({
data: build,
type: "POST",
url: "tabs.php",
success: function(data) {
alert(data);
}
});
PHP:
<?php
$module_c = $_POST['m_count'];
echo $module_c;
?>
JS:
var build = {
m_count : (document.getElementById('count').value),
}
$.ajax({
url: 'php/server.php',
type: 'POST',
data: build,
})
.done(function(msg) {
// JSON.parse turns a string of JSON text into a Javascript object.
var message = JSON.parse(msg);
alert(message);
}
})
.fail(function(err) {
console.log("Error: "+err);
})
.always(function() {
console.log("Complete");
})
;

Ajax upload not working codeigniter

I am using codeigniter 3.1 . I want to post upload data using ajax.
Ajax upload file not working. But when i post the simple form without ajax, it working fine.
I don't know why but no error in console.
HTML
<?php echo form_open_multipart(site_url("upload/post"), ['id' => 'uploader']) ?>
<input type="file" name="userfile" value="">
<input type="submit" value="Submit" />
<?php echo form_close() ?>
JAVASCRIPT
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this)
});
});
CONTROLLERS
public function post()
{
$this->load->helper('url');
$this->load->helper('form');
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE
));
$this->upload->do_upload('userfile');
$data = $this->upload->data();
$image_file = $data['file_name'];
}
Another approach to this would be passing to PHP the file encoded in base64:
get the selected file from #userfile field using $('#userfile').prop('files')[0];
transform the contents of that file into a base64 encoded string using FileReader.readAsDataURL(). We're going to call this content; Here's a similar question showing how to do and expanding the answer & possibilities;
send the AJAX passing both the filename and content strings;
now on CI, fetch the POST data;
base64_decode() the content;
fwrite() the result into a file using the filename.
That way also you could avoid POSTing all form fields.
try this..
Post data using FormData() formdata post file also.
To get all your form inputs, including the type="file" you need to use FormData object.
$('#post').on('click', function (e) {
var file_data = $("#userfile").prop("files")[0];
var form_data = new FormData();
form_data.append("userfile", file_data)
$.ajax({
url: window.location.href+'/post',
type: 'POST',
data: form_data,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
For more...https://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
One of the issues is that file uploading uses a different mechanism than the other form <input> types. That is why $this->input->post("userfile") isn't getting the job done for you. Other answers have suggested using javascript's FormData and this one does too.
HTML
A very simple form for picking a file and submitting it. Note the change from a simple button to <input type="submit".... Doing so makes it a lot easier for the javascript to use the FormData object.
FormData documentation
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://code.jquery.com/jquery-2.2.2.js"></script>
<title>Upload Test</title>
</head>
<body>
<?= form_open_multipart("upload/post", ['id' => 'uploader']); ?>
<input type="file" name="userfile">
<p>
<input type="submit" value="Upload">
</p>
<?php echo form_close() ?>
<div id="message"></div>
<script>
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
</script>
</body>
</html>
JAVASCRIPT
Use FormData to capture the fields.
Note that instead of handling the button click we handle the submit event.
$('#uploader').submit(function (event) {
event.preventDefault();
$.ajax({
url: window.location.href + '/post',
type: "POST",
dataType: 'json',
data: new FormData(this),
processData: false,
contentType: false,
success: function (data) {
//uncomment the next line to log the returned data in the javascript console
// console.log(data);
if (data.result === true) {
$("#message").html("<p>File Upload Succeeded</p>");
} else {
$("#message").html("<p>File Upload Failed!</p>");
}
$("#message").append(data.message);
}
});
});
CONTROLLER
I've added some code that "reports" results to ajax and will display it on the upload page.
class Upload extends CI_Controller
{
public function __construct()
{
parent::__construct();
$this->load->helper(['form', 'url']);
}
public function index()
{
$this->load->view('upload_v');
}
public function post()
{
$this->load->library("upload");
$this->upload->initialize(array(
"upload_path" => './uploads/',
'allowed_types' => 'gif|jpg|png|doc|txt',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$successful = $this->upload->do_upload('userfile');
if($successful)
{
$data = $this->upload->data();
$image_file = $data['file_name'];
$msg = "<p>File: {$image_file}</p>";
$this->data_models->update($this->data->INFO, array("image" => $image_file));
} else {
$msg = $this->upload->display_errors();
}
echo json_encode(['result' => $successful, 'message' => $msg]);
}
}
This will upload your file. Your work probably isn't done because I suspect that your are not saving all the file info you need to the db. That, and I suspect you are going to be surprised by the name of the uploaded file.
I suggest you study up on how PHP handles file uploads and examine some of the similar codeigniter related questions on file uploads here on SO.
Controller
public function upload()
{
$this->load->library('upload');
if (isset($_FILES['myfile']) && !empty($_FILES['myfile']))
{
if ($_FILES['myfile']['error'] != 4)
{
// Image file configurations
$config['upload_path'] = './upload/';
$config['allowed_types'] = 'jpg|jpeg|png';
$this->upload->initialize($config);
$this->upload->do_upload('myfile');
}
}
}
View
<form id="myform" action="<?php base_url('controller/method'); ?>" method="post">
<input type="file" name="myfile">
("#myform").submit(function(evt){
evt.preventDefault();
var url = $(this).attr('action');
var formData = new FormData($(this)[0]);
$.ajax({
url: url,
type: 'POST',
data: formData,
processData: false,
contentType: false,
success: function (res) {
console.log(res);
},
error: function (error) {
console.log(error);
}
}); // End: $.ajax()
}); // End: submit()
Let me know if any query
you need to submit the form not on click but on submit ... give the form an id and then on submit put ajax
HTML
<?php $attributes = array('id' => 'post'); ?>
<?php echo form_open_multipart(site_url("upload/post",$attributes), ?>
<input type="file" id="userfile" name="userfile" value="">
<button id="post">Submit</button>
<?php echo form_close() ?>
JAVASCRIPT
$('#post').on('submit', function () {
var formData = new FormData();
formData.append("userfile",$("#userfile")[0].files[0]);
$.ajax({
url: window.location.href+'/post',
type: "POST",
data: formData
});
CONTROLLERS
public function post()
{
$this->load->library("upload");
$file = $this->common->nohtml($this->input->post("userfile"));
$this->upload->initialize(array(
"upload_path" => 'upload',
"overwrite" => FALSE,
"max_filename" => 300,
"encrypt_name" => TRUE,
));
$data = $this->upload->data();
$image_file = $data['file_name'];
$this->data_models->update($this->data->INFO, array(
"image" => $image_file
)
);
}

AJAX jquery json sending array to php

I'm trying to send a associative array via AJAX $.post to php. Here's my code:
var request = {
action: "add",
requestor: req_id,
...
}
var reqDetails = $("#request_details").val();
switch(reqDetails){
case 1:
request[note] = $("#note").val();
break;
...
}
if(oldRequest()){
request[previousID] = $("old_id").val();
}
$('#req_button').toggleClass('active');
$.post("scripts/add_request.php", {
request_arr: JSON.stringify(request)
}, function(data){
console.log(data);
$('#req_button').toggleClass('active');
}, 'json');
And i'm simply trying to read the received data in my php script:
echo json_decode($_POST["request_arr"]);
But it's not working. I'm a newbie to js, I can't figure out what I'm doing wrong.
Check below link for your reference
Sending an array to php from JavaScript/jQuery
Step 1
$.ajax({
type: "POST",
url: "parse_array.php",
data:{ array : JSON.stringify(array) },
dataType: "json",
success: function(data) {
alert(data.reply);
}
});
Step 2
You php file looks like this:
<?php
$array = json_decode($_POST['array']);
print_r($array); //for debugging purposes only
$response = array();
if(isset($array[$blah]))
$response['reply']="Success";
else
$response['reply']="Failure";
echo json_encode($response);
Step 3
The success function
success: function(data) {
console.log(data.reply);
alert(data.reply);
}
You are already using "json" as dataType, so you shouldn't apply 'stringify' operation on your data.
Instead of request_arr: JSON.stringify(request), can you try request_arr: request directly?

php Uploading multiple files with ajax

I've managed to upload multiple files using my current php and html form and wanted to fancy it up a bit with some ajax and automatically submitting the form. I've hidden the 'file' input and submit button so the form is handeled by the js (mentioning this incase it may affect form submission, form does submission and I've checked via HTTP headers). The ajax section of my js is what I normally use for ajax and standard forms, however when i submit the form my $_FILES is empty so I guess I'm not using the ajax correctly here? What do I need to change in my ajax to handle file uploads?
$("#add_button").click(function(e)
{
e.preventDefault();
$("#folder_open_id").trigger("click");
$("#folder_open_id").change(function()
{
$("#folder_upload").submit();
});
});
$("#folder_upload").submit(function(event)
{
var formdata = $(this).serialize();
event.preventDefault();
$.ajax
({
url: "index.php",
type: "POST",
data: formdata,
success: function(response) { $("#response_div").html(response); },
error: function(response) { alert(response); }
});
});
php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
if(!empty($_FILES['files']['name'][0]))
{
$files = $_FILES['files'];
define('CPATH', $_SERVER['DOCUMENT_ROOT'] . "/uploads/");
$uploaded = array();
foreach($files['name'] as $position => $file_name)
{
$file_temp = $files['tmp_name'][$position];
$file_new = "./uploads/" . $files['name'][$position];
if(move_uploaded_file($file_temp, $file_new))
echo "success";
else
echo "fail, temp: " . $file_temp . " new: " . $file_new;
}
}
else
echo '<pre>', print_r($_POST, 1), '</pre>';
}
so empty($_FILES['files']['name'][0]is returning true and the print_r($_POST) is empty it seems.
html form
<form id="folder_upload" action="" method="post" enctype="multipart/form-data">
<input type="file" class="hide" name="files[]" id="folder_open_id" multiple directory webkitdirectory mozdirectory/>
<input type="submit" class="hide" value="upload" id="folder_open_upload" />
</form>
Here is my js after Mephoros answer, my $_FILES array still seems to be empty:
$.ajax
({
url: "index.php",
type: "POST",
data: new FormData($(this)),
processData: false,
contentType: 'multipart/form-data; charset=UTF-8',
success: function(response) { $("#response_div").html(response); },
error: function(response) { alert(response); }
});
Based on some preliminary research, utilize FormData and set processing and contentType to false.
$.ajax({
// ...
data: new FormData($(this)),
processData: false,
contentType: false,
// ...
});
Sources:
http://portfolio.planetjon.ca/2014/01/26/submit-file-input-via-ajax-jquery-easy-way/
http://abandon.ie/notebook/simple-file-uploads-using-jquery-ajax
See: http://api.jquery.com/jquery.ajax/
See: https://developer.mozilla.org/en-US/docs/Web/Guide/Using_FormData_Objects

Send array with ajax request to php

I created array like this ["9", "ques_5", "19", "ques_4"]. Now I want to send it from JS to PHP but I'm not getting proper results. My JS code is:
$(".button").click(function(e) {
e.preventDefault();
$.ajax({
type : 'post',
cache : false,
url : 'test/result.php',
data : {result : stuff},
success: function(resp) {
alert(resp);
}
});
});
In the above code stuff is an array which contains records. How can I send this array with above code and then in PHP I want to process this array like ques_5 is the key and 9 become the value for that key.
You can pass the data to the PHP script as a JSON object. Assume your JSON object is like:
var stuff ={'key1':'value1','key2':'value2'};
You can pass this object to the php code in two ways:
1. Pass the object as a string:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : {result:JSON.stringify(stuff)},
success : function(response) {
alert(response);
}
});
You can handle the data passed to the result.php as :
$data = $_POST["result"];
$data = json_decode("$data", true);
//just echo an item in the array
echo "key1 : ".$data["key1"];
2. Pass the object directly:
AJAX call:
$.ajax({
type : 'POST',
url : 'result.php',
data : stuff,
success : function(response) {
alert(response);
}
});
Handle the data directly in result.php from $_POST array as :
//just echo an item in the array
echo "key1 : ".$_POST["key1"];
Here I suggest the second method. But you should try both :-)
If you want to send key value pairs, which is what I am seeing, it would be better to use a PHP JSON library (like this one... http://php.net/manual/en/book.json.php)
Then you can send actual key value pairs, using JSON format like...
{"ques_5" : "19", "ques_4": "19"}
Try this
var array = ["9", "ques_5", "19", "ques_4"];
console.log(array.join(","));
above code will output string with comma separated like 9,ques_5,19,ques_4then paste it to ajax call.
And then in php explode that string.
Other possible solutions.
First
var obj = { 'item1': 'value1', 'item2': 'value2' };
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : JSON.stringify(obj) },
success: function(resp)
{
alert(resp);
}
});
Second
var a = $.JSON.encode(obj);
$.ajax(
{
type: 'post',
cache: false ,
url: 'test/result.php',
data: { result : a },
success: function(resp)
{
alert(resp);
}
});
In PHP File
<?php
$json = $_POST["data"]
var_dump(json_decode($json));
?>
You can send the array in json format to the php and then use json_decode function to get back the array like
In ajax call you have to send json for that you need to first make array of the values so that you get it in right form
so that you json look like {"ques_5":"9","ques_4":19}
and use in ajax call
data: JSON.stringify(`your created json`),
contentType: "application/json; charset=utf-8",
dataType: "json",
IN PHP it look like
<?php
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
var_dump(json_decode($json));
?>
I would like to share a complete example that works for me in order to avoid making each JavaScript function for each PHP function
// on the HTML side a simple JavaScript call from a link
<a href="javascript:CargaZona('democonllamada', 'tituloprin', {'key1':'value1','key2':'value2'})" >test</a>
<div id='tituloprin' >php function response here!</div>
// on JavaScript side
function CargaZona(fc, div, params) {
var destino = "#" + div;
var request = $.ajax({
url : "inc/phpfunc.php",
type : "POST",
data : {
fc : fc,
params : JSON.stringify(params)
},
dataType : "html"
});
request.done(function (msg) {
$(destino).html(msg);
});
request.fail(function (jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
}
// on phpfunc.php page
<?php
$params = "{'key1':'value1','key2':'value2'}";
$fc = 'def';
if (isset($_POST['fc'])) { $fc = $_POST['fc']; }
if (isset($_POST['params'])) { $params = $_POST['params']; }
switch ($fc) {
default:
call_user_func($fc,$params);
}
function democonllamada($params) {
$params = json_decode("$params", true);
echo "ok llegaron".$params['key1'];
}
?>

Categories