Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

ajax

php

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);    
?>
like image 216
jibin dcruz Avatar asked Mar 26 '13 12:03

jibin dcruz


People also ask

How do I pass a value to a PHP script using AJAX?

ready(function() { $("#raaagh"). click(function(){ $. ajax({ url: 'ajax. php', //This is the current doc type: "POST", data: ({name: '145'}), //variables should be pass like this success: function(data){ console.

Can AJAX be used with PHP?

Start Using AJAX Today In our PHP tutorial, we will demonstrate how AJAX can update parts of a web page, without reloading the whole page. The server script will be written in PHP. If you want to learn more about AJAX, visit our AJAX tutorial.


1 Answers

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  
?>
like image 71
Rohan Kumar Avatar answered Sep 28 '22 17:09

Rohan Kumar