How to do searching in PHP and AJAX?

How do I get variables from PHP through AJAX?

  • action.php <?php $a=$b[0]; ?> I want to get $a in index.php through AJAX.

  • Answer:

    In addition to some of the good suggestions here, you may also want to consider formatting your JSON output based on some convention or standard. I see a lot of the posts here suggesting that your just use json_encode() on an array, but the problem with their recommendations is that the payload only includes the data and no status. You'll want to know how to deal with certain types of conditions, which include success, errors, and failures. While there is no standard per se, one very lightweight JSON specification is JSend: http://labs.omniti.com/labs/jsend. There are more options out there, but not as lightweight. I would highly recommend that you stick to a convention, then in your AJAX call, add some error handling and don't always assume succesful returns. Also, you'll want to make sure you're not outputting anything before your JSON output, and immediately exit(); right after echoing your JSON response, which I also noticed a lot of people here failed to mention in their examples. You don't want any dummy data to get returned to your AJAX call, which will treat the response as malformed.

Ryan Flores at Quora Visit the source

Was this solution helpful to you?

Other answers

A2A Write a function in php which prints the value of the variable. Call that function using AJAX

Suresh Alse

There is a much simpler way to handle getting variables from PHP through AJAX by using the jQuery framework. I'll use your example, action.php. $.post("action.php", { }, onAction); Using jQuery post, you ask your PHP script, action.php, to give you a value. You would only need to use Javascript Object Notation (JSON), if you needed to get multiple variables in an array of sorts. Since you're not passing any information to your script, I have left the second parameter an empty array. function onAction(output) {   alert(output); } This function will receive the output from your script and show it in a Javascript popup. <?php $a=$b[0]; echo $a; ?> In your action.php script, you would just need to echo the variable, which gets passed via AJAX to the Javascript function onAction. I hope this helps. Thanks.

Rick Scolaro

First make sure it's the only data on the page then echo $a is enough or you can try to convert it to json: echo json_encode(['a' => $a]); and in js you get it by: data.a where data is the result of ajax request.

Greg Szczotka

Hello. This is the ajax script part of the html document: <script type="text/javascript">     $.ajax({         url: "index.php",         dataType: "text",         type: "POST",         timeout: 20000,         cache: false,         data: {             action : 'give me that'         }     })     .done(function(data,textStatus,jqXHR){         alert("index.php response with: " + data);     })     .fail(function(data,textStatus,errorThrown){ alert("Request failed!"); })     .always(function(data,textStatus,errorThrown){}); </script> This is the "index.php" file: <?php     header('Content-Type: text/plain; charset=UTF-8;');     $a = $b[0];     if (TRUE == isset($_POST['action'])) {         echo "this is the content of variable php $a: " . $a;     } ?> In this ajax setup, the browser will send a request to the file "index.php" on the server using method POST with variable "action" with content "give me that". In a form of a text, the server will response "this is the content of variable php $a: " including the content of $a. Highly recommend to read the documentation about jquery ajax methods on http://api.jquery.com/category/ajax/

Milen Genov

I created a action.php page that has a array $a with various indices value set and its value can be queried by GET/POST method using AJAX request. It returns a json string with status either success or failure according to index value queried by user and its value, if found. PHP Script [code] <?php   class retObj{     var $status;     var $value;     function __construct($st, $v=null){       $this->status = $st;       $this->value = $v;    } } $a = array(           1 => 'value 1',          5 => 70         ); if(isset($_GET['id']) && strlen($_GET['id'])){      $id = $_GET['id'];      if(isset($a[$id])){          echo json_encode(new retObj('Success', $a[$id]));      } else{          echo json_encode(new retObj('Failure'));      } } else{         echo json_encode(new retObj('Failure')); } ?> [/code] Javascript jQuery(window).load(function(){ var id = 5 //index value to query for jQuery.ajax({ type: "POST", url: "action.php?id="+id, dataType: "json", success: function(result){ if(result.status == "Success"){ console.log(result.value) // displays found value on console } else{ console.log('Error: No such variable value present') } }, error:function(){ console.log("Error: Unknown Error") } }) }) Hope this helps :)

Deepansh Sachdeva

Hi Raj, In your action.php assign $a value to input tag say named "a" (id="a"); Ajax code in action.php will be get the value of  "a" and sends it to index.php $.ajax({ type: "POST", url: "index.php", data: { "aValue": $("#a").val() }, dataType: 'json' success: function() { } }); In index.php the value of a should be accessible as $_POST['a'].

Swapna Vijayakumar

$.ajax( {   url : 'action.php',   type: "POST",   data : $('#editForm').serialize(),   success:function(response)    {                 if(response == '1'){                               }    } }); In your action.php file, get values by using $_POST['variable_name']. Hope this helps.

Dheeraj Dhawan

Related Q & A:

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.