rib3ye
rib3ye

Reputation: 2923

jQuery $.ajax works when $.post doesn't

I am just trying to do a simple $.post call.

<body>
<div id="main">
    <div id="diver">
    </div>
    <form id="entry_field_container" action="" method="post" accept-charset="utf-8">
        <input type="text" name="entry_field" value="" id="entry_field">

        <input id="send" type="submit" value="send">
    </form>
</div>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
    $(document).ready(function(){
        $('#send').click(function(e){
            e.preventDefault();
            var txt = $('#entry_field').val();
            $.post(
                'http://localhost/proc.php',
                {
                    name:'me',
                    text:txt
                },
                function(data){
                    console.log(data);
                    $('#diver').html(data)
                },
                'json'
            )

        })
    });
</script>

Inside proc.php:

<?php
    $name = $_POST['name'];
    $text = $_POST['text'];
    echo "{\"" . $name . "\", \"" . $text . "\"}";
?>

For some reason, the POST returns a 200, but the console never comes back with data, it's just blank.

The hardest for me to understand is why this $.ajax function works every time. Is it not just a more verbose example of the same thing?

$.ajax({
    'type':    'POST',
    'url':     'http://localhost/proc.php',
    'async':   true,
    'cache':   false,
    'global':  false,
    'data':    {
       'name':'me',
        'text':txt
    },
    'error': function(xhr,status,err){
        alert("DEBUG: status"+status+" \nError:"+err);
    },  
    'success': function(data){
        console.log(data);
    }   
});

Upvotes: 2

Views: 541

Answers (2)

gen_Eric
gen_Eric

Reputation: 227190

In your $.post you are telling jQuery that the returned text is JSON, but in your $.ajax you are not.

The $.post fails because the text returned from PHP isn't valid JSON.

{"me", "test"}

This isn't valid JSON. {} is an object, so it needs keys:

{"name": "me", "text": "test"}

Or, maybe you want an array ([]):

["me", "test"]

P.S. When creating JSON in PHP, it's highly suggested you use json_encode instead of making the JSON yourself.

Upvotes: 5

Deleteman
Deleteman

Reputation: 8680

You're specifing a "json" format on your $.post call, but not on your $.ajax call, could it be that you're not returning a valid JSON response and that's why your $.post is not executing it's sucess method?

Upvotes: 5

Related Questions