简体   繁体   中英

How to get a value back to my ajax result from a PHP file

I am making a post to a php file like this:

$( document ).ready(function() {
  $(document).on('click', '.menulistnaam', function (){
        var menucatnaam = $(this).attr('id');

      $.post("include/menuinclude.php?menucat="+menucatnaam, function(result){
          $("#menukaart").html(result);
      });
  });
});

All works fine but I would like to send a specific result back to this code.

In my PHP I have the following:

$menucatnaam = $_GET['menucat'];

$menu = "
select
  cnt.catid, cat.id, cnt.title, cnt.introtext, cnt.fulltext, cnt.ordering, cnt.images, cnt.alias, cnt.state, f.item_id, cat.id, cat.title,
  max(case when f.field_id = 8 then f.value end) as nieuw,
  max(case when f.field_id = 7 then f.value end) as beschrijving,
  max(case when f.field_id = 5 then f.value end) as prijs,
  max(case when f.field_id = 4 then f.value end) as inhoud,
  max(case when f.field_id = 3 then f.value end) as media
  from snm_fields_values f
  join snm_content cnt
  on cnt.id = f.item_id
  join snm_categories cat
  on cnt.catid = cat.id
  where cnt.state = 1
  and cat.alias = '".$menucatnaam."'
  group by f.item_id
  order by f.item_id, media, beschrijving, prijs, inhoud, nieuw
";

How can I send back the value of $menucatnaam ?

In the end I want to check what anchor tag was clicked and give it an active class.

I googled a bit and found out I had to create an array and then encode it with json but I couldn't get it to work.

My attempt was this:

$aliasjson = json_encode(array("aliasresult"=>"$menucatnaam"));
echo $aliasjson;

And then my js:

$.post('include/menuinclude.php', {"menucat": menucatnaam}, function (result) {
    $("#menukaart").html(result);
    console.log(result.aliasresult);
}, 'json');

But that didn't give me the result I wanted at all, when I clicked an anchor tag nothing was happening.

How can I do this?

In ajax call add below parameter

dataType: "json",//tells jQuery that you want it to parse the returned JSON

and after getting response

result = jQuery.parseJSON(result);//parsing JSON to string
console.log(result.result);

or else don't change any jquery code just echo required paramter from PHP

echo $menucatnaam;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM