1

I call a PHP file from AJAX and I want to pass also a variable. This is my code:

echo "<h4 style='color:white'>Messages</h4>";
echo "<textarea cols='50' rows='10' style='font-size: 24px;'></textarea><br><br>";
echo "<button id='sendmessage' style='padding:10px'>Submit</button>";
echo "<button id='deletemessage' style='margin-left:5px;padding:10px'>Delete</button>";


echo "<script>
    jQuery('#sendmessage').click(function(){
        jQuery.ajax({
            data: { content: jQuery('textarea').val() },
            url:'wp-content/themes/dt-chocolate/postmessages.php',
            success:function(data){}
        });
    });
    </script>"

and the PHP file:

<?php
require_once('/opt/lampp/htdocs/mydomain/wp-config.php');

$post = array(
        'post_content'   =>  data.content,
        'post_title'     =>  "testing",
        'post_status'    =>  'publish',
        'post_type'      =>  'post',
        'post_category'  =>  array(28)  // Default empty.
    );  



wp_insert_post( $post );
?>

However, the content of the post is "datacontent" and not the actual text from the textarea. What am I doing wrong?

0

2 Answers 2

3
echo "<script>
jQuery('#sendmessage').click(function(){
    jQuery.ajax({
        data: { content: jQuery('textarea').val() },
        url:'wp-content/themes/dt-chocolate/postmessages.php',
        type: 'POST',
        success:function(data){}
    });
});
</script>";

-

$post = array(
    'post_content'   =>  $_POST['content'],
    'post_title'     =>  "testing",
    'post_status'    =>  'publish',
    'post_type'      =>  'post',
    'post_category'  =>  array(28)  // Default empty.
);  

Set .ajax type (method) to 'POST', then you can read POST request variables in PHP from the $_POST array.

Sign up to request clarification or add additional context in comments.

1 Comment

That's work. I don't know php and I tried to do it with everything I found in Google. Thank you again. I will check your answer as the best in 7 minutes due to SE limit.
2

First, you'd probably want to use POST instead of GET. Just add type: 'POST' to the ajax params or use the "post()" function.

On the server side, the way the value should be retrieved is by using the $_GET (or $_POST) global variables. Your content should be in $_GET['content'].

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.