Kim Oliveros
Kim Oliveros

Reputation: 711

Ajax wont retrieve the file from php file

Hi guys this script was working fine when I add a console.log but as soon as I replaced the console.log with the $.ajax() function it wont give me the result back from the php file the ajax function I used was working from my other projects but I cant seem to find out why it wont work on this snippet

Here is my js code :

     $(document).ready(function(){

        $("#qs").find(".chs").each(function(i,obj){
             $(this).addClass("chs"+i);

             $(".chs"+i).on("click",function(){
                var s = $(this).data("lvs"),carrier= {"vars":s};

            $.ajax({
               url: aScript.php,
               type: "POST",
               data: carrier,
               dataType: "json"
                    success: function(data) { 
                        console.log(data) }
                });
            });
        });

  });

my php file looks like this

<?php
$json = $_POST['carrier'];
$data = json_decode($json);
$d = $data->vars;
echo $d;
?>
<input type="hidden" id="ss" value="<?=$d?>" />

can someone review this file for me cause I cant seem to find whats wrong please help me find out whats wrong with this script

Upvotes: 0

Views: 41

Answers (2)

Musa
Musa

Reputation: 97672

There are some issues with your code

  1. in this line url: aScript.php, the url string is not quoted, it should be url: 'aScript.php',
  2. you set dataType: "json" but aScript.php returns html instead of json, remove that line
  3. the data you're passing is not json, it will be serialized into key=value pairs and you'll be able to access it via $d = $_POST['vars'];

Upvotes: 1

pixeline
pixeline

Reputation: 17974

You should wrap the filename inside quotes, as it is a string variable

$.ajax({
               url: 'aScript.php',
               type: "POST",
               data: carrier,
               dataType: "json",
                    success: function(data) { 
                        console.log(data) }
                });
            });

Upvotes: 2

Related Questions