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 : <...

问题:

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();
      }
    });
  });
}

回答1:

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();
  }
 });
});

回答2:

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);
  • 发表于 2019-03-30 16:54
  • 阅读 ( 226 )
  • 分类:sof

条评论

请先 登录 后评论
不写代码的码农
小编

篇文章

作家榜 »

  1. 小编 文章
返回顶部
部分文章转自于网络,若有侵权请联系我们删除