How to fix 'ERR_ACCESS_DENIED' when uploading multiple files - javascript

I am trying to upload multiple files to a server. It works fine when there is one file, but as soon as there are multiple, I get "ERR_ACCESS_DENIED". Not sure if this has something to do with my permissions or just my naive code. Thanks in advance!
PHP:
session_start();
function outputJSON($msg, $code = 0, $status = 'error'){
header('Content-Type: application/json');
if ($code == 200 || $code == 201){
echo $code;
exit();
}
echo $msg . "||" . $code . "||" . $status;
die();
}
//ERROR CODES:
//200 - Upload and Processing successful;
//201 - Upload and Processing successful; - Rename made
//400 - Upload Failed
//511 - Not Authorized
//520 - Unknown
$tempDir = guidv4();
mkdir("disk/processing/" . $tempDir);
$putdir = 'disk/processing/' . $tempDir . '/';
if (isset($_FILES['files']) && !empty($_FILES['files'])) {
$no_files = count($_FILES["files"]['name']);
for ($i = 0; $i < $no_files; $i++) {
if ($_FILES["files"]["error"][$i] > 0) {
outputJSON($_FILES["files"]["error"], 520, 'error');
} else {
if (file_exists($putdir . $_FILES["files"]["name"][$i])) {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], $putdir . $_FILES["files"]["name"][$i] . ' (1)');
outputJSON($tempDir, 200, 'done');
} else {
move_uploaded_file($_FILES["files"]["tmp_name"][$i], $putdir . $_FILES["files"]["name"][$i]);
outputJSON($tempDir, 201, 'done');
}
}
}
} else {
outputJSON('Empty Upload.', 400, 'error');
}
JS/JQ
$('#information').show();
var form_data = new FormData();
var ins = document.getElementById('multiFiles').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("files[]", document.getElementById('multiFiles').files[x]);
}
$.ajax({
url: 'uploadbackend.php', // point to server-side PHP script
dataType: 'application/json', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
xhr: function() {
var started_at = new Date();
xhr.upload.addEventListener( 'progress', function( e )
{
if( e.lengthComputable )
{
// Append progress percentage.
var loaded = e.loaded;
var total = e.total;
var progressValue = Math.round( ( loaded / total ) * 100 );
// Bytes received.
jQuery( '.recievedValue' ).html( '' );
jQuery( '.recievedValue' ).append( humanFileSize( loaded ) + ' / ' );
// Total bytes.
jQuery( '.totalValue' ).html( '' );
jQuery( '.totalValue' ).append( humanFileSize( total ) );
// Time Remaining
var seconds_elapsed = ( new Date().getTime() - started_at.getTime() )/1000;
var bytes_per_second = seconds_elapsed ? loaded / seconds_elapsed : 0 ;
var Kbytes_per_second = bytes_per_second / 1000 ;
var remaining_bytes = total - loaded;
var seconds_remaining = seconds_elapsed ? remaining_bytes / bytes_per_second : 'calculating' ;
jQuery( '.timeRemaining' ).html( '' );
jQuery( '.timeRemaining' ).append( seconds_remaining );
// Percentage.
$('#_explorer_progress').css("width", "" + progressValue + "%")
if (progressValue >= 100){
$('#information').html('Processing...')
}
}
}, false );
return xhr;
},
success: function (response) {
$('#information').html('Done.');
$('#upload').html('Uploaded! <i class="fa fa-check ml-5"></i>');
$('#upload').removeClass('btn-primary');
$('#upload').removeClass('btn-danger');
$('#upload').addClass('btn-info');
document.getElementById("upload").disabled = true;
$('#msg').html(response); // display success response from the PHP script
setTimeout(function () {
$('#upload').html('Start Upload <i class="fa fa-upload ml-5"></i>');
document.getElementById("upload").disabled = false;
$('#upload').addClass('btn-primary');
$('#upload').removeClass('btn-danger');
$('#upload').removeClass('btn-info');
$("#multifiles").val('');
}, 3000)
},
error: function (response) {
$('#information').html('There was a problem.');
console.log(response);
}
});
HTML:
<input type="file" id="multiFiles" name="files[]" multiple="multiple"/>
There is no response from the server except an "ERR_ACCESS_DENIED" error from the POST request.
When there is one file, it functions as expected.

Related

How to send one or more data through jquery.ajax

I copied this code from stackoverflow it working fine when i upload multiple file through it. but i cannot send other parameter with it . it only upload the file but dont send the other parameter. i tried different way but i am unable to send the data.
My code is below but i dont send the second parameter of NewDir:foldername to my php file
This is my javascript code///////////
function OnProgress(event, position, total, percentComplete){
//Progress bar
console.log(total);
$('#pb').width(percentComplete + '%'); //update progressbar percent complete
$('#pt').html(percentComplete + '%'); //update status text
}
$(document).ready(function(){
$('#files').change(function(){
var files = $('#files')[0].files;
var foldername = $('#Reciter_Name').val();
var error = '';
var form_data = new FormData();
var bar = $('.bar');
var status = $('#status');
var percent = $('.percent');
if(foldername == ''){
alert("Your Don't enter any name");
return false;
}
for(var count = 0; count<files.length; count++)
{
var name = files[count].name;
var extension = name.split('.').pop().toLowerCase();
if(jQuery.inArray(extension, ['mp3']) == -1)
{
error += "Invalid " + count + " Mp3 File"
}
else
{
form_data.append("files[]", files[count]);
}
}
if(error == '')
{
$.ajax({
url:"<?php echo base_url(); ?>index.php/admin/upload", //base_url()
return http://localhost/tutorial/codeigniter/
method:"POST",
data:{form_data,NewDir:foldername},
contentType:false,
cache:false,
processData:false,
beforeSend:function()
{
// $('#uploaded_files').html("<label class='text-success'>Uploading...</label>");
status.empty();
var percentVal = '0%';
bar.width(percentVal);
percent.html(percentVal);
},
uploadProgress: function(event, position, total, percentComplete) {
var percentVal = percentComplete + '%';
bar.width(percentVal);
percent.html(percentVal);
},
success:function(data)
{
$('#uploaded_files').html(data);
$('#files').val('');
}
})
}
else
{
alert(error);
}
});
});
This is my php code given below///////////
function upload()
{
sleep(3);
if($_FILES["files"]["name"] != '')
{
$output = '';
$config["upload_path"] = './uploads/audio/';
$config["allowed_types"] = 'mp3';
$config["overwrite"] = TRUE;
$this->load->library('upload', $config);
$this->upload->initialize($config);
for($count = 0; $count<count($_FILES["files"]["name"]); $count++)
{
$_FILES["file"]["name"] = $_FILES["files"]["name"][$count];
$_FILES["file"]["type"] = $_FILES["files"]["type"][$count];
$_FILES["file"]["tmp_name"] = $_FILES["files"]["tmp_name"][$count];
$_FILES["file"]["error"] = $_FILES["files"]["error"][$count];
$_FILES["file"]["size"] = $_FILES["files"]["size"][$count];
if($this->upload->do_upload('file'))
{
$data = $this->upload->data();
$output .= '
<input type="hidden" name="url[]" value="'.base_url().'uploads/audio/'.$data["file_name"].'" />
<input type="hidden" name="surahname[]" value="'.$data["file_name"].'" />
'.$data["file_name"].'
';
}
}
}
echo $output;
}
So please tell me how i can pass data from php file.
/////////////////////////////////////////////////////////////////
You just need to add
form_data.append('NewDir',foldername);
Before assign form_data to ajax data variable

handle more than one ajax response

First I want to describe what I want to do.
I've a table and one column has buttons. Each button represents an ID. When the button is clicked, I store the ID into a variable in javascript. I want to use this ID in a MySQL-Statement to get some informations, which are in more than one row and creare a PDF file with these data.
I want to use ajax to handle the recived data, but I don't know exactly how to.
Until now, this is what I got:
<script>
$("#grid-table").bootgrid({
formatters: {
"buttonID": function(column, row){
return "<button type=\"button\" id=\"edit\" class=\"btn btn-xs btn-default print-pdf\" + data-row-id1=\"" + row.ID + "\" ><span class=\"fa fa-file-pdf-o\"></span></button> ";
}
}).on("click", function(e){
var id = $(this).data("row-id1"); // id is a string
var recv_data1[];
var recv_data2[];
var recv_data3[];
var recv_data4[];
var i = 0;
if(id != ""){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (this.readyState == 4 && this.status == 200) {
// how to get all datas and store them here?
// and get the count of $i
var doc = new jsPDF(); // pdf object
mainPage(doc); // my function to create a pdf background
var xPos = 25;
var yPos = 60;
while(i){
doc.setFontSize(12);
doc.setFontType('normal');
doc.text(70, 55, recv_data1[i]); // here I want to use some of the data
doc.setFontSize(11);
doc.setFontType('bold');
doc.text(xPos+10, yPos+10, recv_data2[i]); // some more data I got from the mysql-statement
doc.text(xPos+55, yPos+10, recv_data3[i]);
doc.text(xPos+80, yPos+10, recv_data4[i]);
i--;
}
doc.save(recv_data1 + '.pdf'); // save pdf file
}
};
xmlhttp.open("GET","get_data.php?id="+ id, true);
xmlhttp.send();
}
});
</script>
PHP-Part from get_data.php:
<?php
include "dbconnect.php";
$revc_id = htmlspecialchars_decode($_GET['id']);
$result = mysqli_query($db, "SELECT *
FROM table
WHERE table.id = 'revc_id';");
$i = 1;
while($row = mysqli_fetch_array($result)) {
// how to handle the fetched array and alle the data to
// more than one variable for the js like
// echo $row['name'] for recv_data1[]
// echo $row['city'] for recv_data2[]
// echo $row['street'] for recv_data3[]
// echo $row['country'] for recv_data4[]
// echo $i to know how many datas are in there
$i++;
}
mysqli_close($db);
?>
This is just a general example of what I want to do and not the original code. So what I want is that the respone I got from get_data.php, which is in the most cases more than one row, to be saved into the array.
I hope you know what I mean, if not fell free to ask please.
Tricky to answer when the code shown is not the actual code but in general you could try something like this.
php
---
$data=array();
while( $row = mysqli_fetch_object( $result ) ) {
$data[]=array(
'name' => $row->name,
'city' => $row->city,
'street' => $row->street,
'country' => $row->country
);
}
echo json_encode( $data );
/* javascript */
document.getElementById('BTTN_ID_ETC').onclick = function(e){
e.preventDefault();
var id = $( this ).data("row-id1");
if( id != "" ){
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if( this.readyState == 4 && this.status == 200 ) {
var json=JSON.parse( this.response );
var doc = new jsPDF();
mainPage( doc );
var xPos = 25;
var yPos = 60;
for( var n in json ){
try{
var obj=json[ n ];
if( typeof( obj )=='object' ){
var name=obj.hasOwnProperty('name') ? obj.name : false;
var city=obj.hasOwnProperty('city') ? obj.city : false;
var street=obj.hasOwnProperty('street') ? obj.street : false;
var country=obj.hasOwnProperty('country') ? obj.country : false;
if( name && city && street && country ){
doc.setFontSize(12);
doc.setFontType('normal');
doc.text(70, 55, name );
doc.setFontSize(11);
doc.setFontType('bold');
doc.text(xPos+10, yPos+10, city );
doc.text(xPos+55, yPos+10, street );
doc.text(xPos+80, yPos+10, country );
}
}
} catch( err ){
console.log( err );
continue;
}
}
doc.save( json[0].name + '.pdf');
}
};
xmlhttp.open( 'GET', 'get_data.php?id='+ id, true );
xmlhttp.send();
}
};

javascript data wont show in php codeigniter

I'm trying to get ajax data from my controller to view. but the javascript code seems doesnt execute well. here's my script
<script type="text/javascript">
function view_data(act){
var w = $('#origin').val();
var x = $('#destination').val();
var y = $('#weight').val();
var z = $('#courier').val();
if(w == "" && x == "" && y == "" && z == "" ){
alert("I am an alert box!");
}else{
$.ajax({
url: "<?php echo base_url()?>Cart/getCost",
type: "GET",
data : {origin: w, destination: x, berat: y, courier: z},
success: function (ajaxData){
$("#result").html(ajaxData);
}
});
}
};
</script>
for orgin and destination is came from option select
and for weight and courier from input text.
here's my controller
function getCost()
{
$origin = $this->input->get('origin');
$destination = $this->input->get('destination');
$weight = $this->input->get('weight');
$courier = $this->input->get('courier');
$data = array('origin' => $origin,
'destination' => $destination,
'weight' => $weight,
'courier' => $courier
);
$this->load->view('rajaongkir/getCost', $data);
}}
the problem is , data wontt show up in #result on view.
change your url to this :
url: "<?php echo base_url();?>Cart/getCost",
in ajax you have to give full url address .
please replace load view , to var_dump , and in your ajax success part, console.log(result) to show what we have in controller .
Second one:
another way is to set your view to a variable ( i name it , $Datares) , and add this code after it
$this->set_output($Datares);
This will helps you
<script type="text/javascript">
function view_data(act){
var w = $('#origin').val();
var x = $('#destination').val();
var y = $('#weight').val();
var z = $('#courier').val();
if(w == "" && x == "" && y == "" && z == "" ){
alert("I am an alert box!");
}else{
$.ajax({
url: "Cart/getCost",
type: "GET",
data : {origin: w, destination: x, berat: y, courier: z},
success: function (ajaxData){
$("#result").html(ajaxData);
}
});
}
};
</script>
function getCost()
{
$origin = $this->input->get('origin');
$destination = $this->input->get('destination');
$weight = $this->input->get('weight');
$courier = $this->input->get('courier');
$data = array('origin' => $origin,
'destination' => $destination,
'weight' => $weight,
'courier' => $courier
);
echo $data;
exit;
}

How to show the errors through ajax and Jquery in codeigniter

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 }

Ajax success return

Can someone help me with this
I have this php file for insert data into my database and all is sent by ajax function
<?php
header('Content-type: application/json');
ini_set('max_execution_time', 300);
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');
// Works as of PHP 5.2.9 and 5.3.0.
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
$num= $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = explode(",", $_POST['hora']);
$a = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17];
$c = array_fill_keys(array_keys(array_diff($a,$hora)),null) + $a;
ksort($c);
for ($i=0; $i<17; $i++){
$horas = $c[$i];
$stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(mysql_error($mysqli));
$stmt->bind_param('ssi', $dia, $sala, $horas);
if(!$stmt->execute()){
echo json_encode(array('status' => 'error','message'=> 'Opppss...Os Registo(s) não foram gravado(s)'));
}
else{
echo json_encode(array('status' => 'success','message'=> 'Registo(s) gravado(s) com sucesso'));
}
$stmt->close();
}
$mysqli->close();
?>
And this my ajax function
function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
var data = 'dia='+ dia + '&sala='+ sala + '&hora='+ tempos + '&num='+ num;
$.ajax({
type: "POST",
dataType: "html",
url: "registerBd.php",
data: data,
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error:function(response){
console.log("Aqui 2");
alert("something went wrong");
}});
return false;
}
Called by my form like this
<form method="post" id="salas" name="salas" onsubmit="postData()" >
But i have always error in my function even my data is inserted into dabase
New update
New insert php named registerBd.php
<?php
header('Content-type: application/json');
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
$num = $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = $_POST['hora'];
$a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
$c = array_fill_keys(array_keys(array_diff($a, $hora)), null) + $a;
ksort($c);
for ($i = 0; $i < 17; $i++) {
$horas = $c[$i];
$stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(json_encode(mysqli_error($mysqli)));
$stmt->bind_param('ssi', $dia, $sala, $horas);
if (!$stmt->execute()) {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...Os Registo(s) não foram gravado(s)'));
}
}
echo json_encode(array('status' => 'success', 'message' => 'Registo(s) gravado(s) com sucesso'));
$stmt->close();
unset($stmt);
?>
And modification to ajax
<script>
function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
$.ajax({
type: "POST",
dataType: "json",
url: "registerBd.php",
data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error: function(jq,status,message) {
console.log( message );
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
return false;
}
</script>
But still have the same problem, and in chrome console the registerBd.php is red after the insert, so i think the problem should be here even if everything is recorded into database
New Update...this is getting really strange
Removed 2 lines in registerDb.php
unset($smtp);
?>
With debug and without
i get this
check image
http://postimg.org/image/8wtwxod3r/
Without debuger
http://postimg.org/image/5nctzrjkv/
Check at the bottom it seems that the registerBd.php is canceled...why?
So now i'm lost
Update 3
Where i call my ajax function
<form method="post" id="salas" name="salas" onsubmit="postData()" >
My ajax function
<script>
function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
$.ajax({
type: "POST",
dataType: "json",
url: "registerBd.php",
data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error: function(jq,status,message) {
console.log( message );
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
return false;
}
</script>
and my registerBd.php
<?php
error_reporting(E_ALL | E_NOTICE);
ini_set('display_errors', '1');
$mysqli = new mysqli('localhost', 'root', '', 'ebspma');
if ($mysqli->connect_error) {
die('Connect Error: ' . $mysqli->connect_error);
}
$num = $_POST['num'];
$dia = $_POST['dia'];
$sala = $_POST['sala'];
$hora = $_POST['hora'];
$a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17];
$c = array_fill_keys(array_keys(array_diff($a, $hora)), null) + $a;
ksort($c);
for ($i = 0; $i < 17; $i++) {
$horas = $c[$i];
$stmt = $mysqli->prepare("INSERT INTO `ebspma`.`sala_ocupacao` (id_dia, id_sala, id_tempo) VALUES (?, ?, ?);")or die(json_encode(mysqli_error($mysqli)));
$stmt->bind_param('ssi', $dia, $sala, $horas);
if (!$stmt->execute()) {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...Os Registo(s) não foram gravado(s)'));
}
}
$response = "Registo(s) gravado(s) com sucesso";
echo json_encode($response);
$stmt->close();
In real mode i have this
Request URL: http://localhost/multiple/registerBd.php
Method: POST
Status: Request was cancelled.
Request Headers
Accept: application/json, text/javascript, */*; q=0.01
Content-Type: application/x-www-form-urlencoded; charset=UTF-8
Origin: http://localhost
Referer: http://localhost/multiple/registo_salas.php
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.44 (KHTML, like Gecko) JavaFX/8.0 Safari/537.44
X-Requested-With: XMLHttpRequest
Request data
dia=2&sala=5&hora%5B%5D=1&hora%5B%5D=2&hora%5B%5D=3&num=3
CallStack
send ([native code]:0:0)
send (https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js:4:25552)
ajax (https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js:4:21305)
postData (registo_salas.php:104:26)
onsubmit (registo_salas.php:116:27)
Update 4
I don't know if if this what you mean...but i don't think it is (my fault...)
<script>
$('#salas').on('submit', function(event) {
event.preventDefault();
function postData(){
var dia = document.getElementById('dia').value;
var sala = document.getElementById('sala').value;
var tempos = [];
var s = document.getElementById('hora');
for (var i = 0; i < s.options.length; i++) {
if (s.options[i].selected == true) {
var valores = s.options[i].value;
tempos.push(valores);
}
}
console.log(tempos);
var num = document.getElementById('num').value;
event.preventDefault();
$.ajax({
type: "POST",
dataType: "json",
url: "registerBd.php",
data : {'dia': dia, 'sala': sala, 'hora': tempos, 'num': num},
success: function (response) {
console.log(response);
$('#ajaxDivOk').css("display", "block");
$('#ajaxDivOk').html("Registo(s) gravado(s) com sucesso");
alert(response);
},
error: function(jq,status,message) {
console.log( message );
alert('A jQuery error has occurred. Status: ' + status + ' - Message: ' + message);
}
});
return false;
}
});
i get
Uncaught ReferenceError: postData is not definedonsubmit # registo_salas.php:120
I see a few problems here:
You are sending back json but you specify dataType: "html", in your ajax call. You should change that to dataType: "json",
You are mixing mysql apis:or die(mysql_error($mysqli));You cannot use any mysql_* function as you are using mysqli_*. You need something like: or die(mysqli_error($mysqli));
If you do return json, you need to make sure your error messages are valid json as well, so the second should really be (applies to the other instances too):
or die(json_encode(mysqli_error($mysqli)));
A potential problem is that you are not encoding your query string correctly in your ajax call. You can let jQuery take care of that by using an object:var data = {'dia': dia, 'sala': sala, etc.};
Edit: Based on your last update, it seems that you are not cancelling the default submit event. You do return false from your function, but you don't do anything with that value.
You should change:
<form method="post" id="salas" name="salas" onsubmit="postData()" >
to:
<form method="post" id="salas" name="salas" onsubmit="return postData();" >
Although, as you are using jQuery, a better solution would be to remove the inline javascript and move it to your script section:
$('form').on('submit', function(event) {
event.preventDefault();
// the rest of your javascript that is now in your `postData()` function
});

Categories