jockebq
jockebq

Reputation: 203

PHP variable to ajax, using variable inside jQuery function?

I am trying to send a variable with PHP to jQuery where I want to use this variable to append to a specific div.

Here is how I send the variables to jQuery onclick : <a onclick="searchEmail('<?php echo $location ?>');">

Then I begin the jQuery function like this: function searchEmail(location) {

This how the ajax part in the function looks like, and it works perfectly, but I want to use the location variable for this part of the code: $(location).appendTo('#test'); so that I append the text in location to a specific <p with ID #test.

function searchEmail(email,title,content,location,siteurl) {
  $(document).off("click", "#confirm").on("click", "#confirm", function (event) {
    var $url = (admin_ajax.url);
    $.ajax({
      type: "POST",
      url: $url,
      datatype: "html",
      data: { 'action': 'search_notify_email', email: email, title: title, content: content, location: location, siteurl: siteurl },
      success: function() {
        searchNotification();
        console.log( location );
        $('<p>'+location+'</p>').appendTo('#test');
      },error:function() {
        searchNotificationError();
      }
    });
  });
}

Upvotes: 1

Views: 96

Answers (2)

Lo&#239;s PEYTOUREAU
Lo&#239;s PEYTOUREAU

Reputation: 51

Why don't you create a variable in your jQuery code to store the location:

var location = '<?php echo $location; ?>';

$(document).off("click", "#confirm").on("click", "#confirm", function (event) {
var $url = (admin_ajax.url);
 $.ajax({
  type: "POST",
  url: $url,
  datatype: "html",
  data: { 'action': 'search_notify_email', location: location },
  success: function() {
    searchNotification();
    $(location).appendTo('#test'); /* or $('#test').append(location); */
  },error:function() {
    searchNotificationError();
  }
 });
});

Upvotes: 2

Zakaria Acharki
Zakaria Acharki

Reputation: 67525

so that I append the text in location to a specific

If you've just text then you need instead of appending the text() method :

$('#test').text(location); //Note it will replace the original text

Or:

var p = $('#test');
p.text(p.text() + location);

Upvotes: 1

Related Questions