David Mendienta
David Mendienta

Reputation: 395

Why is AJAX in jQuery not receiving the JSON string from PHP?

Thanks for taking a look at my question, firstly, I know this is not the first time a question of this nature has been asked, but I have being reading StackOverflow for over 3 hours now... still can't figure it out.

Here's the gist:

I'm trying to send a value from messaging.php to messaging.js using json_encode.

-> Here's the messaging.php code:

<?php
header('Content-Type: application/json');
global $wpdb;
$current_user = wp_get_current_user();

$to = $_POST['uname'];
$subject = $_POST['subject'];
$message = $_POST['msg'];


$table_name = $wpdb->prefix . 'none_of_ur_business';

if(isset($to) && isset($to) && isset($to)):
$wpdb->insert(
    $table_name,
    array(
        'notit_sender_userid' => $current_user->display_name,
        'notit_receiver_userid' => $to,
        'notit_subject' => $subject,
        'notit_message' => $messagem
    )
);

$testtext = 'does this work??';
echo json_encode(array('test' => $testtext));


endif;

Here's the messaging.js code:

function sendMessage(uname, subject, message){
  $.ajax({
    url : wp_directory+'/modules/messaging/messaging.php',
    dataType : 'JSON',
    type : 'post',
    data: {
         'uname' : uname,
         'subject' : subject,
         'msg' : message
     },
     success: function(data) {
         alert(data.test);
     }

  });

A couple of relevant things:

I don't get anything from the ajax success function, it never "alerts"

Please provide any help you can, I would highly appreciate it!

Upvotes: 1

Views: 71

Answers (1)

Pawan Developers
Pawan Developers

Reputation: 377

in wordpress you are trying to access file (messaging.php) separatly( out of wordpress) and in messaing.php you have used " global $wpdb; " which is wrong.

First you should include necessary wordpress files. Add below code to your messaging.php

define( 'SHORTINIT', true );
require '{wp_root}/wp-load.php';

change {wp_root}. if your wordpress installed on server root then it will be like $_SERVER["DOCUMET_ROOT"] or you have to adjust manually.

for more info check this page: Using WPDB in standalone script?

Upvotes: 3

Related Questions