<script>
$("#submit").click(function () {
var newhour= [];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]); // output: each: 07:00,08:30
each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
var jsonString = JSON.stringify(newhour);
$.ajax({
type: "POST",
url: "exp.php",
data:{data: jsonString},
cache: false,
success: function(){
alert("OK");
}
});
});
<script>
I want to pass the newhour array values to php and use them to insert into a table.
so php file, exp.php:
$data = explode(",", $_POST['data']);
foreach($data as $d){
echo $d;
$sql = "insert into exp_table (hour) values ('$d')";
mysql_query($sql);
}
However I can not take the values. What is wrong with the code?
Could you please help me?
Thanks in advance.
according to the answers i tried this on php side, but it returns NULL.
$data = json_decode($_POST['data'],true);
//$data = explode(",", $_POST['data']);
echo "data: " .$data;
var_dump($data); // no output
foreach($data as $d){
echo $d; // no output
}
You do not have to stringify an array in the javascript.
.ajax looks after all that.
pass
data: {newhours: newhour},
then you will get $_POST['newhours'] in the PHP code which will be the array you had in javascript.
In Ajax there is not "type" params, use "method".
Beside that everything should works, you might need to decode the json using json_decode($_POST['data']) on in your php file.
Hopes it helps !
Nic
Pass the array without JSON.stringify in ajax data post. And fetch the data in php file using $_POST['data'].
I just have tried below code and it working great.
<?php
if(isset($_POST['data'])){
print_r($_POST);exit;
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
var newhour= [];
arrayNumbers = [['07:00','08:30'],['08:30','18:00','19:00']];
for (var i = 0; i < arrayNumbers.length; i++) {
newhour.push(arrayNumbers[i].toString().split(','));
console.log("each: " + newhour[i]);
// output: each: 07:00,08:30 each: 18:00,19:00
}
console.log("all: " + newhour); //output: all: 07:00,08:30,18:00,19:00
$.ajax({
type: "POST",
url: "abc.php",
data:{data: newhour},
cache: false,
success: function(data){
console.log(data);
}
});
});
</script>
Related
Is this valid approach: I want to keep api key from being accessible via source code so I have been trying to keep it hidden with PHP and use Javascript to display data. (I prefer to use js syntax to display data) I've been able to display data successfully but when I look at the source code I can see the JSON response. Can anyone tell me if this is a valid approach and why not good idea to have json shown in source?
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
$json = json_decode($data,true);
?>
I then access the response like so:
<script type="text/javascript">
var data = <?php echo json_encode($json) ?>;
$('.in-theaters-soon').append('<p>' + data.movies[0].title + '</p>');
</script>
You can directly echo the values from PHP since you already have the response in $json. For example:
<div class="in-theaters-soon">
<p><?php echo $json['movies'][0]['title']; ?></p>
</div>
Always make some validation of the printed data.
<?php
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
if (is_array($data) && ! empty($data)) {
/**
* Do something.
/**/
}
You could do something like this if you have the php in a separate file.
Your php file.
<?php
// create a token check to make sure it is being called.
$apikey = "xxxx";
$data = file_get_contents('http://url?apikey=' . $apikey);
echo json_encode($data);
?>
Then query your php file something like this sending a token or something similar.
$.ajax({
url: url,
type: 'POST',
data: {token:token},
success: function(data){
var response = $.parseJSON(data);
for(var x = 0; x < response.length; x++){
$('.in-theaters-soon').append('<p>' + response[x].title + '</p>');
}
},
cache: false,
contentType: false,
processData: false
});
Hope this helps.
I tried to get a simple ajax-test working but without success. I am trying to pass a variable($add1) from PHP to JS, then let the JS calculate the sum and return it back to a PHP variable via $_POST and ECHO it out in the html.
index.php:
<?php
echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum($add1)</script>";
$sum = $_POST['variable'];
echo $sum;
?>
script.js:
function sum(param) {
var sum = 3;
sum = 3 + param;
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
});
}
For some reason this code doesn't work. Any help is appreciated.
I want the php file to pass the $add1 to the Javascript and then i want the javascript to return the var sum back to the php and the php to echo the $sum from the $POST.
$sum from $_POST is actually echoed, but not shown in HTML page, but handled as a response back to Ajax.
You have to add a success function in Ajax closure
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function (data){
document.write(data);
}
});
You will see the answer show in page.
php:
if (isset($_POST['variable'])) {
$sum = some_futher_function($_POST['variable']);
echo $sum;
} else {
echo "<script type='text/javascript' src='script.js'></script>";
$add1 = 3;
echo "<script>sum({$add1})</script>";
}
function some_futher_function($param){
//do some thing
return $return;
}
Include this on your page before your script.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
PHP code
<?php
if ($_POST['variable']) { // If ajax request only
$sum = $_POST['variable'] + $add1;
echo $sum;
} else { // Loading in the browser
$add1 = 3;
echo '<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="script.js"></script>';
echo "<script>sum(".$add1.")</script>";
}
?>
Javascript
function sum(param) {
var sum = 3;
sum = 3 + param;
$.ajax({
type: 'POST',
url: 'index.php',
data: {
'variable': sum
},
success: function(result) {
alert(result)
},
error: function(e) {
console.log(e);
}
});
}
I'm querying my database using ajax (jquery) but the data I'm getting back is proving difficult to deal with. I did notice that others have posted similar issues and identified the PHP code (specifically how data is being allocated to the array) as being the issue. However I couldn't find a solution. The contents of my returned data (when I transform the returned data into a string) looks like this:
[{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin#admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}]
I'd really like to be able to pull an individual element from the returned data, such as the userLastLogin field.
My ajax query:
$.ajax({
url: 'authenticate2.php',
type: 'POST',
dataType: 'JSON',
data: {
username: $('#username').val(),
},
success: function (res) {
$('#resultBox').text(res);
}
});
My PHP below:
<?php
$con = mysqli_connect('127.0.0.1','root','','db1');
if (!$con) {
die('Could not connect: ' . mysqli_error($con));
}
mysqli_select_db($con,"db1");
$sql="SELECT * FROM Users WHERE userName = 'admin'";
$result = mysqli_query($con,$sql);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
$rows[] = $r;
}
echo json_encode($rows);
mysqli_close($con);
?>
This'll help you
JS
success: function (res) {
var res = [{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin#admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}];
$.each(res,function(key,value){
alert(res[key].id);
alert(res[key].userName);
alert(res[key].userPassword);
alert(res[key].userEmail);
alert(res[key].userRegistrationIP);
alert(res[key].registrationDateTime);
alert(res[key].userLastLogin);
})
}
You can access individual elements from array like this (Client Side)
$.ajax({
....
....
success: function (res) {
alert(res[0].userLastLogin);
// OR
alert(res[0]['userLastLogin']);
}
});
Check out this:
$.ajax({
url: 'authenticate2.php',
type: 'POST',
success: function(res) {
var response = $.parseJSON(res);
console.log(res.userLastLogin);
})
or you can just do this in your ajax success:
$.each(JSON.parse(res), function() {
console.log(this[Object.keys(this)[6]]);
});
Try this
var json = '{"id":"1","userName":"admin","userPassword":"admin","userEmail":"admin#admin.com","userRegistrationIP":"","registrationDateTime":"2015-05-28 21:22:54","userLastLogin":"2015-05-28 21:22:54"}';
for(var i = 0; i < json.length; i++) {
var obj = json[i];
console.log(obj.userLastLogin);
}
If u want to use only userLastLogin data then u can try this ,
while($r = mysqli_fetch_assoc($result)) {
$rows['userLastLogin'] = $r['userLastLogin'];
}
I'm trying to loop through the Callback from PHP result.
But I can't or I don't know how to return an array as a Callback
This is my PHP code :
$id = $_GET['id'];
$data = file_get_contents('__url');
parse_str($data);
$array = explode(',', $url_encoded_fmt_stream_map);
foreach($array as $item) {
parse_str($item);
echo $_GET['callback']."(".json_encode($url).");"; // it should return an array at least 3 urls
}
And this is my Jquery code :
$.ajax({
url:"file.php",
dataType: 'jsonp',
data: {id: id},
success:function(response){
$('body').append(response);
}
});
It gives me one result only but it should return an array, it's working like I did not use foreach loop in the php code.
I tested the PHP code without Ajax Request and it returned an array of urls, but if I used the ajax callback it's returning one url only.
It only returns 1 URL because it only returns the first one.
You should encode your entire array and loop in the success function like so:
PHP:
$id = $_GET['id'];
$data = file_get_contents('__url');
parse_str($data);
$array = explode(',', $url_encoded_fmt_stream_map);
echo json_encode($array);
JS:
$.ajax({
url:"file.php",
dataType: 'jsonp',
data: {id: id},
success:function(response){
var res = JSON.parse(res);
$.each(res, function(key, index){
$('body').append(index);
});
}
});
What if you try something like this:
$id = $_GET['id'];
$data = file_get_contents('__url');
parse_str($data);
$array = explode(',', $url_encoded_fmt_stream_map);
$final_arr = array();
foreach($array as $item) {
parse_str($item);
array_push($final_arr , $url);
}
$jsonp = json_encode($final_arr);
if(isset($_GET['callback'])){
header("Content-Type: application/json");
echo $_GET['callback'] . '(' . $jsonp . ')';
}else{
echo $jsonp;
}
and your ajax:
$.ajax({
url:"file.php",
dataType: 'jsonp',
data: {id: id},
success:function(response){
var obj = JSON.parse(response);
$.each(obj, function(key,val){
console.log(key);
console.log(val); //depending on your data, you might call val.url or whatever you may have
});
$('body').append(response);
}
});
i am sending an array from one page to another through ajax.i used JSON object for this purpose.I am able to send but i am not able to capture in the ajax page.Please help me how to capture the array values.
javascript:
var jsonString = JSON.stringify(dataString);
$.ajax({
type: "POST",
url: "ajaxpage.php",
data: {data : jsonString},
cache: false,
success: function(response){
alert("ok");
$('#test').html(response);
}
});
PHP page:
$data = json_decode(stripslashes($_POST['data']));
// here i would like use foreach:
foreach($data as $d){
echo $d;
}
please help me in this regard.
I am stuck up here
If you want to decode the JSON into an associative array, you should specify that in json_decode:
Replace
$data = json_decode(stripslashes($_POST['data']));
With
$data = json_decode(stripslashes($_POST['data']), true);
See json_decode reference for more information
Also, is dataString possibly already a JSON string?
I think this is what you want, I have tried and it works
in your php:
<?php
$data = ($_POST['data']);
foreach($data as $d){
echo stripslashes($d);
}
?>
in your jsvascript/jquery:
<script>
$(document).ready(function(){
$('a').on('click',function(){
var dataString = {
'id':'1',
'name':'peter parker',
'age':'unknown',
'role':'spiderman'
}
$.ajax({
url: "<?php echo $this->webroot;?>test_1.php",
data: {'data':dataString},
type: "POST",
cache: false,
success: function(response){
alert("ok");
$('#test').html(response);
}
});
})
})
</script>
in your html
Click Me
<div id="test"></div>