This is probably very simply but I cannot figure it out. I am using a jquery script I found to display a timer. I then want to send the number of seconds to a PHP file. Below is the script, if I just alert the value variable, it contains the correct data, so I am accessing it correctly but its empty on the PHP side when it arrives.
$('.get-timer-btn').on('click', function() {
var value = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php',
data: { value : value },
cache: false,
success: function(result){
alert(result);
}
});
});
The result alert displays empty based on this test php file
<?php
if (isset($_POST['value'])) {
$value = $_POST['value'];
echo $value;
} else {
$value = "Empty!";
echo $value;
}
?>
I would really appreciate some help.
I thought you must add a header to Ajax object.
edits :
change var name
check URL address
add header
$('.get-timer-btn').on('click', function() {
//change this name !
var value_data = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php', //make sure correct address
headers: {'Accept': 'application/json'}, //add header is so important
data: { value : value_data },
cache: false,
success: function(result){
alert(result);
}
});
});
You must end php hier is a worked example:
<?php
if(isset($_POST['value'])){
$value = $_POST['value'];
echo ($value)?$value:'Empty';
die;}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<p class="timer" data-seconds="2"></p>
<button class="get-timer-btn">BTN</button>
<script>
$('.get-timer-btn').on('click', function() {
var value = $('.timer').data('seconds');
$.ajax({
type: 'POST',
url: 'test.php',
data: { value : value },
cache: false,
success: function(result){
alert(result);
}
});
});
</script>
Related
I am making a call with ajax to a php file. All I want to do is get a value back from the php file to test it with javascript. I have tried many many things, but can only get undefined (from the below code).
How can I get "hello" returned from the php file to my javascript?
jQuery.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = jQuery(data).html();
alert(the_returned_string)
}
});
The PHP file:
<?php
echo '<div id="id-query-result>"';
echo "hello";
echo "</div>";
You can change the code inside PHP like this
<?php
$queryResult = '<div id="id-query-result">hello</div>';
echo json_encode(['html' => $queryResult]);
Then, change your ajax call
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
dataType: 'json',
success: function(data) {
var the_returned_string = data.html;
alert(the_returned_string);
}
});
$.ajax({
type: "POST",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
$('body').append(data);
var text = $('#id-query-result').text();
alert(text);
$('#id-query-result').remove()
}
});
Why not just append the HTML response of your php file then get the text accordingly. You can then remove it after.
There are two changes to be done:
Change the type to "GET" since you directly call the PHP File.
remove the wrapped jQuery method inside the success function and add .html as an attribute
jQuery.ajax({
type: "GET",
url: "the_file_to_call.php",
data: {userid: group_id_tb},
success: function(data) {
var the_returned_string = data.html
alert(the_returned_string)
}
});
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 unable to figure out the problem .I apology in advance if I have lack of knowledge and did silly mistakes. Here is my piece of code.
<!-- Piece of html -->
<div class="form-group">
<input class="form-control" placeholder="Enter Service image" id="edit_service_image-1" type="file" name="file_image">
</div>
<button type="button" class="btn btn-primary" onclick="processIt(<?php echo $service['service_id'];?>,'esi',document.getElementById('edit_service_image-1').files[0])">Edit</button>
The javascript function :->
function processIt(id,flag,inputvalue)
{
var filedata = new FormData();
filedata.append('imagefile', inputvalue);
filedata.append('id', id);
filedata.append('flag', flag);
$.ajax({
url: 'modify.php',
type: 'POST',
inputvalue: filedata,
contentType: false,
processData: false,
cache: false
}).success(function(msg) {
alert(msg);
});
}
Here is modify.php (Only test code)
<?php
if(isset($_REQUEST['flag']) && !empty($_REQUEST['flag']) && isset($_REQUEST['id']) && !empty($_REQUEST['id']) )
{
$flag = $_REQUEST['flag'];
$id = $_REQUEST['id'];
echo "Processed";
}
else
echo "Request not processed";
?>
So my problem is its always alerting "Request Not Processed", which means nothing is getting posted using ajax POST . I am confused, couldn't figure out the exact problem.
Edit
Another test code of modify.php
<?php
print_r($_FILES);
print_r($_POST);
?>
In this case the output is -->
Array{
}
Array{
}
SOLVED
Thanks to everybody who guided me
Just a change in javascript worked . Here's the following changed code in processIt() function, which served my purpose->
function processIt(id,flag,inputvalue)
{
var filedata = new FormData();
filedata.append('imagefile', inputvalue);
filedata.append('id', id);
filedata.append('flag', flag);
$.ajax({
url: 'modify.php',
type: 'POST',
data: filedata, // Here instead of inputvalue it's changed to data
contentType: false,
processData: false,
cache: false
}).success(function(msg) {
alert(msg);
});
}
I am basing my answer off this answer. Not sure where you got inputvalue from, but replace it with data.
function processIt(id, flag, inputvalue)
{
var data = new FormData();
data.append('imagefile', inputvalue);
data.append('id', id);
data.append('flag', flag);
$.ajax({
url: 'modify.php',
type: 'POST',
data: data,
contentType: false,
processData: false,
cache: false,
success: function (msg) {
alert(msg);
}
});
}
And just a friendly code review in your PHP code, avoid using $_REQUEST and you are doing too much unnecessary checking in your IF condition. Here's one way to fix it:
if (!empty($_POST['flag']) && !empty($_POST['id'])) {
$flag = $_POST['flag'];
$id = $_POST['id'];
echo "Processed";
} else {
echo "Request not processed";
}
You may also try filter_input function which offers some validation and sanitization features. Unfortunately, there is no INPUT_FILE and you have to use $_FILES array.
Assuming id is an integer, you could do something like:
$flag = filter_input(INPUT_POST, 'flag', FILTER_SANITIZE_STRING);
$id = filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT);
if ($flag && $id) {
echo "Processed";
} else {
echo "Request not processed";
}
You need to replace your "inputvalue" with "data".
So your code will look more like this:
function processIt(id,flag,inputvalue)
{
var filedata = new FormData();
filedata.append('imagefile', inputvalue);
filedata.append('id', id);
filedata.append('flag', flag);
$.ajax({
url: 'modify.php',
type: 'POST',
data: { mydata: filedata },
contentType: false,
processData: false,
cache: false
}).success(function(msg) {
alert(msg);
});
}
And then in your modify.php do:
var_dump($_POST);
To see if the post data is accessable.
I have no idea how did you get this option: inputvalue: but this will do:
function processIt(id,flag,inputvalue){
$.ajax({
url: 'modify.php',
type: 'POST',
data: {inputvalue:'imagefile',id:id, flag:flag},
contentType: false,
processData: false,
cache: false,
success: function(msg) {
alert(msg);
}
});
}
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);
}
}
});