0

My jQuery ajax posting is not working. Here is the javascript

function SocialButtons() {  
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
    var postData = $buttonWrapper.html();
    jQuery.ajax({
        type: 'POST',
        url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
        data: postData, 
        cache: false,
        success: function(data) { 
            console.log(data);
        },
        contentType: "application/json",
        dataType: 'json'    
    });
}
}

I am saving the data to be posted inside a hidden div like

<div class='WrapperDiv hidden'>{"post_id":392,"url":"http:\/\/www.wordpress-site\/post\/post-title\/","title":"SEO Friendly title"}</div>

All I am getting in return from the post.php page is an empty array. Here is my code for post.php

<?php
if(isset($_POST)){
    print_r($_POST);
} else {
    echo "0";
}   
?>

Any Idea whats wrong?

EDIT : Its working after I removed

    contentType: "application/json",
    dataType: 'json' 
rahul Ram
  • 91
  • 1
  • 1
  • 6

4 Answers4

0

What about something like this:

var postData = "data=" + encodeURCIComponent($buttonWrapper.html());

Than in PHP:

echo $_POST["data"];

Than parse it or something....

Draško
  • 727
  • 1
  • 8
  • 12
0

Couple of things to try,

Try to pass the data directly in to the data object first. If it works then you can debug and see why it's not ready your hidden div.

instead of $buttonWrapper.html try $buttonWrapper.text();

function SocialButtons() {  
var $buttonWrapper = jQuery('.WrapperDiv');
if ($buttonWrapper.length){
    var postData = $buttonWrapper.**text**();
    jQuery.ajax({
        type: 'POST',
        url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
        data: **{'id':1}**, 
        cache: false,
        success: function(data) { 
            console.log(data);
        },
        contentType: "application/json",
        dataType: 'json'    
    });
}
}
Harish
  • 1,469
  • 16
  • 43
0

Inside your jQuery ajax call, your data is not set to $_POST variable names. Hence why nothing is showing

Try changing your function to this:

function SocialButtons() {  
  var buttonWrapper = jQuery('.WrapperDiv');
  if (buttonWrapper.length){
    var postData = buttonWrapper.html();
    jQuery.ajax({
    type: 'POST',
    url: 'http://www.wordpress-site.com/wp-contents/themes/theme-name/post.php',
    data: {postData: postData}, 
    cache: false,
    success: function(data) { 
        console.log(data);
    },
    contentType: "application/json",
    dataType: 'json'    
    });
  }
}

Then you should have a $_POST['postData'] variable on your print_r or var_dump of $_POST.

Cory Shaw
  • 1,130
  • 10
  • 16
0

Its working after I removed

contentType: "application/json",
dataType: 'json' 
rahul Ram
  • 91
  • 1
  • 1
  • 6