I have three php files.
main.php - to use stored Ajax response.
filter.php - to send Ajax request and get response
insert.php - to store Ajax response for using in main.php
Primary purpose of doing all these thing is to use client side values using PHP code because server and client can't exchange variable values each other.
The response should be stored in php variable in main.php.
main.php:
?>
<script>
$.ajax({
type: "POST",
url: "filter.php",
data: { id1: name, id2:"employees"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { id1: res },
success:function(data){
alert(data);
}
});
});
<script>
<?php
$ajaxResponse = ???? <need to get value of data over here>
filter.php:
// Return employee names
if ($_POST['id1'] == "name" && $_POST['id2'] == "employees") {
$conn = mysqli_connect (DB_HOST, DB_USER, DB_PASSWORD, DB_NAME);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT " .$_POST['id1']. " FROM 1_employees";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_array($result)) {
$rows[] = $row['name'];
}
}
echo json_encode($rows);
mysqli_close($conn);
exit (0);
}
insert.php:
if ($_POST) {
if ($_POST['id1'] !== "") {
echo $_POST['id1'];
}
}
So how can I get ajax response value in main.php at $ajaxResponse = ?????
You can't use it that way.
Why:
javascript/jQuery is a scripting language which runs in browser when DOM is fully loaded and elements are available to make selectors.
While php is serverside language which runs on server way before page load.
So in short you can't assign a ajax response to a php variable.
one thing you can do to have a hidden input and put the response value in it and you can get that value to use it.
success:function(data){
alert(data);
$('#hiddenInputId').val(data); // set the response data to the hidden input and use it.
}
You can create a div where you want to display the response contents
in your case it is after <script> tag
And use innerHTML to display the contents
Use this code
<script>
$.ajax({
type: "POST",
url: "filter.php",
data: { id1: name, id2:"employees"},
success:function(response) {
var res = response;
$.ajax({
type: "POST",
url: "insert.php",
data: { id1: res },
success:function(data){
$("#responseContent").html(data);
}
});
});
<script>
<div id="responseContent"></div>
Let me know if it is helpful
Here is the answer:
Get names in main.php using below way:
-------- filter.php ----------
session_start(); //at the top
$_SESSION['names'] = json_encode($rows);
-------- main.php ----------
session_start();
$issued_to = explode(",", $names);
session_unset();
session_destroy();
The answer is to simply use Javascript to store the response from Ajax into a hidden variable and make use of that for further action. That solved my query and I'm sure many will actually need this too!
Related
I am using AJAX and trying to return variables that I got after querying the database in the modcomp.php file, I am then trying to input those values back into my main site to put into input boxes. Below is what I have tried but it is not working. Is this because I am getting variables in PHP and then bringing them back to use in JS / jQuery? Doing a few searches it looks like JSON might be the answer but looking at JSON I havent seen an example of how I could run code to query the database and then put that info in JSON format to pull back? My goal is to eventually pull back all 10 variables.
$.ajax({
method: "POST",
url: "modcomp.php",
data: {item: $(this).val()}
success: function(data) {
$('#itemnumber').val($itemnumber);
$('#cost').val($cost);
}
});
The modcomp.php file
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
$id=$row[0];
$itemnumber=$row[1];
$itemname=$row[2];
$cost=$row[3];
$company=$row[4];
$contact=$row[5];
$address1=$row[6];
$address2=$row[7];
$phone=$row[8];
$part=$row[9];
//print_r ($id." ".$itemnumber." ".$itemname." ".$cost." ".$company." ".$contact." ".$address1." ".$address2." ".$phone." ".$part);
} else {
print_r("Issue with query");
}
}
?>
The easiest way to do that is just set your jquery.ajax to expect a json as return:
$.ajax({
method: "POST",
dataType: "JSON",
/** others attributes **/
After, convert your return to a json and print it (just it, nothing more) at php script:
//a better approach is return the column name (fetch_assoc)
echo json_encode($row);
Now, your return can be used as json:
success: function(data) {
data.column_name
}
json_encode is the answer
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
$array = ();
$array['id']=$row[0];
$array['itemnumber']=$row[1];
$array['itemname']=$row[2];
.
.
$array['part']=$row[9];
$array['status'] = true;
echo json_encode($array);
} else {
echo json_encode(array(status => false , msg => "Issue with query");
}
}
Then in your js code use json as
$.ajax({
method: "POST",
url: "modcomp.php",
data: {item: $(this).val()}
success: function(data) {
data = JSON.parse(data); // to parse json string to object
if(data.status){
$('#itemnumber').val(data.itemnumber);
$('#cost').val(data.cost);
}
}
});
you should return your value from your php file as
<?php
if(array_key_exists("item", $_POST)) {
include("connection.php");
$query="SELECT * FROM components WHERE itemname = '".mysqli_real_escape_string($link,$_POST['item'])."' LIMIT 1";
if ($result=mysqli_query($link,$query)) {
$row=mysqli_fetch_array($result);
return json_encode($row,true);
} else {
return json_encode("Some error occured");
}
}
don't use print_r() function to return data from your php file
And set the datatype in ajax as JSON to parse the json data to be returned as
$.ajax({
method: "POST",
url: "modcomp.php",
datatype:'json',
data: {item: $(this).val()}
success: function(data) {
$('#itemnumber').val(data.itemnumber);
$('#cost').val(data.cost);
}
});
Now you are able to use your json data using the dot(.) operator like
$('#cost').val(data.cost);
Right now I need to use phonegap to call on a php script on another webserver to retrieve data from a database i have. Running the script with hard codes retrieves the data correctly but it appears as tho either the ajax call is not returning anything or not even getting the data as post. Currently in the console I am getting "Origin null is not allowed by Access-Control-Allow-Origin. "
$(document).ready(function() {
$('.check').click(function(){
alert("Step1");
var thisID = $(this).attr('id');
alert(thisID);
$.ajax({
type: "POST",
url: "http://csmaster.sxu.edu/group2/group2/CougarLunch/retrieveColumn.php",
data: { ID: thisID},
cache: false,
async:true,
datatype: "json",
success: function(data)
{
console.log(data);
alert(data.ItemID);
}
});
});
});
PHP if it is relevent I doubt it tho
if(isset($_POST['ID']))
{
$ID = $_POST['ID'];
function retrieve($ID)
{
$stmt = $mysqli->query("SELECT * FROM group2.menu WHERE ItemID = $ID");
if($stmt->num_rows) //if there is an ID of this name
{
$row = $stmt->fetch_assoc();
echo $row;
print json_encode($row);
}
}
Add this line to the top of php file to allow access:
header("Access-Control-Allow-Origin: "*");
you need to pass in AndroidManifest.xml
<access origin="*" />
phonegap doc
i am writing a online tictactoe game and i have a function in javascript that check that if some where clicked in the screen is not X or O then mark it with X or O and then update the database where is clicked. here is my javascript code in play.php page (this is in ) where check that with isEmpty function . path is the variable that detect which cells in tictactoe is clicked(from 1 to 9) :
....
if (isEmpty(xBoard, oBoard, bit)) {
path.push(y*3+x+1);
alert(path);
markBit(bit, playerXO);
$.ajax({
type: "POST",
url: "gameProcess.php",
data: {
'ID' : path
},
dataType: "json",
success: function(){
alert('success');
},
});
....
i use ajax to update something in database with PHP (gameProcess.php) and send 'ID' value to write in a table of mysql Database.here is my gameProcess.php code:
<?php
function post($key) {
if (isset($_POST[$key]))
return $_POST[$key];
return false;
}
// setup the database connect
$cxn = mysql_connect('localhost', 'root', 'Mazda1428');
if (!$cxn)
exit;
mysql_select_db('irgc', $cxn);
// check if we can get hold of the form field
if (!post('ID'))
exit;
// let make sure we escape the data
$val = mysql_real_escape_string(post('ID'), $cxn);
// lets setup our insert query
$sql = "UPDATE game SET sequence=".$val." WHERE id = 2;";
// lets run our query
$result = mysql_query($sql, $cxn);
// setup our response "object"
$resp = new stdClass();
$resp->success = false;
if($result) {
$resp->success = true;
}
print json_encode($resp);
?>
but when i open the browser and go in play.php and click in tictactoe game the first time is OK. but after that no thing will add in DB (but still i see the alert('success')).
finally,sorry for bad english.
disable cache and try again.
$.ajax({
type: "POST",
cache: false,
url: "gameProcess.php",
data: {
'ID' : path
},
dataType: "json",
success: function(){
alert('success');
},
});
Perhaps you should add a random URL address parameter
While using jquery $.ajax or $.post, to submit a value (say uid {user id}) how can I define a callback function to retrieve multiple values from the php script and retrieve values from my mysql table say(user details, corresponding to the uid) and store them in vars, using the default datatype:datatype???
Can anyone please show me both the jquery and php scripts please. And yes the database is runninga mySQL 5.5.24 and PHP version is 5.3
instead of using $.ajax you can also use this...
var id=$("#id").val();
$.getJSON('script.php', {id:id}, function(json) {
var id=json.id;
var name=json.name;
var email=json.email;
});
}
in your php scrip..
<?php
mysql_connect($host,$dbuser,$dbpass);
mysql_select_db($db_name);
$id=$_GET['id'];
$query="select * from tbl_name where id='$id'";
$rs=mysql_query($query);
$row=mysql_fetch_assoc($rs);
$id=$row['id'];
$name=$row['name'];
$email=$row['email'];
$data=array("id"=>$id,"name"=>$name,"email"=>$email);
echo json_encode($data);
?>
The best way to do this would be to send it back to javascript as a json object.... so for your user example
// assuming post containing a username, using pseudo code for db access
$row = $db->fetchAssoc("select * from users where username = '".dbEscape($_POST["username"]."'");
header("Content Type: application/json");
echo json_encode($row);
ajax code will be like follows
$.ajax({
type: "POST",
url: "your_page.php",
data: { param1: "val1", param2: "val2" }
}).done(function( data) {
// do your callback operation
});
get values from your_page.php like below
$_POST["param1"] , $_POST["param2"]
if you want to know more then click here
I think this will solve your problem.
<script type="text/javascript">
$.ajax({ // ajax call starts
url: 'serverside.php', // JQuery loads serverside.php
data: 'button=' + $(this).val(), // Send value of the clicked button
dataType: 'json', // Choosing a JSON datatype
success: function(data) // Variable data contains the data we get from serverside
{
}
});
</script>
dataType: json..so jason will return multiple values. from you php script
echo json_encode($array_of_val);
$.ajax({
type: "POST",
dataType:"html",
url: "ajax_page.php",
data:"params1="$params1"¶ms2="+$params2,
}).done(function(value) {
// write your callback operation
});
you can get your data on ajax_page.php using an post method like
$_POST['params1'];
and
$_POST['params2'];
$query= select statement
$items=array();
while ($row = mysql_fetch_object($rs)) {
array_push($items, $row);
}
$result["rows"] = $items;
echo json_encode($result);
So far I have something like this:
//HTML
<body onload=getRoomTemp();>
//JS
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
datatype: "text";
data: {
temp: temp
}
}).done(function () { $('#getRoomTemp').append(text); });
}
//PHP
<?php
if (isset($_POST['temp'])) {
require('database.php');
$query = ("SELECT temp FROM tempWHERE tempID=1");
$res = mysql_query($query) or die("ERROR ".__LINE__.": ".mysql_error());
while ($ar = mysql_fetch_array($res)) {
$temperatureIn = $ar['temp'];
echo $temperatureIn;
}
}
?>
So, when my HTML body loads, I would like to make query and show query result in div called "getRoomTemp" with AJAX. Later, I will need the same technique to insert data in MySQL (single number value) on button click.
I can't find the problem with my current code, tried different dataType for ajax but no success. Please help..
You have 2 undefined identifiers temp and text, try
function getRoomTemp() {
$.ajax({
type: "POST",
url: "getRoomTemp.php",
dataType: "text",
data: {
temp: 'temp'
}
}).done(function (text) { $('#getRoomTemp').append(text); });
}