here is my code in ajax
function loadcountries()
{
var p = document.getElementById("selectCntry");
while(p.firstChild)
{
p.removeChild(p.firstChild);
}
var data = {
action: "loadccc"
};
jQuery.ajax
(
{
type: "POST",
url: "ajax-ows2.php",
dataType: 'json',
async:false,
data:data,
success: function(msg)
{
alert(msg.test);
}
}
);
}
here is my ajax-ows2.php
<?php
$action = $_POST["action"];
include "dbconnect.php";
if($action == "loadccc")
{
$var = $action;
$response_array['test'] = $var;
header('Content-type: application/json');
echo json_encode($response_array);
}
?>
and here is my function call:
<script>
window.onload = loadcountries;
</script>
my ajax way is different. I really have no idea why it is not alerting when the page is load. Im really sure that my ajax-ows2.php is good and im sure that my function call is correct. Can somebody help me with this. This is not a duplicate one. I tried to used asynch:false but still not working.
try this format:
$.ajax({
method: "POST",
contentType: "application/json; charset=utf-8",
data: data,
url: 'ajax-ows2.php',
success: function (data) {
console.log(data);
},
error: function (error){
console.log(error);
}
});
since you are doing POST method, your data parameter must be a stringify, https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify
Related
I've been trying to send this information to the js.
$statement = ibase_prepare($sql);
$query = ibase_execute($statement);
while ($row = ibase_fetch_assoc($query)) {
$data[] = $row;
}
echo json_encode($data);
However, when I try to, I get the response, but I can't get the data.
$('document').ready(function (){
$.ajax({
method: "POST",
url: "../Dashboard/php/chart.php",
dataType: "json",
sucess: function (data){
console.log(JSON.stringify(data));
}
});
})
You just have a grammatical error in a word "sucess", the correct word is "success"
$.ajax({
method: "POST",
url: "./data.php",
dataType: "json",
sucess: function (data){ // Here -> success
alert(JSON.stringify(data));
}
});
I'm trying to make a login through Facebook, in the console it shows that I'm getting the requested data (email, first_name ...) but ajax keeps sending null data to the PHP method.
here's the ajax code:
function saveUserData() {
FB.api('/me?fields=id,first_name,last_name,email', function(response){
$.ajax({
url: '<?php echo base_url();?>Auth/fb_auth',
data: {response: JSON.stringify(response)},
type: 'POST',
dataType: 'json',
success: function (data) {
if(data['state'] == 'ok'){
window.location.href ="<?php echo base_url(); ?>";
}
}
});
});
}
and this is how I get the data in the method:
$response = json_decode($this->input->post('response'), true);
You donĀ“t need to stringify stuff with $.ajax, it does that for you. Also, you can use $.post instead:
function saveUserData() {
FB.api('/me?fields=id,first_name,last_name,email', function(response){
$.post({
url: '<?php echo base_url();?>Auth/fb_auth',
data: response,
dataType: 'json',
success: function (data) {
if(data['state'] === 'ok'){
window.location.href ="<?php echo base_url(); ?>";
}
}
});
});
}
I want to get some data from a php script to my html page. They array $UniqueNames has a value on the server side, but nothing seems to happen when i use json_encode on the html page, the console.log returns an empty array (BilderID). Any suggestions?
code:
<script>
var BilderID = [];
$(document).ready(function (e) {
$('#SubmitBild').on('click', function () {
var form_data = new FormData();
var ins = document.getElementById('Myfilefield').files.length;
for (var x = 0; x < ins; x++) {
form_data.append("Bilder[]", document.getElementById('Myfilefield').files[x]);
}
$.ajax({
url: 'Includes/Bildhantering.php', // point to server-side PHP script
dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
$('#msg').html(response); // display success response from
},
error: function (response) {
$('#msg').html(response); // display error response from the PHP script
}
});
BilderID = <?php echo json_encode($UniqueNames); ?>
console.log(BilderID);
});
});
</script>
Php:
$UniqueNames = array();
for($i=0;$i<count($file_array);$i++)
{
if($file_array[$i]['error']){
echo $phpFileUploadErrors[$file_array[$i]['error']];
} else {
$extensions = array('jpg','png','gif','jpeg');
$file_ext = explode('.',$file_array[$i]['name']);
$file_ext = end($file_ext);
if (!in_array($file_ext, $extensions)){
echo "Invalid file extension!";
} else {
$fileNameNew = uniqid('', true).".".$file_ext;
$UniqueNames[] = $fileNameNew;
move_uploaded_file($file_array[$i]['tmp_name'], 'Bilder/'.$fileNameNew);
echo $phpFileUploadErrors[$file_array[$i]['error']];
}
}
}
The solution was to remove the datatype specifier, echo out the array in php and receive it inside the success method:
$.ajax({
url: 'Includes/Bildhantering.php', // point to server-side PHP script
//dataType: 'text', // what to expect back from the PHP script
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function (response) {
BilderID = response;
console.log(BilderID);
},
error: function (response) {
console.log("error:");
}
});
i mean, why use "datatype" if javascript figures it out anyway?
I have used postman to send the json data to the specifified url.I am getting the requred response that is json in postman.I want to send this json to some other file so i used ajax post method.Ajax post method is not called.My function is not triggering success or error here.
<?php
// get the HTTP method, path and body of the request
$method = $_SERVER['REQUEST_METHOD'];
$request = explode('/', trim($_SERVER['PATH_INFO'],'/'));
$input = json_decode(file_get_contents('php://input'),true);
$value1=json_encode($input);
//echo print_r($value1,1);
?>
<script type="text/javascript">
$(document).ready(function() {
// alert("hello");
var jsondata = <?php echo $value1 ?>;
$.ajax({
url: "/restapi/subscribe.php",
type: "POST",
data: { jsondata:jsondata },
dataType: "json",
Content-Type: "application/json",
success: function() {
alert("data sent!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
</script>
I am sending any of the json data as input.Output also json data that should be posted in subscribe.php.In subscribe.php i have written
<?php
$json=$_POST['jsondata'];
echo $json;
?>
Try with below code
<script type="text/javascript">
$(document).ready(function() {
// alert("hello");
var jsondata = <?php echo $value1 ?>;
$.ajax({
url: "/restapi/subscribe.php",
type: "POST",
data: { jsondata:jsondata },
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function() {
alert("data sent!");
},
error: function() {
alert("There was an error. Try again please!");
}
});
return false;
});
</script>
and let me know if it work
You should remove Content-Type: "application/json" from your js code and use next code in your php script:
header('Content-Type: application/json');
echo json_encode($data);
I think the problem is with Content-Type
Try to replace it with contentType:"application/json"
Try to replace Content-Type: "application/json" with contentType: "application/json; charset=utf-8",
I have a PHP function where I pass a variable to and it returns an array containing a start date and end date.
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return $date;
}
?>
I am also trying to use this PHP function in an AJAX call so I can reuse the code. I have added this to the beginning of the page:
if (isset($_POST['dateFunction'])) {
print_r(dateRangeTimeFrame($_POST['dateFunction']));
}
My jQuery code is as follows:
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response['startDate']);
console.log(response.startDate);
}
});
My issue is that I do not know how to access the response that the php function is returning.
Here is the response I am getting from the PHP function:
Array
(
[startDate] => 2015/01/17
[endDate] => 2015/02/16
)
How would I go about getting these 2 vars from the PHP response?
You need to use JSON. Your Javascript natively understands and can parse it
if (isset($_POST['dateFunction'])) {
echo json_encode(dateRangeTimeFrame($_POST['dateFunction']));
}
And your jQuery (note I added dataType)
$.ajax({
url: 'includes/functions.php',
dataType: 'json',
type: 'post',
data: { "dateFunction": theDate},
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1){
...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
return json_encode($date);
}
?>
jQuery
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate},
dataType: "json",
success: function(response) {
console.log(response.startDate);
}
});
<?php
function dateRangeTimeFrame($var1) {
// ...
$date['startDate'] = $startDate;
$date['endDate'] = $endDate;
echo json_encode($date);
}
?>
Ajax
$.ajax({
url: 'includes/functions.php',
type: 'post',
data: { "dateFunction": theDate },
success: function(response) {
for (var i = 0; i < response.length; i++) {
alert(response[i].startDate);
}
}
});