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);
}
}
});
Related
New to Web development and multiple scripting languages and how they mesh together...
I'm looking to return the entire SQL table (or a subset of it) from PHP and iterate through the values in JS and can't quite get it to work any help is appreciated.
In PHP encoding the array like this.
//get SQL data
$return_arr[] = array("id" => $id, "otherinfo" => $otherinfo);
echo json_encode($return_arr);
The ajax code I have looks like this but is where I'm getting tripped up...
jQuery.ajax({
type: "POST",
url: 'example.php',
type: 'POST',
data: { i: i },
dataType: "json",
success: function(response)
{
for(var i=0; i<response.length; i++)
{
var info = response[i].otherinfo;
var title = document.createElement("div");
var titletext = document.createTextNode(titledb);
title.appendChild(info);
}
}
)}
Thanks
I think its a syntax mistake.
jQuery.ajax({
url: 'example.php',
type: 'POST',
data: { i: '' },
dataType: "json",
success: function(response)
{
// code here
}
}) // <--- here
I have a very simple php page with a jquery function
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: "test.php",
type: "POST",
data: {
myvar: 1,
},
success: function(result) {
console.log("it works");
}
});
});
</script>
My AJAX function is supposed to be triggered as soon as the document is ready. My test.php just shows my $_POST.
<?php
var_dump($_POST);
die();
Nothing is happening. I should go to test.php and see the var_dump. It works if I have a button and start the AJAX function on the click but not like that... Isn't possible to do so ?
Since on the Back-end part you expect $_POST the best you can do is to use
FormData API
jQuery(function($) {
// Your object
const data = {
myvar: 1,
foo: "foo",
};
// Create FormData from Object
const FD = new FormData();
Object.entries(data).forEach(([prop, val]) => FD.append(prop, val));
$.ajax({
url: "test.php",
type: "POST",
processData: false, // https://api.jquery.com/jquery.ajax/
data: FD, // pass the formData and enjoy with $_POST in PHP
success: function(result) {
console.log("it works", result);
}
});
});
I test your code work with datatype like :
ajax page:
$(document).ready(function() {
$.ajax({
url: "test.php",
type: "POST",
dataType: 'json', //add that line
data: {
myvar: 1,
},
success: function(result) {
console.log(result);
console.log(result['name']);
}
});
});
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?
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
i am trying to send ajax post request on two php pages which are 1. properties.php and 2. profile.php the code i am trying it sends ajax request on properties.php so how i can send the same post request on profile.php below is my code
index.php
<div id="div-second-dropdown"></div>
<div id="div-third-dropdown"></div>
ajax.js
$(document).ready(function () {
sendAjax();
});
function sendAjax() {
$.ajax({
url: 'properties.php',
type: 'post',
data: 'account-id=' + $('#account-dropdown').val(),
success: function (html) {
$('#div-second-dropdown').html(html);
$.ajax(
{
url: 'analytics.php',
type: 'post',
data: 'account-id=' + $('#account-dropdown').val(),
success: function (html) {
$('#div-third-dropdown').html(html);
}
}
);
}
});
}
properties.php
<?php
echo $_POST['accountid'];
?>
it display the post value on index.php in #div-second-dropdown.
profile.php
<?php
echo $_POST['accountid'];
?>
it don't display the post value on index.php in #div-third-dropdown
You can take advantage of jquery promise and playing around to execute the 2nd call if the first is successful.
function sendAjax(dest)
{
return $.ajax({
url: dest + '.php',
type: 'post',
data: 'account-id=' + $('#account-dropdown').val(),
success: function (html) {
$('#div-second-dropdown').html(html);
},
error: function(s)
{
return s;
}
});
}
$(document).ready(function () {
sendAjax('properties').then( function(){ sendAjax('profile')} );
});
Just do it:
$(document).ready(function() {
sendAjax();
});
function sendAjax()
{
$.ajax(
{
url: 'properties.php',
type: 'post',
data: 'account-id=' + $('#account-dropdown').val(),
success: function (html) {
$('#div-second-dropdown').html(html);
$.ajax(
{
url: 'profile.php',
type: 'post',
data: {'account-id': $('#account-dropdown').val(),
'profile-id': $('#profile-dropdown').val()},
success: function (html) {
$('#div-third-dropdown').html(html);
}
}
);
}
}
);
}
The first A in ajax stands for asyncronous, so the second request is made before the first one finishes. There might be session locking problem.
Try calling the second page ajax call in the success callback of first ajax call
$(document).ready(function () {
sendAjax();
});
function sendAjax(myUrl) {
$.ajax({
url: 'properties.php',
type: 'post',
data: 'account-id=' + $('#account-dropdown').val(),
success: function (html) {
$('#div-second-dropdown').html(html);
$.ajax({
url: 'profile.php',
type: 'post',
data: 'account-id=' + $('#account-dropdown').val(),
success: function (html) {
$('#div-second-dropdown').html(html);
}
});
}
});
}