I have a HTML page through which I need to pass two variables through post method to a PHP page which accept those two variables and call an API to fetch the result from those two variables.
Now, my requirement is to get the API result back to first page.
I am not able to get it.
From index.html, I am calling another page with -
$.ajax({
url: "data.php",
type: 'POST',
data: {
difficulty: term,
cr : country
},
success: function (res) {
console.log(res);
}
In data.php, I am taking parameters through POST method and calling API,
$(document).ready(function(){
var data;
$.ajax({
url: "https://key***.co*/api?key="+api_key,
dataType: "json",
data: {
difficulty: <?php echo $diff; ?>,
cr : <?php echo $cr; ?>
},
success: function (res) {
data = difficulty;
}
});
}
Here the api_key is defined above. How to fetch the data back to index.html?
You should remove the Javascript from the data.php page, and use php to make the request.
You can refer this:
PHP cURL GET request and request's body
Related
I am working on a site using HTML/CSS/JS and AJAX for connecting to the server. (new to web development)
I currently have this to get data and put it in an array.
var addresses = [];
$.ajax({
type: "GET",
url: 'GetAddresses.php',
data: {"type":"check"},
success: function(response){
alert(response);
addresses.push(response) // add values from php to array
}
});
But what if php echoed an address, a name, and a city for example. How could I access those different values?
Thank you for your help.
Typically you would write PHP that outputs structured data, e.g. JSON, and then parse that on the client.
<?php
header("Content-Type: application/json");
$data = [ "address" => "foo", "name" => "bar", "city" => "baz" ];
echo json_encode($data);
?>
and then on the client:
$.ajax({
type: "GET",
url: 'GetAddresses.php',
data: {"type":"check"},
success: function(response){
alert(response);
console.log(response.address);
console.log(response.name);
console.log(response.city);
}
});
Unrelated to the focus of your question, pushing data into an array in the wider scope from an Ajax callback is likely to cause you problems.
I'm using ajax to send values to another form. There, I insert in DB and return the table as html to update instantly. So far it's a simple ajax refresh the table.
The problem is, I check the session to be logged in and do that things. when i delete the cookie (the session timeout) the login page shows in the partial form that should shows the returned table.
I checked... it seems has the "303 see other!" error.
I need it to redirect to login page when the session is times out.
Here is my ajax code:
function save(){
var value = {
//values
};
$.ajax({
type: 'POST',
url: '<?php echo site_url('admin/test'); ?>',
data: value,
success: function(resp){
$('#sample_1').html(resp);
},
});
}
I check the session in the admin controller.
You can try to use jQuery ajax() statusCode handler like so:
$.ajax({
type: 'POST',
url: '<?php echo site_url('admin/test'); ?>',
data: value,
success: function(resp){
$('#sample_1').html(resp);
},
statusCode: {
303: function() {
...do stuff you want to do when 303 happens...
}
}
});
Goal: Serialize data, send them in HTTP POST request using AJAX, proceed data in PHP (and answer)
Problem: PHP $_POST variable seems to be empty
JS/AJAX
var postData = [cmd, data];
alert(postData = JSON.stringify(postData));
$.ajax({
url: "./backendTag.php",
type: "post",
data: postData,
dataType: 'json',
success: function (response) {
alert(response); // Empty
//logToServerConsole(JSON.parse(response));
},
error: function(jqXHR, textStatus, errorThrown) {
logToServerConsole("E3"); // Communication Error
console.log(textStatus, errorThrown);
}
});
PHP
<?php echo json_encode($_POST);
The reason for the same is probably because you are not posting properly in javascript. Before i add the codes, let me add a couple of tips on how to debug in these situations.
First is, you check if the request is properly formed. Inspect the network in browser dev tools.
Second method could be to use var_dump on $_POST to list out all the post parameters and check if they have been recieved in PHP
Now as far as the code goes
here is the javascript
$.ajax({
method: "POST",
url: "url.php",
data: { name: "John Doe", age: "19" }
}).done(function( msg ) {
alert(msg);
});
and in php you can simply check using
<?php
print $_POST["name"];
?>
which would work perfectly. Notice how the data in javascript is a list, while from what you wrote seems to be json string
Apparently we can't pass an array directly after serializing him. The following code resolved the problem. (Split array)
data = JSON.stringify(data);
var JSONdata = {"cmd" : cmd, "data" : data};
$.ajax({
url: "./backendTag.php",
type: "post",
data: JSONata,
dataType: 'json',
/* Handlers hidden*/
});
JSON content won't be parsed to the $_POST globals. If you want to reach them, try to get from php://input with:
file_get_contents('php://input')
And I suggest giving the content-type during the ajax request:
contentType: 'application/json',
If it's not working, try to set the data as a string, with JSON.Stringify, like the following:
data: JSON.stringify(postData)
I have a JSON string (stringified array of objects in javascript) which i intend to post to another page and then retrieve it from the $_POST variable. I used json =JSON.stringify(array).
The result gave me the following string
json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}]
Now I use
$( "#other").click(function() {
$.ajax({
url: 'some.php',
type: 'POST',
data: { kite : json}
});
On the page some.php I use
$kite=json_decode($_POST['kite'],true);
print_r($kite)
But nothing shows up. I have read many links on this topic and tried adding ContentType,dataType,processData parameters to the $.ajax() function but nothing helped.
What about this:
$( "#other").click(function() {
var json = [{"keycodec":68,"eventc":"keydown","timec":1392849542994}
,{"keycodec":65,"eventc":"keydown","timec":1392849543063},
{"keycodec":87,"eventc":"keydown","timec":1392849543084}];
$.ajax({
url: 'test.php',
type: 'POST',
data: "kite=" + JSON.stringify({ kite : json }),
success: function(msg){
alert(msg);
},
failure: function(errMsg) {
alert(errMsg);
}
});
});
And on your php code:
<?php
$obj=json_decode($_POST['kite']);
print_r($obj->{'kite'});
?>
Not in an elegant way on passing the json..
but this way you can still capture "kite" as post variable and decode your desired json string.
$.ajax({
type: "GET",
url:"http://localhost:8080/privateTraining/getTrainingsJson",
data: { ListID: '1'},
dataType: "jsonp",
success: function(data)
{
anotherFunction(data);
}
});
function anotherFunction(data){
$.ajax({
type:"POST",
data:data,
url:"anotherFile.php,
success: function(data)
{
//do something elese;
}
});
}
here first one is cross domain ajax call.
here i want to send the result (jasonp response) of first ajax call to second ajax call to a php file .. where i need to convert jsonp data to php array .
is it possible to do like this?