Programing

Ajax 성공 이벤트가 작동하지 않습니다

lottogame 2020. 5. 20. 07:48
반응형

Ajax 성공 이벤트가 작동하지 않습니다


등록 양식이 있고 $.ajax제출하는 데 사용 하고 있습니다.

이것은 내 AJAX 요청입니다.

$(document).ready(function() {
    $("form#regist").submit(function() {
        var str = $("#regist").serialize();
        $.ajax({
            type: 'POST',
            url: 'submit1.php',
            data: $("#regist").serialize(),
            dataType: 'json',
            success: function() {
                $("#loading").append("<h2>you are here</h2>");
            }        
        });
        return false;        
    });
});

내에서 submit1.php의 파일 나는 필드의 존재를 확인 이메일 주소사용자 이름 데이터베이스입니다. 해당 값이 페이지 새로 고침없이 존재하면 오류 메시지를 표시하고 싶습니다 .

AJAX 요청 성공 콜백에 이것을 어떻게 추가 할 수 있습니까?


결과는 아마도 JSON 형식이 아니므로 jQuery가 구문 분석하려고하면 실패합니다. error:콜백 함수로 오류를 잡을 수 있습니다 .

어쨌든 해당 기능에 JSON이 필요하지 않으므로 dataType: 'json'을 가져올 수도 있습니다 .


문제가 이미 해결되었지만 다른 사람들에게 도움이되기를 바랍니다.

나는 실수를 이런 식으로 직접 사용하려고 시도했다 (성공 : OnSuccess (productID)). 그러나 먼저 익명 함수를 전달해야합니다.

  function callWebService(cartObject) {

    $.ajax({
      type: "POST",
      url: "http://localhost/AspNetWebService.asmx/YourMethodName",
      data: cartObject,
      contentType: "application/x-www-form-urlencoded",
      dataType: "html",
      success: function () {
        OnSuccess(cartObject.productID)
      },
      error: function () {
        OnError(cartObject.productID)
      },
      complete: function () {
        // Handle the complete event
        alert("ajax completed " + cartObject.productID);
      }
    });  // end Ajax        
    return false;
  }

랩퍼로 익명 함수를 사용하지 않으면 웹 서비스가 예외를 리턴하더라도 OnSuccess가 호출됩니다.


dataType 행을 제거하려고 시도했지만 작동하지 않았습니다. 콜백으로 "성공"대신 "완료"를 사용하여 문제를 해결했습니다. 성공 콜백은 여전히 ​​IE에서 실패하지만 스크립트가 실행되고 완료되기 때문에 어쨌든 그게 전부입니다.

$.ajax({
    type: 'POST',
    url: 'somescript.php',
    data: someData,
    complete: function(jqXHR) {
       if(jqXHR.readyState === 4) {
          ... run some code ... 
       }   
    }        
 });

jQuery 1.5에서는 이와 같이 할 수도 있습니다.

var ajax = $.ajax({
    type: 'POST',
    url: 'somescript.php',
    data: 'someData'
});
ajax.complete(function(jqXHR){
    if(jqXHR.readyState === 4) {
        ... run some code ... 
    }
});

Make sure you're not printing (echo or print) any text/data prior to generate your JSON formated data in your PHP file. That could explain that you get a -sucessfull 200 OK- but your sucess event still fails in your javascript. You can verify what your script is receiving by checking the section "Network - Answer" in firebug for the POST submit1.php.


Put an alert() in your success callback to make sure it's being called at all.

If it's not, that's simply because the request wasn't successful at all, even though you manage to hit the server. Reasonable causes could be that a timeout expires, or something in your php code throws an exception.

Install the firebug addon for firefox, if you haven't already, and inspect the AJAX callback. You'll be able to see the response, and whether or not it receives a successful (200 OK) response. You can also put another alert() in the complete callback, which should definitely be invoked.


I had same problem. it happen because javascript expect json data type in returning data. but if you use echo or print in your php this situation occur. if you use echo function in php to return data, Simply remove dataType : "json" working pretty well.


I was returning valid JSON, getting a response of 200 in my "complete" callback, and could see it in the chrome network console... BUT I hadn't specified

dataType: "json"

once I did, unlike the "accepted answer", that actually fixed the problem.


I'm using XML to carry the result back from the php on the server to the webpage and I have had the same behaviour.

In my case the reason was , that the closing tag did not match the opening tag.

<?php
....
header("Content-Type: text/xml");
echo "<?xml version=\"1.0\" encoding=\"utf-8\"?>
    <result>
        <status>$status</status>
        <OPENING_TAG>$message</CLOSING_TAG>
    </result>";
?>

I had this problem using an ajax function to recover the user password from Magento. The success event was not being fired, then I realized there were two errors:

  1. The result was not being returned in JSON format
  2. I was trying to convert an array to JSON format, but this array had non-utf characters

So every time I tried to use json_eoncde() to encode the returning array, the function was not working because one of its indexes had non-utf characters, most of them accentuation in brazilian portuguese words.


I tried to return string from controller but why control returning to error block not in success of ajax

var sownum="aa";
$.ajax({
    type : "POST",
    contentType : 'application/json; charset=utf-8',
    dataType : "JSON",
    url : 'updateSowDetails.html?sownum=' + sownum,
    success : function() {
        alert("Wrong username");
    },
    error : function(request, status, error) {

        var val = request.responseText;
        alert("error"+val);
    }
});

I faced the same problem when querying controller which does not return success response, when modified my controller to return success message problem was solved. note using Lavalite framework. before:

public function Activity($id)
    {
        $data=getData();
        return
            $this->response->title('title')
                ->layout('layout')
                ->data(compact('data'))
                ->view('view')
                ->output();
    }
after code looks like:
    try {
            $attributes = $request->all();
            //do something
            return $this->response->message('')
                ->code(204)
                ->status('success')
                ->url('url'. $data->id)
                ->redirect();
        } catch (Exception $e) {
            return $this->response->message($e->getMessage())
                ->code(400)
                ->status('error')
                ->url('nothing Wrong')
                ->redirect()
        }

this worked for me


in my case the error was this was in the server side and for that reason it was returning a html

wp_nonce_field(basename(__FILE__), "mu-meta-box-nonce");

Add 'error' callback (just like 'success') this way:

$.ajax({
   type: 'POST',
   url: 'submit1.php',
   data: $("#regist").serialize(),
   dataType: 'json',
   success: function() {
      $("#loading").append("<h2>you are here</h2>");
   },
   error: function(jqXhr, textStatus, errorMessage){
      console.log("Error: ", errorMessage);
   }
});

So, in my case I saw in console:

Error:  SyntaxError: Unexpected end of JSON input
  at parse (<anonymous>), ..., etc.

I had the same problem i solved it in that way: My ajax:

event.preventDefault();
$.ajax('file.php', {
method: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify({tab}), 
success: function(php_response){
            if (php_response == 'item') 
                {
                    console.log('it works');
                }
            }
        })

Ok. The problem is not with json but only php response. Before: my php response was:

echo 'item';

Now:

$variable = 'item';
 echo json.encode($variable);

Now my success working. PS. Sorry if something is wrong but it is my first comment on this forum :)


You must declare both Success AND Error callback. Adding

error: function(err) {...} 

should fix the problem


The success callback takes two arguments:

success: function (data, textStatus) { }

Also make sure that the submit1.php sets the proper content-type header: application/json

참고URL : https://stackoverflow.com/questions/1969476/ajax-success-event-not-working

반응형