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
Related
I want to send a javascript variable to php file which shows the comments on a webpage.
I was able to send this js variable to some other php file, but I can't do it with this comment-list.php file. I guess there is some problem with JSON.
function listComment() {
$.ajax({
url: "Komentarji/comment-list.php",
data : {page_num: page_num},
type : 'post',
success : function(response) {
}
});
$.post("Komentarji/comment-list.php", function(data) {
var data = JSON.parse(data);
.
.
.
The function is called here:
$(document).ready(function() {
listComment();
});
Inside comment-list.php I try to get the variable that was sent with ajax. However it doesn't work and comment's aren't displayed on page. If I delete this line, the comments work again (but of course, I don't get the sent variable).
$num = $_POST['page_num'];
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
Here is the javascript variable and included php file.
<script>
var page_num = 1;
</script>
<?php
include($_SERVER["DOCUMENT_ROOT"]."/index.php");
?>
I get this error in console: Uncaught SyntaxError: Unexpected token < in JSON at position 0 at JSON.parse ()
As said eariler if I remove the line where I get the variable with post, this error disappears.
You shouldn't use $.ajax and $.post to do the same thing, pick one, I'd say remove the $.post one and dont forget to put an exit; statement after you echo the response to avoid PHP to process further code if existing, also worth mentionning but not necessary, you can put the dataType to json so dataType: 'json' in the $.ajax call, dataType is used to tell jQuery what to expect as a response type from the server, as you are echoing the response by encoding it in JSON, you won't need to parse the response on your JS side if you speficied the dataType beforehand.
$.ajax({
url: "Komentarji/comment-list.php",
data : {page_num: page_num},
type : 'post',
dataType: 'json',
success : function(response) {
console.log(response); //will show the result of echo json_encode($record_set); from your PHP
}
});
$num = $_POST['page_num'];
$sql = "SELECT * FROM tbl_comment ORDER BY parent_comment_id asc, comment_id asc";
$result = mysqli_query($conn, $sql);
$record_set = array();
while ($row = mysqli_fetch_assoc($result)) {
array_push($record_set, $row);
}
mysqli_free_result($result);
mysqli_close($conn);
echo json_encode($record_set);
exit; //exit statement here
Following discussion with OP who wanted to use the $.post method, this is how it is done, pass the data as an object to the second attribute (more infos here):
$.post("Komentarji/comment-list.php", {page_num: page_num});
Just make your format JSON in your JS script
$.ajax({
url : 'Komentarji/comment-list.php',
type: "POST",
data: page_num:page_num,
dataType: "JSON",
success: function(data)
{
console.log(data);
},
error: function (jqXHR, textStatus, errorThrown){
console.log(errorThrown);
}
});
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!
Please can anyone assist I'm trying to get my JSON data displayed on my html5 localhost page,
I'm still new to JSON
I get the following returned but no data is loading on the page.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
Please if anyone can assist.
Below is my php script
`mysql_select_db($database_xxx, $xxx);
$rsfet = "SELECT * FROM cs_tracking ";
$fet = mysql_query($rsfet, $xxx) or die(mysql_error());
$json = array();
while($r=mysql_fetch_array($fet)){
$json[] = $r;
}
header('Access-Control-Allow-Origin: *');
echo $callback ='('.json_encode($json).')';`
and my javascript to display the table data
`
$(document).ready(function(){
$.ajax({
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
type: 'GET',
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
jsonp: true,
success: function(data){
$.each(data,function(i,photo){
var tblRow =""
+""+data.CS_Track_Child+""
+""+data.CS_Track_Date+""
+""+data.Tracking_Status+""
+""+data.CS_Tracking_ID+""
+"" ;
$(tblRow).appendTo("#userdata tbody");
});
},
});
});`
The $callback variable is not magically declared in your script (at least, it shouldn't be); you can access the value via $_GET['callback'] but make sure to sanitize its value:
if (isset($_GET['callback']) && preg_match('/[A-Z]\w*/i', $_GET['callback']) {
header('Content-Type: application/javascript');
header('Access-Control-Allow-Origin: *');
printf('%s(%s);', $_GET['callback'], json_encode($json));
}
You have two GET parameter of callback one is valid but empty and second is invalid.
http://www.hostname/getCheck.php?callback?&callback=jQuery110205560797746881064_1392215061343&_=1392215061344
url: 'http://xxxxxxxxxxx.com/getCheck.php?callback=?',
So remove your parameter and try with this:
url: 'http://xxxxxxxxxxx.com/getCheck.php',
Hi I currently have a JS file being called to populate my html page with dynamic data. My JS file calls a PHP file to fetch stuff from my sqldb and my PHP file echos json_encode the stuff it got from the sqldb, which in turn is used to populate the html page.
My problem is that depending on what's in the url ie ?user=Bob, I want my js file to call the php file to search for Bob. Right now it searches for current user if ?user=xxxx is not specified. It seems the $GET['user'] is always null, thus it's not being passed because I suspect the JS file working as a middleman. Here are my code snippets:
My URL:
www.website.com/index.php?user=Bob
My HTML Code
<script type="text/javascript" src="js/get-data.js"></script>
My JavaScript
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
dataType: 'json',
success: function(response){
var name = response[0];
var location = response[1];
$('#name').html(name);
$('#location').val(location);
}
});
});
My PHP Code
$id;
if (isset($_GET["user"]))
{
$id = $_GET["user"];
}
else
{
$id = $_SESSION['loggedInUser'];
}
$query = "SELECT * FROM Persons WHERE User = '$user'";
if($result = mysqli_query($sqlconnection,$query))
{
$row = mysqli_fetch_row($result);
echo json_encode($row);
}
You need to specify the data attribute in your ajax call.
$.ajax({
type: 'GET',
data: $("#myForm").serialize(), //for example. You can change this to something relevant.
/*rest of the code*/
});
What this will do is prepare a GET request with the proper data, for example, http://path/to/backend/?key1=value1&key2=value2
I believe you want to do something like this
$(document).ready(function(){
$.ajax({
type: 'GET',
url: 'php/retrieve-db.php',
data: <?php echo json_encode($_GET); ?>,
dataType: 'json',
....
EDIT:
Thanks #Brad and #Ashwin Musjija for pointing out. I was focusing on answer too quickly that I overlook the possible non persistent XSS attack.
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);