weixin_33697898 2015-05-29 12:09 采纳率: 0%
浏览 32

Json对Ajax的回应

The data is inserted and i receive in console the json response but the page move for the insert php and gives the json response So i start in page A (form) and after submit moves to page B (insert)giving me the json response. I'm having a problem getting the response of the following php into ajax

if (move_uploaded_file($_FILES['fileToUpload']['tmp_name'], $uploadfile)) {

$target_path = "/uploads/" . basename($_FILES['fileToUpload']['name']);
$sql = "INSERT INTO `ebspma_paad_ebspma`.`formacoes`(idescola, nome, inicio, horas, local, destinatarios, dataLimite, visto, path) VALUES(?, ?, ?, ?, ? ,?, ?, ?, ? )";
$stmt = $mysqli->prepare($sql);
if ($stmt === false) {
    trigger_error('Wrong SQL: ' . $sql . ' Error: ' . $mysqli->error, E_USER_ERROR);
}
$stmt->bind_param('issssssis', $escola, $form, $data, $horas, $local, $dest, $datas, $visto, $target_path);
if (!$stmt->execute()) {
    echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
} else {
echo json_encode(array('status' => 'error', 'message' => 'Opppss...A formação não foi gravada'));
}
$stmt->close();
echo json_encode(array('status' => 'success', 'message' => 'Nova formação gravada'));

This is my ajax

$.ajax({
            url: 'nova_formacaoBD.php',
            dataType: 'json',
            data: data,
            success: function(data) {
                $('#ajaxDivOk').html('Informação: Esta formação foi registada na base de dados');
                if(data.status == "success"){ 
                   $('#ajaxDivOk').append(data.message);
                }
             }
          });

And this is my form

 <form action="nova_formacaoBD.php" method="post" id="formacao" name="formacao" enctype="multipart/form-data">

UPDATE

The data is all the input fields in the form

Seven strings and upload of one file

 <form method="post" id="formacao" name="formacao" enctype="multipart/form-data">
                    <div class="form-group">
                        <label for="exampleInputFile">Escola: </label>
                        <select class="form-control" id="escola" name="escola" onchange="verificaEscola()">
                            <?php echo $escolaOptions; ?>
                        </select>   
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Nome Formação: </label>
                        <input class="form-control" id="form" name="form" onchange="verificaNome()">
                        </input>
                    <div class="form-group">
                            <label for="exampleInputEmail1">Data de Início: </label><input type="text" class="form-control" id="data" name="data" onchange="verificaData()" />
        </div>

                    <div class="form-group">
                            <label for="exampleInputEmail1">Horas: </label><input type="text" class="form-control" id="horas" name="horas"  onchange="verificaHoras()">
        </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Local: </label>
                        <input class="form-control" id="local" name="local" onchange="verificaLocal()">
                        </input>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Destinatários: </label>
                        <input class="form-control" id="dest" name="dest" onchange="verificaDest()">
                        </input>
                    </div>

                    <div class="form-group">
                        <label for="exampleInputEmail1">Data Limite: </label><input type="text" class="form-control" id="datas" name="datas" onchange="verificaDataLimite()"/>
        </div>
                    <div class="form-group">
                       <label for="exampleInputFile">Programa da Formação</label>
                       <input type="file" name="fileToUpload" id="fileToUpload" name="fileToUpload">
                    </div>          

                    <button type="submit" class="btn btn-default" onclick="return checkBoxes(this)">Registar</button>
                </form>

This is my form complete

UPDATE 2 (now it works but i have a warning in my console Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.

and the beforeSend funtion doesn't work I don't see the div "Wait while updating the file) Js code

<script type="text/javascript">
     $(document).ready(function () {
        $("#formacao").submit(function (event) {
            event.preventDefault();
            //grab all form data  
              var formData = new FormData($(this)[0]);

            $.ajax({
                url: 'nova_formacaoBD.php',
                type: 'POST',
                data: formData,
                async: false,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function(data){
                    $('#ajaxDivAlert').html('A carregar o ficheiro...aguarde por favor')
                },
                success: function (data) {
                    var result = data.status;
                    console.log(result);
                    if(result == 'success'){
                        $('#ajaxDivAlert').empty();
                        $('#ajaxDivOk').html('Informação: ' + data.message);   
                        $("#ajaxDivOk").fadeIn(); 
                        $("#ajaxDivOk").fadeOut(5000);
                    }
                },
                error: function(){
                   $("#ajaxDivErro").html('Esta formação já está registada na base de dados');
                   $("#ajaxDivErro").fadeIn();
                   $("#ajaxDivErro").fadeOut(5000);
                }
            });

            return false;
        });
    });
    </script>

So, i just need to put info to complete the code, the rest is working

  • 写回答

1条回答 默认 最新

  • weixin_33694620 2015-05-29 12:21
    关注

    You have some changes to do :

    Html : Remove the action="nova_formacaoBD.php" like that :

     <form method="post" id="formacao" name="formacao" enctype="multipart/form-data">
    

    Then I suppose that you have a ajax called like that :

    UPDATE

     $(document).ready(function () {
        $("#formacao").submit(function (e) {
            e.preventDefault();
            var formData = new FormData($(this)[0]);
            var ajaxDivAlert = $('#ajaxDivAlert');
    
            $.ajax({
                url: 'nova_formacaoBD.php',
                type: 'POST',
                data: formData,
                cache: false,
                contentType: false,
                processData: false,
                beforeSend: function () {
                    ajaxDivAlert.empty().html('A carregar o ficheiro...aguarde por favor')
                }
            }).done(function (data) {
                var result = data.status;
                if (result == 'success'){
                    ajaxDivAlert.empty().fadeIn().html('Informação: ' + data.message).fadeOut(5000);
                }
            }).fail(function () {
                ajaxDivAlert.empty().fadeIn().html('Esta formação já está registada na base de dados').fadeOut(5000);
            });
        });
    });
    

    You had the error XMLHttpRequest because you put async: false. I removed it because since jQuery 1.8, the use of async: false with jqXHR ($ .Deferred) is deprecated

    评论

报告相同问题?

悬赏问题

  • ¥100 set_link_state
  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度