Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
476 views
in Technique[技术] by (71.8m points)

jquery - Using AJAX to pass variable to PHP and retrieve those using AJAX again

I want to pass values to a PHP script so i am using AJAX to pass those, and in the same function I am using another AJAX to retrieve those values.

The problem is that the second AJAX is not retrieving any value from the PHP file. Why is this? How can I store the variable passed on to the PHP script so that the second AJAX can retrieve it?

My code is as follows:

AJAX CODE:

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: 145}),
            success: function(data){
                console.log(data);
            }
        });  
        $.ajax({
            url:'ajax.php',
            data:"",
            dataType:'json',
            success:function(data1){
                var y1=data1;
                console.log(data1);
            }
        });
    });
});

PHP CODE:

<?php
$userAnswer = $_POST['name'];    
echo json_encode($userAnswer);    
?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Use dataType:"json" for json data

$.ajax({
     url: 'ajax.php', //This is the current doc
     type: "POST",
     dataType:'json', // add json datatype to get json
     data: ({name: 145}),
     success: function(data){
         console.log(data);
     }
});  

Read Docs http://api.jquery.com/jQuery.ajax/

Also in PHP

<?php
  $userAnswer = $_POST['name']; 
  $sql="SELECT * FROM <tablename> where color='".$userAnswer."'" ;
  $result=mysql_query($sql);
  $row=mysql_fetch_array($result);
  // for first row only and suppose table having data
  echo json_encode($row);  // pass array in json_encode  
?>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...