Mozak
Mozak

Reputation: 2798

Calling a post mockjax service with jquery $.post not returning value

I am attempting to call a Mockjax 'post' endpoint through jQuery $.post method as below

service.js

$.mockjax({
    url: '/api/callfor/data',
    type: 'post',
    responseTime: 1000,
    contentType: 'text/json',
    dataType: 'json',
    responseText: {
        success: true,
        data: 'Hello World'
    }
});

index.html

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>Mock Ajax call</title>
</head>
<body>
    <script src="jquery-1.10.2.min.js" type="text/javascript"></script>
    <script src="jquery.mockjax.js" type="text/javascript"></script>
    <script src="service.js" type="text/javascript"></script>
    <script type="text/javascript">

        $.post('/api/callfor/data', {}, function (resp) {
            var html = (resp.success) ? 'Your data is ' + resp.data : 'No data received';
        });
    </script>
</body>
</html>

However on calling the method, the resp always coming as undefined. What could be wrong here?

Upvotes: 3

Views: 2606

Answers (2)

76484
76484

Reputation: 8993

I experienced this issue when I updated my project's jQuery version from 1.12.4 to 2.2.4. The project had been using jquery-mockajax version 2.0.1. $.post calls to URLs mocked with jquery-mockjax were resulting in a Type Error:

Uncaught TypeError: Cannot read properties of undefined (reading 'reload')

By updating to the latest (as of this time) jquery-mockjax - v2.6.1 - I no longer experienced the error.

Upvotes: 1

Mozak
Mozak

Reputation: 2798

The type of data being requested or rather say that the type of data endpoint provides i.e. JSON was not mentioned in the call.

So changing the post call to

 $.post('/api/callfor/data', {}, function (resp) {
            var html = (resp.success) ? 'Your data is ' + resp.data : 'No data received';
        }, 'json');

This returns the data.

Upvotes: 4

Related Questions