can any one help me please
What Im trying to do is a phone app using HTML5, JQUERY, Json and PHP. I cannot use PHP pages in this as I will be packaging it with Phone Gap Cloud Compliler.
I have tried using many scripts and suggestions that I have researched on the internet but cannot seem to get this to work.
On the page I need to retrieve data from the database there are 6 text boxes or divs I wish to populate using a on page ajax request to a PHP processing page that gets the required data and forms it into a Json string, the following scripts will show where I am at presently.
PHP Page:- this works as far as getting the data from the database and from the research I have done succssefully parces it into a Json format
PHP Script **********************************************
<?php
include_once 'db_connect.php';
header("Content-Type: application/json"); //this will tell the browser to send a json object back to client not text/html (as default)
session_start();
$return_arr = array();
$sql = "SELECT * FROM `autumnTerm`"; //query
$result = mysqli_query($mysqli, $sql);
while($row = mysqli_fetch_array($result)) {
$row['term1start'] = date('d-m-y', strtotime($row['term1start']));
$row['term1finish'] = date('d-m-y', strtotime($row['term1finish']));
$row['term2start'] = date('d-m-y', strtotime($row['term2start']));
$row['term2finish'] = date('d-m-y', strtotime($row['term2finish']));
$row_array['term1start'] = $row['term1start'];
$row_array['term1finish'] = $row['term1finish'];
$row_array['term2start'] = $row['term2start'];
$row_array['term2finish'] = $row['term2finish'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
?>
this returns the following json :-
[{"term1start":"01-04-15","term1finish":"02-04-15","term2start":"03-04-15","term2finish":"04-04-15"}]
which I believe to be the right format.
The Jquery:-
<script>
I think I am right in believing that document ready should run the jquery script on page load
$(document).ready(function() {
the processing page address which is associated to a variable
var url = "http://www.newberylodge.co.uk/webapp/includes/retrieveAutumn.inc.php";
The ajax request defining the request elements
$.ajax({
type: "POST",
cache: false,
url: url,
dataType: "json",
success: function(data) {
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
If anyone would be so kind as to helping me figure this out I would be most greatful, I have been trying to resolve this for over a week now
I havent posted the html trying not to swamp the question with code, but if its needed I will put it up on request
try this:
$.ajax({
type: "GET",
cache: false,
url: url,
dataType: "json",
success: function() {
console.log()
$('#termoneError').text('The page has been successfully loaded');
},
error: function() {
$('#termoneError').text('An error occurred');
}
});//ajax request
});//ready function
</script>
and try to see the console is there any error?
you should try for the error Cross-Origin Request Blocked to put proper header
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET,POST,OPTIONS');
header('Access-Control-Allow-Credentials: true');
the rest code its ok
Related
Basically I have a combination of PHP codes and javascript codes. My mySQL data are encrypted using CodeIgniter, thus to load the data (view and edit) in json, i need to decrypt it again. My question is how to make my "$x" variable dynamic?
Thanks.
function edit_person(id)
{
save_method = 'update';
$('#form')[0].reset();
$('#modal_form').modal({backdrop: 'static', keyboard: true, show: true });
<?php
$x = 13; //<== **i need to make this $x dynamic based on "edit_person(id)"** //
$url = "http://myurlhere.com/main/ajax_edit/".$x;
$datax = file_get_contents($url);
$string = json_decode($datax, TRUE);
?>
$.ajax({
url : "<?php echo site_url('main/ajax_edit')?>/" + id,
type: "GET",
dataType: "JSON",
success: function(data)
{
$('[name="id"]').val(data.id);
// ** below code "firstName" is my decryption requirement ** //
$('[name="firstName"]').val("<?php echo $this->encryption->decrypt($string['firstName']); ?>");
$('#modal_form').modal('show');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error get data from ajax');
}
});
}
You are probably confusing the server-side and the client-side code.
In simple terms: First, the client sends a request to the server. The target PHP code gets executed on the server-side only. It then generates an HTML file, which contains your JS code. This file is sent to the client and is executed on the client-side only. At that time, on the client-side, there is JS code only and no PHP code anymore. All the PHP code gets replaced by some value or is simply removed or ignored.
If you want to access some PHP functionality from your JS code, you have to send a request from the client to the server. As you are doing with the AJAX call.
So in order to make your $x dynamic, you have to call some PHP code and pass the ID as a parameter.
In a strongly simplifyed way you could achieve this by:
$.ajax({
url : "your url to some file.php/?id=" + id,
type: "GET",
})
some file.php
<?php
$x = $_GET["id"]; //<== $_GET["id"] will return the value of the parameter "id" in the url
?>
Starting from here, you should read more about AJAX calls, input sanitation and validation in order to secure your requests.
I can't get the php $_SESSION variable to work the way I want it to. I've got two files. The first one setting the variable:
<?php
session_start();
header("Access-Control-Allow-Origin: *");
$_SESSION['authenticated'] = "yes";
echo json_encode('Authenticated successfully.');
?>
and a second one trying to retrieve it:
<?php
session_start();
header("Access-Control-Allow-Origin: *");
print '<pre>';
var_dump($_SESSION['authenticated']);
print '</pre>';
?>
But the second file always prints NULL when it should print "Yes" and a new error is recorded in the server's log:
[Thu Sep 22 12:52:47.763114 2016] [:error] [pid 26644] [client <ip_here>] PHP Notice: Undefined index: authenticated in <Second_file> on line 5, referer: <client_url_here>
Both files are accessed by AJAX calls from JavaScript.
The AJAX code for file 1 works as following:
$.ajax({
url: corrDomain + '/auth.php', //Path and name of file #1. It's correct and working.
type: 'POST',
data: {
//This part is excluded in the above php code for simplification. It's guaranteed to work.
username: username,
password: password,
action: 'init'
},
dataType: 'json',
success: function(data){
//Check if data contains the right information, then call function for file #2.
},
error: function(){
//Something went wrong
}
});
When that code gets thumbs up from the php, that the user is authorized the following code will be run for file #2:
$.ajax({
url: path + '/getProducts.php', //Also correct and working.
type: 'POST',
dataType: 'json',
success: function(data){
products.push(data);
orderProductIds();
//Update col 1 + 2;
updateOrders('reload');
//Set interval of updating col 1.
setInterval(function(){
updateOrders('update');
}, 10000);
},
error: function(){
alert('Something went wrong.');
}
});
UPDATE: I added session_name(); as the first row in all my php files. The session now works if I open each file in the browser but not if I access them via AJAX. So the problem still persists, but maybe this can help you help me.
UPDATE #2: In Chrome's web inspector I can see that both files are returning Session Cookie ids, but they have different values. See screenshots.
UPDATE #3: I've researched and found that php sessions isn't possible when using PhoneGap, even though I'm requesting the php file via jQuery AJAX. Can someone confirm this?
Make sure you also start the session session_start(); on the page which makes the AJAX calls
EDIT
A not preferable but maybe usefull method is to send the session_id with each ajax request to use more like a token.
The first PHP-script:
session_start();
echo json_encode([
'message' => 'Session started',
'session_id' => session_id()
]);
exit();
Store the received id in a javascript-variable:
var session_id;
$.ajax({
...
success: function(data) {
session_id = data.session_id;
}
...
}
After that send the session_id along with each AJAX-request:
var data = {session_id: session_id, ... };
$.ajax({
type: "POST",
url: "server.php",
data: data,
success: function(data) {
}
});
Instead of the session_id you can generate a random token instead to send along with each request.
I am trying to to extract a Json response in jquery sent from a php file.
This is the .js code:
$.ajax({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
datatype: 'json',
data: {'userCheck': username},
success: function(data){
// Check if username is available or not
},
error: function(){
alert('Much wrong, such sad');
}
});
This is the response from the php file:
if($sth->fetchColumn()!=0){
//$response = array("taken");
$response = array("username"=>"taken");
echo json_encode($response);
//echo '{"username':'taken"}';
}else{
//$response = array("available");
$response = array("username"=>"available");
echo json_encode($response);
//echo '{"username":"available"}';
}
I have tried all combinations I can think of in both files, but nothing seems to work. It is a simple check for a username in the database. If I console log the data I get from the response, I get this:
{"username":"available"}<!DOCTYPE html>
// The rest of the page html
So the info is there, but how do I access it? I have tried several syntaxes found around the internet, but no luck so far. I seem to recall that a json response only can contain valid json, so is the problem the html? I don't think I can avoid this due to the structure of my application, so hopefully it is possible to access the json with my present structure.
in you Ajax
EDIT:
change
datatype:"json",
the case of parameter name was not respected, the t must be T
dataType:"json",
now retry please
$.ajax
({
url: 'index.php?page=register', //This is the current doc
type: 'POST',
dataType: 'json',
data: {'userCheck': username},
success: function(data)
{
// Check if username is available or not
switch(data.username)
{
case "available":
// do you want
break;
case "taken":
// do you want
break;
}
},
error: function()
{
alert('Much wrong, such sad');
}
});
in PHP
simply that, and don't forget to exit; to avoid include html page in your json response !
This is the code coming after the }".... who break your json output
and make it unreadable by javascript (worste, it simply break your javascript !)
echo json_encode(["username"=> ($sth->fetchColumn()!=0) ? "taken":"available"]);
exit;
When you're responding to an AJAX call, you should just return the JSON response, not the HTML of the page. Add:
exit();
after this code so you don't display the HTML after the JSON.
In the JS code, use if (data.username == 'available') to tell whether the username is available.
The other problem in your code is that you have a typo here:
datatype: 'json',
It should be dataType, with an uppercase T.
You can also put:
header("Content-type: application/json");
before echoing the JSON in the script, and jQuery will automatically parse the response.
Also you can set request headers in your jQuery ajax call beforeSend function like follows
beforeSend: function (xhr) {
xhr.setRequestHeader('Content-Type', 'application/json;charset=utf-8');
xhr.setRequestHeader('Accept', 'application/json');
}
So you're strictly declaring the data type to be json
This is probably something very simple, and I've seen that there are/have been more people with the same issue. But the solutions provided there did not seem to work.
So, I want to execute a .php file through AJAX. For the sake of testing the php file (consolefunctions) is very small.
<?php
if(isset($_POST['action'])) {
<script>console.log('consolefunctions.php called.');</script>
}
?>
And now for the javascript/ajax part.
$(".startConsole").click(function(){
var consoleID = $(this).attr("value");
$.ajax({ url: 'include/consolefunctions.php',
type: 'post',
data: {action: 'dosomething'},
success: function(output) {
//alert("meeh");
}
});
});
Somewhere, somehow there's an issue because the message from the PHP file never shows. I've tested the location from the php file, which is valid.
First the php code is not correct, you should add an echo
<?php
if(isset($_POST['action'])) {
echo"<script>console.log('consolefunctions.php called.');</script>";
}
?>
but the problem is, when you send this code to js, you'll get it as a string on your variable output, not as a code that will be executed after making the ajax call, so the best way to do this is to echo only the message to display on your console and then once you receive this message you can call console.log function
<?php
if(isset($_POST['action'])) {
echo"consolefunctions.php called";
}
?>
in the success function :
console.log(output);
Can someone explain me how to make a REST call using jQuery/Javascript? I tried using the .getJSON() and .ajax(), but neither helped me.
This is the REST URL :
http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&date=2010-01-15&format=json&key=API_KEY
Code:
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode='+zip+'&format=json&key=**<KEY HERE>**',
function(data)
{
alert(data.AQI);
}
);
$.ajax({
url: 'http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode',
type: 'GET',
data: 'zipcode='+zip+'&format=json&key=**<KEY HERE>**',
success: function() { alert('get completed'); }
});
there are a couple of problems. First, you need to add &callback=? to the end of the querystring to allow the crossdomain.
$.getJSON('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=94954&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D&callback=?',
function(data)
{
alert(data.forecast[0]);
}
);
You will then get an Uncaught SyntaxError: Unexpected token : error. This is because you are expecting json data, but the headers on the server are sending text/html - not application/json. Take a look at the console when you run this fiddle, you'll see the errors.
Therefore, you can't get the data from cross domain because you have to be using jsonp - which requires the header to be sent correctly.
If this is your api, then you just need to send the correct header, otherwise, you need to get with the developers there and ask them to fix it.
Alternatively
If neither of those above options work, you could always create a proxy script that would get the contents of the json feed for you and echo it out. Here's one in PHP:
<?php
// myproxy.php
header('Content-type: application/json');
$zip = $_GET['zip'];
$results = file_get_contents('http://ws1.airnowgateway.org/GatewayWebServiceREST/Gateway.svc/forecastbyzipcode?zipcode=' . $zip . '&format=json&key=B868EA39-1D92-412A-96DE-DCF5ED30236D');
echo $results;
?>
Then, you would just point your $.getJSON to this script on your server:
$.getJSON('/myproxy.php?zip='+zip,
function(data)
{
var mydata = jQuery.parseJSON(data);
alert(mydata.forecast[0]);
}
);