aJ-47 aJ-47 - 1 month ago 4x
jQuery Question

using $.post() jQuery method for button click event

I have a mini-web application that populates contents of a JavaScript object as the user interacts with the page. I've added a

on('click', function() {})

event handler to a button element on the page.

I want to use
method in the event handler to post/submit the JavaScript object to a PHP backend and asynchronously update a 'Div' element with the data/message received from the PHP server/script.

console.log verifies the JavaScript object is OK, but I can't even receive a 'Hello World' string back from the PHP script, let alone processing the JavaScript object.

Here is my code:


<button id="sbButton" type="button">Submit </button> <div id="output"></div>`


$(function() {
// populates name:value pairs as user interacts on the web page
var vInfo = {};
$('#sbButton').on('click', function() {

$.post('http://localhost/ReceptionVisitorKiosk/response.php'‌​, vInfo, function(data) {
console.log("Response Info " + data);

PHP: Tried both as suggested by kyshel and robert in their replies to no help.


try following snippet:

var objectToSend = {name:"Some Name", lastName:"Some last name"};
    $.post('url_to_php.php', objectToSend , function(response){

accessing variables in php.

$name = $_POST["name"];
$lastName = $_POST["lastName"];
$data = //some object you are returning
header('Content-Type: application/json');
echo json_encode($data); 


I've tested following snippet on http://phpfiddle.org/. I could not save it cause it requires registration, but you can re-paste it.

    $name = $_POST["name"];
    $data = "Thank you $name";
    header('Content-Type: application/json');
    echo json_encode($data); 
    return false;

<!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">
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
            PhpFiddle Initial Code
        <script type="text/javascript" src="/js/jquery/1.7.2/jquery.min.js"></script>
        <style type="text/css">
        <div style="margin: 50px 10%;">
            <button id="mybutton" type="button">Click to See</button>
            $("#mybutton").click(function() {
                // myurl can be an URL or PhpFiddle API, fopr example, 
                //var myurl = "http://main.xfiddle.com/<?php echo pf_file('jh2-qj7'); ?>";
                var dataToSend = {name : "Robert"};
                $.post(window.location.href, dataToSend , function(response){