I have my json being passed to the php file as follows.
JAVASCRIPT
$.ajax({
url: "/gallerytest/getimages.php",
type: "POST",
dataType: "json",
data: {
imagesArray: imageArray.itemList,
action: "load"
},
success: function(imagesArray) {
for (var i = 0; i < imagesArray.length; i++) {
console.log('image ' + imagesArray[i]["src"]);
}
}
});
With the imagesArray being captured in the php file, I want to put it into an array. In my php I have this so far:
PHP
if(isset($_POST['action']) && !empty($_POST['action'])) {
$action = $_POST['action'];
switch($action) {
case "test" : test();break;
case "load" : load();break;
// ...etc...
}
}
function load(){
$imagesArray = $_POST['imagesArray'];
$images = json_decode($imagesArray, true);
$imagesArr = array();
for ($i = 0; $i < count($images); $i++){
$image = array(
"src" => $images[$i]
);
$imagesArr[] = $image;
}
echo json_encode($imagesArr);
}
I am passing the array back for testing purposes where the javascript outputs the src of each element.
The ultimate goal which I would like help on too, should it not go beyond the call of duty, is in an SQL statement capture more images where the src does not match.
In essence:
SELECT * FROM images WHERE id_image NOT IN (imagesArray) ORDER BY rand() LIMIT 12
$.ajax({
url: "/gallerytest/getimages.php",
type: "POST",
dataType: "json",
data: {
"imagesArray": imageArray.itemList,
"action": "load"
},
success: function(imagesArray) {
for (var i = 0; i < imagesArray.length; i++) {
console.log('image ' + imagesArray[i]["src"]);
}
}
});
Please Pass the action and imagesArray tag in double quote
Related
I have an Dynamic HTML table I am simply calling the id using JavaScript, looping through the data and capturing the cell values.
Question- How do I take this data POST it to test save.php page to insert the entire table into my MySQl db ?
var table = document.getElementById('table'),
rows = table.getElementsByTagName('tr'),
i, j, cells, OS_d,roleApp_d,Men_d,vcpu_d,Val_d,Per_d,hw_d ;
for (i = 1, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue;
}
OS_d = cells[1].firstChild.value;
roleApp_d = cells[2].firstChild.value;
vcpu_d = cells[3].firstChild.value;
Men_d = cells[4].firstChild.value;
Val_d = cells[5].firstChild.value;
Per_d = cells[6].firstChild.value;
hw_d = cells[7].firstChild.value;
}
--- Section where assistance is required
$.ajax({
type: "POST",
url: 'Save.php',
data: ({data:OS_d, roleApp_d, vcpu_d, Men_d, Val_d, Per_d, hw_d}),
success: function(data) {
alert(data);
}
});
PHP Side Save.php
<?php
$test = $_POST['data'];
echo $test;
?>
Just quick code, not tested it so your post data should be like this:
var table = document.getElementById('table'),
rows = table.getElementsByTagName('tr'),
i, j, cells, OS_d,roleApp_d,Men_d,vcpu_d,Val_d,Per_d,hw_d ;
var p_row = '[';
for (i = 1, j = rows.length; i < j; ++i) {
cells = rows[i].getElementsByTagName('td');
if (!cells.length) {
continue;
}
p_row += "{";
p_row +='"OS_d":"'+cells[1].firstChild.value+'",';
p_row +='"roleApp_d":"'+ cells[2].firstChild.value+'",';
p_row +='"vcpu_d":"'+ cells[3].firstChild.value+'",';
p_row +='"Men_d":"'+ cells[4].firstChild.value+'",';
p_row +='"Val_d":"'+ cells[5].firstChild.value+'",';
p_row +='"Per_d":"'+ cells[6].firstChild.value+'",';
p_row +='"hw_d":"'+ cells[7].firstChild.value+'"';
p_row += '},';
}
p_row = (p_row).replace(new RegExp("[,]+$"), "");
p_row += ']';
var formData = new FormData();
formData.append('data',p_row);
fetch("/save.php", {
method: "POST",
body: formData
}).then(function (response) {
console.log(response);
}).catch(function (error) {
console.error(error, "code: " + error.status);
});
I figured it out so I decided to share to the community. Thanks for the support.
$.ajax({
type: "POST",
url: 'test.php',
data: {p_row : p_row },
success: function(data){
alert(data);
}
});
}
On the test.php side
<?php
$data = false;
if(isset($_POST['p_row'])){
$data = $_POST['p_row'];
}
echo 'Received Data: ' . $data ;
//$conn->close();
?>
This is my ajax call
function exportCSV(){
var sampleid = $("#sampleid").val();
var scheme = $("#scheme").val();
var v = $("#v").val();
var date = $("#date").val();
var assignedvalue = $("#assignedvalue").val();
var units = $("#units").val();
var assayvalue = $("#assayvalue").val();
var analyte = $("#analyte").val();
var filename=$("#filename").val();
var sample_error=$("#sample_error").val();
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>" + "import/validate_file",
dataType: 'json',
data: {
sampleid: sampleid,
scheme: scheme,
v: v,
date: date,
assignedvalue: assignedvalue,
units: units,
assayvalue: assayvalue,
analyte: analyte,
filename:filename,
sample_error: sample_error
},
success: function (data) {
console.log(data); //as a debugging message.
}
});
}
and this is my controller
<?php
if (!empty($unit_check) and !empty($analyt) and !empty($sch) and count($sample_id) == count(array_unique($sample_id)) and $assigned_check == '1' and $assay_check == '1') {
for ($row = 2; $row <= $lastRow; $row++) {
$data['sample_id'] = $worksheet->getCell($sampleid . $row)->getValue();
$data['scheme'] = $worksheet->getCell($scheme . $row)->getValue();
$data['v'] = $worksheet->getCell($v . $row)->getValue();
$data['units'] = $worksheet->getCell($unit . $row)->getValue();
$data['date'] = $worksheet->getCell($date . $row)->getFormattedValue();
$data['assay_value'] = $worksheet->getCell($assayvalue . $row)->getValue();
$data['assigned_value'] = $worksheet->getCell($assignedvalue . $row)->getValue();
$data['analyte'] = $worksheet->getCell($analyte . $row)->getValue();
$data['trace_id'] = $insert_id;
$this->import_model->insert_data($data);
$response['success'] = true;
}
} else {
$data['sample_id'] = '';
$data['analyte'] = '';
$data['unit_check'] = '';
$data['sch'] = '';
$data['assigned_value'] = '';
$data['assay_value'] = '';
if (count($sample_id) != count(array_unique($sample_id))) {
$data['sample_id'] = '1';
}
if (empty($analyt)) {
$data['analyte'] = '1';
}
if (empty($unit_check)) {
$data['unit_check'] = '1';
}
if (empty($sch)) {
$data['sch'] = '1';
}
if ($assigned_check == '') {
$data['assigned_value'] = '1';
}
if ($assay_check == '') {
$data['assay_value'] = '1';
}
$data['file_name'] = '';
}
?>
I have to show the errors and success message on ajax call.
Right now I'm succeeded in valuating the data and putting it in the database.
But I want to show the success message at the end of the page by clicking the submit button.
And if there is validations error it must shows the errors in that fields at the end of the page
Any help would be appreciated.
Here inside your success method of ajax
success: function (data) {
$("#resultDiv").html(data)
}
Return some real data from your controller in both case success and failed. and based on your data inside success method show your message.
Like:
success: function (data) {
$("#resultDiv").html(data.success) //this requires string to convert your result in string if neccessary
//But you should return a JSON data as msg from your controller
}
You should put a result HTML element for example:
<div id='resultDiv'></div> <!-- to match with #resultDiv -->
Put response data in both condition if success=true and else success=false
In your controller
if(.....){
//what ever check you wanna do
..........
..........
$response['msg']='success';
header('Content-Type', 'application/json');
echo json_encode($response);
}
else{
$response['msg']='failed';
header('Content-Type', 'application/json');
echo json_encode($response);
}
In your ajax
success: function (data) {
$("#resultDiv").html(data.msg)
}
Try something like:
$response = array(
'errCode' = 0,
'errMsg' = 'msg'
);
return this kind of array by json_encode() from php to ajax() call and use it in ajax() success like:
var data = JSON.parse(response);
alert(data.errMsg);
You can also put a check on errCode like:
if(errCode == 0) { something }
if(errCode == 1) { something }
I am trying to display multiple images coming from a remote server on a single page, the page is a html file where putting php blocks wouldn't be doing anything to get thing I want
Using PHP version 5.6, the code for the php is
$dir = "uploads/image/dashed/";
$files = scandir($dir);
foreach ($files as $file)
{
if ( is_file($dir. $file) ){
echo $file;
}
}
the ajax response code is:
$(document).ready(function(){
$.ajax({
async: true,
type: 'POST',
url: 'folder.php',
success: function(data){
$("#imageContent").html(data).append("<br/>");
var images = data.split("\n");
for (var i = 0, j = images.length; i < j; i++){
$("#imageContent").append("<img src='uploads/image/dashed/" + images[i] + "' width='300'>");
}
}
});
});
all I keep getting from the server is
1354876944ABF.jpg_MG_0085.jpg
and an empty image place holder (not two, just the one) for where the image
and the image address is showing two image names stuck together in one link
uploads/image/dashed/1354876944ABF.jpg_MG_0085.jpg
where the response link should be on two (for this example) different lines and images where the <img> is on the html inside the ajax call
Try This,
$dir = "uploads/image/dashed/";
$files = scandir($dir);
$i = 1;
$count = count($files);
foreach ($files as $file){
if(is_file($dir. $file)){
if($i == $count){
echo $file;
}else{echo $file.'|||';
}
}
$i++;}
and change ajax to:
$(document).ready(function(){
$.ajax({
async: true,
type: 'POST',
url: 'folder.php',
success: function(data){
$("#imageContent").html(data).append("<br/>");
var images = data.split("|||");
for (var i = 0, j = images.length; i < j; i++){
$("#imageContent").append("<img src='uploads/image/dashed/" + images[i] + "' width='300'>");
}
}
});
});
thats using ||| as a delimiter.
EDIT: now it should work properly,
EDIT2: changed $i = 0 order, added $i++; at the end
scandir() is already giving you an array, so why not just json_encode it and return this? unset() any output that is not a valid file:
$files = scandir($dir);
$count = count($files);
for($i = 0; $i < $count; $i++) {
if ( !is_file($dir. $file) ){
unset($files[$i]);
}
}
echo json_encode($files);
then in your success block:
success: function(data){
$("#imageContent").html(data).append("<br/>");
var i,
json = JSON.parse(data);
for (i in json){
$("#imageContent").append("<img src='uploads/image/dashed/" + json[i] + "' width='300'>");
}
}
I have music file to upload on database
and from view side I have addmore button for music input type file and I got that music's name like:
music1.mp3,music2.mp3,music3.mp3
After that I explode this above on controller file.
I don't know, is this correct?
$expaudio = explode(',',$audio);
$audioCount = count($expaudio);
if($audioCount == 0){ $audiolist = $audio; }
else{ $audiolist = $expaudio; }
for($i=0; $i<$audioCount; $i++){
//******************************* UPLOAD MUSIC ********************************//
$config['allowed_types'] = 'avi|mpeg|mp3|mp4|3gp|wmv'; //video and audio extension
$config['max_size'] = '40000000';
$config['overwrite'] = FALSE;
$config['remove_spaces'] = TRUE;
//$video_name = random_string('numeric', 5);
$characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
$randomString = '';
for ($i = 0; $i < 10; $i++) {
$randomString .= $characters[rand(0, strlen($characters) - 1)];
}
$video_name = $randomString;
$config['file_name'] = $video_name;
$config['upload_path'] = 'Users/'.$data['loginuserpage'].'/music/'.$project_url.'/audio';
//$config['allowed_types'] = 'gif|jpg|jpeg|png|doc|docx|ppt|pptx|pdf|txt|avi|mpeg|mp3|mp4|3gp|wmv'; // Image , video and audio
$this->load->library('upload', $config);
if (!$this->upload->do_upload($audiolist[$i]))
{
$error = array('error' => $this->upload->display_errors());
$vid_url = '';
print_r($this->upload->display_errors());
}
else
{
$upload_data = $this->upload->data();
$aud_name = $upload_data['file_name'];
$aud_type = $upload_data['file_type'];
$aud_url = $baseurl.$config['upload_path']."/".$aud_name;
}
//******************************* UPLOAD MUSIC ********************************//
}
My Ajax file
$("input[name='audio[]']").change(function()
{
var temp =[]
$("input[name='audio[]']").each(function(i, selected){
texts = $(selected).val()
temp.push(texts);
var jcat1 = temp.join(",");
alert(jcat1);
$('#audioarr').val(jcat1);
});
});
$('form#music').submit(function(e)
{
e.preventDefault();
var form = $(this);
/*var purl = form.find('#project_url').val();
if (purl.length < 8) {
$('p#purl').html('Please enter a url without space and specialchar');
return false;
}*/
var video = form.find('#video').val();
var trailer = form.find('#trailer').val();
dataString = $("form#music").serialize();
$.ajax({
url: '<?php echo base_url('video/creations/createmusic'); ?>',
type: "POST",
data: dataString,
data: new FormData(this),
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
success: function(data) { $("#success").html(data); }
});
});
You don't need to use for loop for uploading multiple files.
Since you are storing all file details in single array, use can use
$this->upload->do_upload('audio'); // input file name
You can access uploaded file details from
$data = $this->upload->data();
foreach($data as $audio) {
`// code goes here...`
}
ajax i have this snippet:
$("input#search_field").keyup(function(){
var searchText = $("input#search_field").val()
if(searchText.length > 1){
$.ajax({
url: 'search.php',
data: {data: JSON.stringify(searchText)},
type: 'POST',
dataType: "json",
success: function (data) {
if(data.result == 1) {
console.log(data.error);
}
if(data.result == 0) {
console.log(data.error)
}
}
});
}
});
When data.result is = 1, than the returned data.error is an array, in my console:
["string"]
My question is how get every string in my array into a different variable so i can use it later?
Because returned array could be also:
["string","string2","string3"]
Anyone knows?? Greetings!
I split the array as folow
var string = $('#uInput').val();
var array = string.split('\n');
for($i = 0; $i < array.length; $i++){
var dateAndText = array[$i].split(',');
$('#spota').append(dateAndText[0] + '<br>');
$('#spotb').append(dateAndText[1] + '<br>');
Hope this helps.