#StackBounty: #javascript #jquery #node.js #ajax jquery ajax request to nodejs server only works on page refresh

Bounty: 50

I am quite new to ajax and I am not sure what I am doing wrong. I have a webpage that fetches all comments on a post with an ajax get request. The issue is that the ajax request is only succesful after the webpage is refreshed. I disabled the cache to see if that would solve the issue, but it didn’t.

For example, when I fetch the first comments after refreshing the page from post A and then go onto post B on the website, the comments from the post A appear as the comments for post B, then when I refresh the page the comments for post B are replaced with post B’s comments successfully.

I am using jQuery to make the request:

$.ajax({
    type: "GET",
    url: someURL,
    success: (comments) => {
        console.log(comments);
    
        comments.questions.forEach(questionComment => {
            $('.questionComments').append(
                `<div class="comment">
                    <p>${questionComment.content}</p>
                </div>
                `
            )
        });
    
    
        comments.answers.forEach(answer => {
            answer.forEach(answerComment => {
                $(`.answer#${answerComment.forId} .answerComments`).append(
                    `<div class="comment">
                    <p>${answerComment.content}</p>
                </div>
                `
                )
            })
        })
    },
    cache: false
})

What the commets object looks like brefore the reload – a blank objectblank object

What the comments object looks like after the reloadenter image description here

When you navigate to a different post / different url, the object from the previous post / url is the initial object on the new post, and then when you reload the page the correct object is fetched.


Get this bounty!!!

#StackBounty: #python #django #ajax AJAX call with Django is printing the response to a blank page

Bounty: 50

What’s happening now is when I click submit ("Go!"), Django clears the entire page and then prints the correct JSON response results_matrix on a blank page. alert("success") does not appear or alert("error").
I don’t know why the post function is doing this since I’m not returning a render of anything.

Before clicking "Go!":

enter image description here

After clicking "Go!" in Chrome:

enter image description here

After clicking "Go!" in Internet Explorer:
enter image description here

The ajax call is returning a raw json file to download (which Chrome displays automatically in the browser) instead of going into the ajax success function.

Expected Behavior: Page remains the same while a pop-up appears saying, "success".

In index.js:

$(document).ready(function() {
  ......
  
  var csrftoken = Cookies.get("csrftoken");

  function csrfSafeMethod(method) {
      // these HTTP methods do not require CSRF protection
      return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
  }

  $.ajaxSetup({
      beforeSend: function (xhr, settings) {
          if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
              xhr.setRequestHeader("X-CSRFToken", csrftoken);
          }
      }
  });  

  $(document).on("submit","#weather_form",function(event){
    // //Prevent default django post behaviour for a form submission.
    event.preventDefault();

    $.ajax({
      url: "/weather/",
      type: "POST",
      data: {type_of_person: $("#id_type_of_person").val(),
        exercise: $("#id_exercise").val(),
        unit: $("#id_unit").val(),
        zip_postal: $("#id_zip_postal").val()},
      dataType: "json",
      contentType: "application/json",
      success: function (data){
        alert("success");
      },
      error: function(xhr,errmsg,err) {
        alert("error");
        console.log(errmsg + "n" + xhr.status + ": " + xhr.responseText)
      }
    });

    return false;
  });
});

In index.html:

           <form action="/weather/" method="post" autocomplete="off" id="weather_form">
                {% csrf_token %}
                {{ form.non_field_errors }}
                {{ error }}
                <ul>
                    <li class="center_text">
                        <h3>Best Time to Go Out</h3>
                    </li>
                    <li>
                        <label>{{ form.type_of_person.label }}: </label>
                        {{ form.type_of_person }}
                        {{ form.type_of_person.errors }}
                    </li>
                    <li>
                        <label>{{ form.exercise.label }}: </label>
                        {{ form.exercise }}
                        {{ form.exercise.errors }}
                    </li>
                    <li>
                        <label>{{ form.unit.label }}: </label>
                        {{ form.unit }}
                        {{ form.unit.errors }}
                    </li>
                    <li>
                        <label>{{ form.zip_postal.label }}: </label>
                        {{ form.zip_postal }}
                        {{ form.zip_postal.errors }}
                    </li>
                    <li>
                        <input id="go" type="submit" value="Go!">
                    </li>
                </ul>
            </form>

In views.py:

class weather(base.TemplateView):
    ...

    @staticmethod
    def post(request, *args, **kwargs):
        ...
        if request.method == "POST":
            ...
            if form.is_valid():
                ...
                return http.JsonResponse({"results_matrix": results_matrix.tolist()}, status=200)
            else:
                return http.JsonResponse({"error": form.errors}, status=400)

Edit #1:

The request made after clicking "Go!":
enter image description here

Details:
enter image description here

enter image description here

Edit #2:

Other things I tried, but to no avail:

  • Adding async: false to the ajax call.
  • Directing the ajax call to be handled by another view rather than the current view.

Edit #3:

Dependencies for this web app:

  • jquery-ui-1.12.1/jquery-ui.min.css
  • jquery-ui-1.12.1/jquery-ui.structure.min.css
  • jquery-ui-1.12.1/jquery-ui.theme.min.css
  • jquery-3.5.1.min.js
  • jquery-ui-1.12.1/jquery-ui.min.js
  • index.js
  • index.css
  • Django 3.1


Get this bounty!!!

#StackBounty: #php #wp-query #ajax #search #query-posts Can't search posts using WP_QUERY inside AJAX Function

Bounty: 50

WP_Query is used to get posts via simple arguments provided by it. WordPress provides an argument called ‘s’ for search. It basically searches content of all posts and lists the ones with that string anywhere. There is another WP_Query argument called, post_status, which can be used to filter posts, with particular Post_Status

Do note that this code is enclosed in AJAX function. I am calling an AJAX function from frontend, that passes the url of the current page to $_POST['url']. $_POST['url'] is defined and please don’t worry about it. I want the Query to have only draft posts if the url has "draft/" in it. By echoing the variables I know, that the variables themselves are working fine.

So below is the WP_Query

$Current_Id =get_current_user_id();


echo $_POST['url'] . '/n';
if(strpos($_POST['url'], 'draft') == false ){
    $post_status = array('publish', 'privatised', 'draft', 'inherit', 'future');
}
else{
    $post_status = array('draft');
}

echo print_r($post_status) . '/n';

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
    's'     => $_POST['search'],
 );

$pagenum = ($_POST['pagenum'] ? $_POST['pagenum'] : '1');
$user_posts = new WP_Query( $args);

    if( !empty($user_posts)){   
    ?>

    <?php 
    while ($user_posts->have_posts()) {
        $user_posts->the_post();

The above code while seems correct does not work. When I use this code, it ignores the Post Status. Say I submit the form, from url "https://milyin.com/draft/" and the Input Field has text "Elon Musk" in it. The AJAX should do WP_Query and return, posts from current user, that have the word "Elon Musk" in them and also only show the "draft" posts. unfortunately It filters and shows Elon Musk posts from all Post Statuses.

My Initial suspicion was that $_POST['url'] is undefined or wrongly defined. But then I randomly decided to remove the search parameter. That is shown below.

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
 );

As U can see the only thing changed in the above code is that the line 's' => $_POST['search'], is missing. And when I submitted the form this time. It showed only the draft posts as I expected. Then I tried the opposite.

I tried, to remove 's' => $_POST['search'], and include 'post_status' => $post_status, and boom it works again. It was just showing all draft posts as I expect it to do.

So In Nutshell, My code runs perfect, if I just Query post_status, it also runs perfect when I just query s but it does not run when I s and post_status both together. Key Things to remember, this code is running using AJAX, the $_POST[‘url’] seems obvious suspect, but it is running perfectly in my opinion, and I am using this code to echo (not returning any thing) Title Featured Image etc.

When I run the query with s and post_status together, it just shows search results from All Post_type, also, when I run this code directly without AJAX, then also it works.


Get this bounty!!!

#StackBounty: #php #wp-query #ajax #search #query-posts Can't search posts using WP_QUERY inside AJAX Function

Bounty: 50

WP_Query is used to get posts via simple arguments provided by it. WordPress provides an argument called ‘s’ for search. It basically searches content of all posts and lists the ones with that string anywhere. There is another WP_Query argument called, post_status, which can be used to filter posts, with particular Post_Status

Do note that this code is enclosed in AJAX function. I am calling an AJAX function from frontend, that passes the url of the current page to $_POST['url']. $_POST['url'] is defined and please don’t worry about it. I want the Query to have only draft posts if the url has "draft/" in it. By echoing the variables I know, that the variables themselves are working fine.

So below is the WP_Query

$Current_Id =get_current_user_id();


echo $_POST['url'] . '/n';
if(strpos($_POST['url'], 'draft') == false ){
    $post_status = array('publish', 'privatised', 'draft', 'inherit', 'future');
}
else{
    $post_status = array('draft');
}

echo print_r($post_status) . '/n';

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
    's'     => $_POST['search'],
 );

$pagenum = ($_POST['pagenum'] ? $_POST['pagenum'] : '1');
$user_posts = new WP_Query( $args);

    if( !empty($user_posts)){   
    ?>

    <?php 
    while ($user_posts->have_posts()) {
        $user_posts->the_post();

The above code while seems correct does not work. When I use this code, it ignores the Post Status. Say I submit the form, from url "https://milyin.com/draft/" and the Input Field has text "Elon Musk" in it. The AJAX should do WP_Query and return, posts from current user, that have the word "Elon Musk" in them and also only show the "draft" posts. unfortunately It filters and shows Elon Musk posts from all Post Statuses.

My Initial suspicion was that $_POST['url'] is undefined or wrongly defined. But then I randomly decided to remove the search parameter. That is shown below.

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
 );

As U can see the only thing changed in the above code is that the line 's' => $_POST['search'], is missing. And when I submitted the form this time. It showed only the draft posts as I expected. Then I tried the opposite.

I tried, to remove 's' => $_POST['search'], and include 'post_status' => $post_status, and boom it works again. It was just showing all draft posts as I expect it to do.

So In Nutshell, My code runs perfect, if I just Query post_status, it also runs perfect when I just query s but it does not run when I s and post_status both together. Key Things to remember, this code is running using AJAX, the $_POST[‘url’] seems obvious suspect, but it is running perfectly in my opinion, and I am using this code to echo (not returning any thing) Title Featured Image etc.

When I run the query with s and post_status together, it just shows search results from All Post_type, also, when I run this code directly without AJAX, then also it works.


Get this bounty!!!

#StackBounty: #php #wp-query #ajax #search #query-posts Can't search posts using WP_QUERY inside AJAX Function

Bounty: 50

WP_Query is used to get posts via simple arguments provided by it. WordPress provides an argument called ‘s’ for search. It basically searches content of all posts and lists the ones with that string anywhere. There is another WP_Query argument called, post_status, which can be used to filter posts, with particular Post_Status

Do note that this code is enclosed in AJAX function. I am calling an AJAX function from frontend, that passes the url of the current page to $_POST['url']. $_POST['url'] is defined and please don’t worry about it. I want the Query to have only draft posts if the url has "draft/" in it. By echoing the variables I know, that the variables themselves are working fine.

So below is the WP_Query

$Current_Id =get_current_user_id();


echo $_POST['url'] . '/n';
if(strpos($_POST['url'], 'draft') == false ){
    $post_status = array('publish', 'privatised', 'draft', 'inherit', 'future');
}
else{
    $post_status = array('draft');
}

echo print_r($post_status) . '/n';

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
    's'     => $_POST['search'],
 );

$pagenum = ($_POST['pagenum'] ? $_POST['pagenum'] : '1');
$user_posts = new WP_Query( $args);

    if( !empty($user_posts)){   
    ?>

    <?php 
    while ($user_posts->have_posts()) {
        $user_posts->the_post();

The above code while seems correct does not work. When I use this code, it ignores the Post Status. Say I submit the form, from url "https://milyin.com/draft/" and the Input Field has text "Elon Musk" in it. The AJAX should do WP_Query and return, posts from current user, that have the word "Elon Musk" in them and also only show the "draft" posts. unfortunately It filters and shows Elon Musk posts from all Post Statuses.

My Initial suspicion was that $_POST['url'] is undefined or wrongly defined. But then I randomly decided to remove the search parameter. That is shown below.

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
 );

As U can see the only thing changed in the above code is that the line 's' => $_POST['search'], is missing. And when I submitted the form this time. It showed only the draft posts as I expected. Then I tried the opposite.

I tried, to remove 's' => $_POST['search'], and include 'post_status' => $post_status, and boom it works again. It was just showing all draft posts as I expect it to do.

So In Nutshell, My code runs perfect, if I just Query post_status, it also runs perfect when I just query s but it does not run when I s and post_status both together. Key Things to remember, this code is running using AJAX, the $_POST[‘url’] seems obvious suspect, but it is running perfectly in my opinion, and I am using this code to echo (not returning any thing) Title Featured Image etc.

When I run the query with s and post_status together, it just shows search results from All Post_type, also, when I run this code directly without AJAX, then also it works.


Get this bounty!!!

#StackBounty: #php #wp-query #ajax #search #query-posts Can't search posts using WP_QUERY inside AJAX Function

Bounty: 50

WP_Query is used to get posts via simple arguments provided by it. WordPress provides an argument called ‘s’ for search. It basically searches content of all posts and lists the ones with that string anywhere. There is another WP_Query argument called, post_status, which can be used to filter posts, with particular Post_Status

Do note that this code is enclosed in AJAX function. I am calling an AJAX function from frontend, that passes the url of the current page to $_POST['url']. $_POST['url'] is defined and please don’t worry about it. I want the Query to have only draft posts if the url has "draft/" in it. By echoing the variables I know, that the variables themselves are working fine.

So below is the WP_Query

$Current_Id =get_current_user_id();


echo $_POST['url'] . '/n';
if(strpos($_POST['url'], 'draft') == false ){
    $post_status = array('publish', 'privatised', 'draft', 'inherit', 'future');
}
else{
    $post_status = array('draft');
}

echo print_r($post_status) . '/n';

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
    's'     => $_POST['search'],
 );

$pagenum = ($_POST['pagenum'] ? $_POST['pagenum'] : '1');
$user_posts = new WP_Query( $args);

    if( !empty($user_posts)){   
    ?>

    <?php 
    while ($user_posts->have_posts()) {
        $user_posts->the_post();

The above code while seems correct does not work. When I use this code, it ignores the Post Status. Say I submit the form, from url "https://milyin.com/draft/" and the Input Field has text "Elon Musk" in it. The AJAX should do WP_Query and return, posts from current user, that have the word "Elon Musk" in them and also only show the "draft" posts. unfortunately It filters and shows Elon Musk posts from all Post Statuses.

My Initial suspicion was that $_POST['url'] is undefined or wrongly defined. But then I randomly decided to remove the search parameter. That is shown below.

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
 );

As U can see the only thing changed in the above code is that the line 's' => $_POST['search'], is missing. And when I submitted the form this time. It showed only the draft posts as I expected. Then I tried the opposite.

I tried, to remove 's' => $_POST['search'], and include 'post_status' => $post_status, and boom it works again. It was just showing all draft posts as I expect it to do.

So In Nutshell, My code runs perfect, if I just Query post_status, it also runs perfect when I just query s but it does not run when I s and post_status both together. Key Things to remember, this code is running using AJAX, the $_POST[‘url’] seems obvious suspect, but it is running perfectly in my opinion, and I am using this code to echo (not returning any thing) Title Featured Image etc.

When I run the query with s and post_status together, it just shows search results from All Post_type, also, when I run this code directly without AJAX, then also it works.


Get this bounty!!!

#StackBounty: #php #wp-query #ajax #search #query-posts Can't search posts using WP_QUERY inside AJAX Function

Bounty: 50

WP_Query is used to get posts via simple arguments provided by it. WordPress provides an argument called ‘s’ for search. It basically searches content of all posts and lists the ones with that string anywhere. There is another WP_Query argument called, post_status, which can be used to filter posts, with particular Post_Status

Do note that this code is enclosed in AJAX function. I am calling an AJAX function from frontend, that passes the url of the current page to $_POST['url']. $_POST['url'] is defined and please don’t worry about it. I want the Query to have only draft posts if the url has "draft/" in it. By echoing the variables I know, that the variables themselves are working fine.

So below is the WP_Query

$Current_Id =get_current_user_id();


echo $_POST['url'] . '/n';
if(strpos($_POST['url'], 'draft') == false ){
    $post_status = array('publish', 'privatised', 'draft', 'inherit', 'future');
}
else{
    $post_status = array('draft');
}

echo print_r($post_status) . '/n';

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
    's'     => $_POST['search'],
 );

$pagenum = ($_POST['pagenum'] ? $_POST['pagenum'] : '1');
$user_posts = new WP_Query( $args);

    if( !empty($user_posts)){   
    ?>

    <?php 
    while ($user_posts->have_posts()) {
        $user_posts->the_post();

The above code while seems correct does not work. When I use this code, it ignores the Post Status. Say I submit the form, from url "https://milyin.com/draft/" and the Input Field has text "Elon Musk" in it. The AJAX should do WP_Query and return, posts from current user, that have the word "Elon Musk" in them and also only show the "draft" posts. unfortunately It filters and shows Elon Musk posts from all Post Statuses.

My Initial suspicion was that $_POST['url'] is undefined or wrongly defined. But then I randomly decided to remove the search parameter. That is shown below.

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
 );

As U can see the only thing changed in the above code is that the line 's' => $_POST['search'], is missing. And when I submitted the form this time. It showed only the draft posts as I expected. Then I tried the opposite.

I tried, to remove 's' => $_POST['search'], and include 'post_status' => $post_status, and boom it works again. It was just showing all draft posts as I expect it to do.

So In Nutshell, My code runs perfect, if I just Query post_status, it also runs perfect when I just query s but it does not run when I s and post_status both together. Key Things to remember, this code is running using AJAX, the $_POST[‘url’] seems obvious suspect, but it is running perfectly in my opinion, and I am using this code to echo (not returning any thing) Title Featured Image etc.

When I run the query with s and post_status together, it just shows search results from All Post_type, also, when I run this code directly without AJAX, then also it works.


Get this bounty!!!

#StackBounty: #php #wp-query #ajax #search #query-posts Can't search posts using WP_QUERY inside AJAX Function

Bounty: 50

WP_Query is used to get posts via simple arguments provided by it. WordPress provides an argument called ‘s’ for search. It basically searches content of all posts and lists the ones with that string anywhere. There is another WP_Query argument called, post_status, which can be used to filter posts, with particular Post_Status

Do note that this code is enclosed in AJAX function. I am calling an AJAX function from frontend, that passes the url of the current page to $_POST['url']. $_POST['url'] is defined and please don’t worry about it. I want the Query to have only draft posts if the url has "draft/" in it. By echoing the variables I know, that the variables themselves are working fine.

So below is the WP_Query

$Current_Id =get_current_user_id();


echo $_POST['url'] . '/n';
if(strpos($_POST['url'], 'draft') == false ){
    $post_status = array('publish', 'privatised', 'draft', 'inherit', 'future');
}
else{
    $post_status = array('draft');
}

echo print_r($post_status) . '/n';

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
    's'     => $_POST['search'],
 );

$pagenum = ($_POST['pagenum'] ? $_POST['pagenum'] : '1');
$user_posts = new WP_Query( $args);

    if( !empty($user_posts)){   
    ?>

    <?php 
    while ($user_posts->have_posts()) {
        $user_posts->the_post();

The above code while seems correct does not work. When I use this code, it ignores the Post Status. Say I submit the form, from url "https://milyin.com/draft/" and the Input Field has text "Elon Musk" in it. The AJAX should do WP_Query and return, posts from current user, that have the word "Elon Musk" in them and also only show the "draft" posts. unfortunately It filters and shows Elon Musk posts from all Post Statuses.

My Initial suspicion was that $_POST['url'] is undefined or wrongly defined. But then I randomly decided to remove the search parameter. That is shown below.

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
 );

As U can see the only thing changed in the above code is that the line 's' => $_POST['search'], is missing. And when I submitted the form this time. It showed only the draft posts as I expected. Then I tried the opposite.

I tried, to remove 's' => $_POST['search'], and include 'post_status' => $post_status, and boom it works again. It was just showing all draft posts as I expect it to do.

So In Nutshell, My code runs perfect, if I just Query post_status, it also runs perfect when I just query s but it does not run when I s and post_status both together. Key Things to remember, this code is running using AJAX, the $_POST[‘url’] seems obvious suspect, but it is running perfectly in my opinion, and I am using this code to echo (not returning any thing) Title Featured Image etc.

When I run the query with s and post_status together, it just shows search results from All Post_type, also, when I run this code directly without AJAX, then also it works.


Get this bounty!!!

#StackBounty: #php #wp-query #ajax #search #query-posts Can't search posts using WP_QUERY inside AJAX Function

Bounty: 50

WP_Query is used to get posts via simple arguments provided by it. WordPress provides an argument called ‘s’ for search. It basically searches content of all posts and lists the ones with that string anywhere. There is another WP_Query argument called, post_status, which can be used to filter posts, with particular Post_Status

Do note that this code is enclosed in AJAX function. I am calling an AJAX function from frontend, that passes the url of the current page to $_POST['url']. $_POST['url'] is defined and please don’t worry about it. I want the Query to have only draft posts if the url has "draft/" in it. By echoing the variables I know, that the variables themselves are working fine.

So below is the WP_Query

$Current_Id =get_current_user_id();


echo $_POST['url'] . '/n';
if(strpos($_POST['url'], 'draft') == false ){
    $post_status = array('publish', 'privatised', 'draft', 'inherit', 'future');
}
else{
    $post_status = array('draft');
}

echo print_r($post_status) . '/n';

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
    's'     => $_POST['search'],
 );

$pagenum = ($_POST['pagenum'] ? $_POST['pagenum'] : '1');
$user_posts = new WP_Query( $args);

    if( !empty($user_posts)){   
    ?>

    <?php 
    while ($user_posts->have_posts()) {
        $user_posts->the_post();

The above code while seems correct does not work. When I use this code, it ignores the Post Status. Say I submit the form, from url "https://milyin.com/draft/" and the Input Field has text "Elon Musk" in it. The AJAX should do WP_Query and return, posts from current user, that have the word "Elon Musk" in them and also only show the "draft" posts. unfortunately It filters and shows Elon Musk posts from all Post Statuses.

My Initial suspicion was that $_POST['url'] is undefined or wrongly defined. But then I randomly decided to remove the search parameter. That is shown below.

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
 );

As U can see the only thing changed in the above code is that the line 's' => $_POST['search'], is missing. And when I submitted the form this time. It showed only the draft posts as I expected. Then I tried the opposite.

I tried, to remove 's' => $_POST['search'], and include 'post_status' => $post_status, and boom it works again. It was just showing all draft posts as I expect it to do.

So In Nutshell, My code runs perfect, if I just Query post_status, it also runs perfect when I just query s but it does not run when I s and post_status both together. Key Things to remember, this code is running using AJAX, the $_POST[‘url’] seems obvious suspect, but it is running perfectly in my opinion, and I am using this code to echo (not returning any thing) Title Featured Image etc.

When I run the query with s and post_status together, it just shows search results from All Post_type, also, when I run this code directly without AJAX, then also it works.


Get this bounty!!!

#StackBounty: #php #wp-query #ajax #search #query-posts Can't search posts using WP_QUERY inside AJAX Function

Bounty: 50

WP_Query is used to get posts via simple arguments provided by it. WordPress provides an argument called ‘s’ for search. It basically searches content of all posts and lists the ones with that string anywhere. There is another WP_Query argument called, post_status, which can be used to filter posts, with particular Post_Status

Do note that this code is enclosed in AJAX function. I am calling an AJAX function from frontend, that passes the url of the current page to $_POST['url']. $_POST['url'] is defined and please don’t worry about it. I want the Query to have only draft posts if the url has "draft/" in it. By echoing the variables I know, that the variables themselves are working fine.

So below is the WP_Query

$Current_Id =get_current_user_id();


echo $_POST['url'] . '/n';
if(strpos($_POST['url'], 'draft') == false ){
    $post_status = array('publish', 'privatised', 'draft', 'inherit', 'future');
}
else{
    $post_status = array('draft');
}

echo print_r($post_status) . '/n';

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
    's'     => $_POST['search'],
 );

$pagenum = ($_POST['pagenum'] ? $_POST['pagenum'] : '1');
$user_posts = new WP_Query( $args);

    if( !empty($user_posts)){   
    ?>

    <?php 
    while ($user_posts->have_posts()) {
        $user_posts->the_post();

The above code while seems correct does not work. When I use this code, it ignores the Post Status. Say I submit the form, from url "https://milyin.com/draft/" and the Input Field has text "Elon Musk" in it. The AJAX should do WP_Query and return, posts from current user, that have the word "Elon Musk" in them and also only show the "draft" posts. unfortunately It filters and shows Elon Musk posts from all Post Statuses.

My Initial suspicion was that $_POST['url'] is undefined or wrongly defined. But then I randomly decided to remove the search parameter. That is shown below.

$args = array(
    'post_type'     => array('post', 'download', 'page'),
    'post_status'   => array('draft'),
    'author'        => $Current_Id,
    'numberposts'   => -1,
    'orderby'           => 'post_date',
    'order'             => 'DESC',
    'posts_per_page'    => 20,
    'paged'      => $_POST['pagenum'], 
 );

As U can see the only thing changed in the above code is that the line 's' => $_POST['search'], is missing. And when I submitted the form this time. It showed only the draft posts as I expected. Then I tried the opposite.

I tried, to remove 's' => $_POST['search'], and include 'post_status' => $post_status, and boom it works again. It was just showing all draft posts as I expect it to do.

So In Nutshell, My code runs perfect, if I just Query post_status, it also runs perfect when I just query s but it does not run when I s and post_status both together. Key Things to remember, this code is running using AJAX, the $_POST[‘url’] seems obvious suspect, but it is running perfectly in my opinion, and I am using this code to echo (not returning any thing) Title Featured Image etc.

When I run the query with s and post_status together, it just shows search results from All Post_type, also, when I run this code directly without AJAX, then also it works.


Get this bounty!!!