lilHar
lilHar

Reputation: 1864

$.post returns object when aiming for simple php

I guess I'm just having difficulty with $.post... I've used it successfully in the past, but I have to be forgetting something important. All I want is a "hello world", but I'm getting a complicated object. I am befuddled.

var_test.php

<?php
    PRINT "hi";
?>

index.html

<!doctype html>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
<html><head>
    var thing = $.post( "var_test.php");
    console.log(thing);
</head><body></body></html>

console output

Object { readyState: 1, getResponseHeader: .ajax/v.getResponseHeader(), getAllResponseHeaders: .ajax/v.getAllResponseHeaders(), setRequestHeader: .ajax/v.setRequestHeader(), overrideMimeType: .ajax/v.overrideMimeType(), statusCode: .ajax/v.statusCode(), abort: .ajax/v.abort(), state: .Deferred/d.state(), always: .Deferred/d.always(), then: .Deferred/d.then(), 8 more… }

Upvotes: 1

Views: 122

Answers (3)

JSelser
JSelser

Reputation: 3630

The $.post() isn't supposed to return your data, if you look closer at the 'big' object it has connection data.

You want this

$.post('var_test.php', function(myData) {
    console.log(myData);
});

Also you should be using $.get() for this sort of things, in exactly the same way

$.get('var_test.php', function(myData) {
    console.log(myData);
});

Upvotes: 1

Oussama Gammoudi
Oussama Gammoudi

Reputation: 761

The problem is with the jquery code, to request the content of a page you use the following code:

$.post( "var_test.php", function( data ) {
    console.log( data );
});

In the code you wrote $.post( "var_test.php") returns a jqXHR Object, it is an asynchronous call, so you need to use a callback, a more info can be found here:

http://api.jquery.com/jquery.post/

Upvotes: 1

taxicala
taxicala

Reputation: 21789

You should add a callback instead that receives the response/data from your php:

$.post( "var_test.php", function(response) {
    console.log(response);
});

That callback will be executed once the request has finished, that way, you can be sure that you will have your data ready and set to use it in your JS.

Upvotes: 1

Related Questions