I have an array of strings in JS, and I want to send it to php (to be able to add it to db). This is my current code -> showing success message, but not showing the $_POST['array'] variable.
Keep in mind that that array I want to send has string values only and is called times
JS
function fetchDates(){
times = [];
var table = document.getElementById("timeScheduleBody");
var tableRows = table.getElementsByTagName("tr");
for(var j=0;j<tableRows.length;j++){
var tableCells = tableRows[j].getElementsByTagName("td");
for(var i = 0;i<tableCells.length;i++){
if(tableCells[i].getAttribute('class').includes("success")){
var arr = tableCells[i].getAttribute('value').split("-");
var date, hour, mins;
date = arr[0];
hour = arr[1];
mins = arr[2];
times.push(date);
times.push(hour);
times.push(mins);
}
}
}
window.alert(times);
//send array to PHP from jQuery
jQuery.ajax({
type: "post",
url: window.location.href,
data: {array:times},
success: function(){
alert("done");
}
});
}
PHP
<?php
if(isset($_POST['array'])){
$array = $_POST['array'];
echo $array[0];//just testing -> output: nothing
foreach($array as $d){
print '<script>window.alert($d);</script>';//also just to test -> output: nothing
}
}
?>
But you're not getting and showing the response of the ajax call, to see the response you have to get the response in the success function...
PHP (test.php - Create this file and put it in the same directory):
<?php
if(isset($_POST['array']))
print_r($_POST['array']);
?>
JQUERY:
$.ajax({
type: 'POST',
url: 'test.php',
data: { array: times },
success: function(response) {
alert(response);
}
});
You'll see the array content. You're sending the javascript array correctly, but if you want to see the response of the ajax call you have to get it in the success function and do something with it (alert it, add it to the DOM, etc.)
Related
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr[] = array($arrResult, // include only one value
$response_array['status'] );//success or not success value
return $return_arr;
}
?>
This $return_arr[] value return to the javascript ajax file >>
$.ajax({
url: 'PHPMethodCalls_AL.php',
type: 'post',
data: {... post many values to php function.. },
success: function(data) {
alert(data);
//data is successfully come as this format >> [[["Testing123"],"success"]]
var results = JSON.parse(data);
alert(results);
// this alert got >> Testing123,success
},
//this one is post value to function
$newCIarrayList = array();
$newCIarrayList = phpfunction(..data include );
echo json_encode($newCIarrayList);
What should I do to get each value as "Testing123" and "success" value separately? I tried with split(",") function but it didn't work.
You can seperate in php function before response to ajax like below .Then you can get easy
<?
function phpfunction(){
//insert data to database //some codes work inside this.
$return_arr = array("data" =>$arrResult, // include only one value
"status" =>$response_array['status'] );//success or not success value
return $return_arr;
}
?>
var results = JSON.parse(data);
alert(results.data || results.status);
What you get back in success: function(data) is a stringified json of a nested array: [[["Testing123"],"success"]].
To get your status and payload out of this structure, you can use the following snippet.
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
console.log(parsedData); // quite nested
var status = parsedData[0][1];
console.log(status);
var payload = parsedData[0][0][0];
console.log(payload);
Or using ES6 destructuring:
var data = '[[["Testing123"],"success"]]';
var parsedData = JSON.parse(data);
[[[payload], status]] = parsedData;
console.log(status);
console.log(payload);
I would however suggest that you revise your php-side code, and make it so that it forms a simpler structure, ideally:
{"status": "success", "payload": "Testing123"}
I am trying to receive data from the controller to the view using json_encode and ajax functions. But I am sending to separate values through json, and I am tring to access it. So how can I separate those two objects, and get only a single value?
Let me show you my code:
function check_relation_status()
{
var id=$('.id_data').attr('value');
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/check_relation_status"); ?>',
data:{id:id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_Data = $.parseJSON(ParsedObject);
var senders_id=sender_Data.senders_id;
jQuery.ajax({
type:'POST',
url:'<?php echo base_url("user/get_senders_data"); ?>',
data:{id:senders_id},
dataType:'json',
success:function(data)
{
console.log(data);
var ParsedObject = JSON.stringify(data);
var sender_values = $.parseJSON(ParsedObject);
var senders_name=sender_values.sender_data;
// alert(senders_name);
$.each(sender_values, function(key,data)
{
var uname = data.uname;
// alert(uname);
$('#friendship_request').append('<div>'+uname +'has sent you a request</div>');
});
}
});
}
});
}
now the controller code
public function get_senders_data()
{
$sender_id=$this->input->post('id');
$this->load->model('Pmodel');
$userdata=$this->Pmodel->getUserdata($sender_id);
$senders['senders_data']=$userdata;
$senders['senders_post'] = $this->Pmodel->get_all_count($sender_id);
// print_r($senders);
echo json_encode($senders);
}
the json value '$senders' holds both the values but when i try to access it usng 'each' function it shows the values two time when there is only a single column for uname . let me add some images to explain.
Where I am wrong?
Try to change like below:-
if(uname){
$('#friendship_request').html('<div>'+uname +'has sent you a request</div>');
}
Note:-
1.You are appending all usernames (which is not correct).
2.You are not checking that username is either undefined or null or empty etc
I want to send JS variables using Ajax, to a PHP page so that I could save those variable in the Database. However, it isn't working as I expected.
My JS code:
var a= payment;
var b= count_days;
var c= <?php echo $teacher_id; ?>;
var jsonString1 = JSON.stringify(a);
var jsonString2= JSON.stringify(b);
var jsonString3= JSON.stringify(c);
$.ajax({
type: "POST",
url: "student_searching_availibility.php",
data: {
data1 : jsonString1,
data2:jsonString2,
data3:jsonString3
},
cache: false,
success: function() {
alert('success');
}
});
Now my PHP
$data1 = json_decode($_POST['data1']);
$data2 = json_decode($_POST['data2']);
$data3 = json_decode($_POST['data3']);
include "db.php";
$sql2= "INSERT INTO availibility_status_date(student_id,teacher_id,status) VALUES ('$data1','$data2','$data3')";
if(!mysqli_query($con,$sql2)){
die("error". mysqli_connect_error());
}
I have searched almost all such queries here but still could not solve the problem.
JSON is javascrip object notation you cannot JSON.stringify a variable, it has to be an object. Try this.
var data = {}; //defines that data is a javascript object
//assign your values to there respective indexes
data['a'] = payment;
data['b'] = count_days;
data['c'] = <?php echo $teahcer_id; ?>
//since data is now a object you can json.stringify it
var jsonData = JSON.stringify(data);
//make ajax request with json data
$.ajax({
type: "POST",
url: "student_searching_availibility.php",
data: { data:jsonData },
cache: false,
success: function()
{
alert('success');
}
});
On your PHP, remember that json_decode() expects second parameter the $assoc parameter as a boolean, its default is false which means that if you only specity the json string to be decoded then it will return you data in an object form, for associative array pass true as second parameter.
$data = json_decode($_POST['data']); //$data is now an object
$data->a; //your payment
$data->b; //your count_days
$data = json_decode($_POST['data'],true); //$data is now an associative array
$data[a]; //your payment
$data[c]; //your count_days
when you were inserting into sql $data1, $data2 you were actually trying to store objects into your table, here mysqli_query should have returned false and your code died thus you are not getting any error.
So your sql insert values depending upon your json_decode($_POST['data'], true or false) use either $data->a or $data[a] i.e,
"INSERT INTO availibility_status_date(student_id,teacher_id,status) VALUES ('$data[a]','$data[b]','$data[c]')";
OR
"INSERT INTO availibility_status_date(student_id,teacher_id,status) VALUES ('$data->a','$data->b','$data->c')";
I used AJAX to send back an array with many variables worth of data to my page to have displayed. The array looks something like this right now:
{"dateName":"05/18/2016","hour1":null,"hour2":null,"hour3":null,"hour4":null,"hour5":null,"hour6":null,"hour7":null,"hour8":null,"hour9":null,"hour10":null,"hour11":null,"hour12":null,"hour13":null,"hour14":null,"hour15":null,"hour16":null,"hour17":null,"hour18":null,"hour19":null,"hour20":null,"hour21":null,"hour22":null,"hour23":null,"hour24":null}
Now I am displaying the parts of the array in my data boxes using
//AJAX Data
success: function(data) {
var array = data.split(",");
$("#date").html(array[0]);
i = 0;
while (i < 25) {
$("#hour"+i).html(array[i]);
i++;
}
This displays data that looks like this on my webpage
"hour1":"sleep"
As you can see, the variable name in quotes and the variable value that was passed through ajax. But I only want
sleep
displayed (no quotes, no variable) . How do I get the variable name and quotes out of my displayed data?
Thank you so much!
use this
$.ajax({url: "demo_test.txt", success: function(result){
// $("#div1").html(result);
var parsed = JSON.parse(result);
alert(parsed["hour1"]);
}});
//AJAX Data
success: function(data) {
var hour = "hour";
for(var i=0; i<data.length; i++) {
hour += i;
console.log(data.hour)
}
Through the help of a few of you awesome members here at stackexchange I have finally figured out how to send an ajax, call back multiple variables, and arrange them cleanly on my page. Attached is my code, I hope that this can help future users.
//SEND MULTIPLE DATA THROUGH AJAX
<script>
function ajax() {
$.ajax({
type: "POST",
url: "changeDate.php",
data: {
amount: changeDate,
loginName: "benjamin_lawson"
},
success: function(result) {
//make array out of data
var array = JSON.parse(result);
$("#date").html(array[0]);
i = 0;
while (i < 25) {
//call array information for parts
$("#hour"+i).html(array[i]);
i++;
}
}
});
}
</script>
<?php
//create the array
$response_arr = array();
//add your variables to the array
$response_arr[] = date("m/d/Y", strtotime("+" . $amount . " day"));
$response_arr[] = $row[$dateName];
//echo the final array to be sent to your ajax
echo json_encode($response_arr);
?>
success: function(data) {
var json_obj =JSON.parse(data)
$("#date").html(json_obj['datename']);
i = 0;
while (i < 25) {
$("#hour"+i).html(json_obj['hour'+i]);
i++;
}
}
You can use JSON.parse to convert the string to json obj :
json_obj=JSON.parse(data)
$("#date").html(json_obj['']);
(Secondary title): ajax array recieved as json encoded PHP array not behaving as javascript array
For some reason, my PHP array gets sent over to JavaScript just fine, but when I try to access an individual key of the array, it doesn't return anything, or it returns some other value which doesn't correspond. I am of course using json_encode() in the corresponding PHP file (echoClientData.php):
$id = $_GET['selected_id'];
$id = str_replace("clientSel","",$id);
$getclientinfo = "SELECT * FROM `clients` WHERE `ClientID` = $id";
if ($result = $Database->query($getclientinfo))
{
$row = $result->fetch_row();
$output = $row;
}
echo json_encode($output);
This code works fine:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data;
$('#client-detail-box').html(test);
}
});
And returns an array into the #client-detail-box div, e.g.
["1566","","Adrian","Tiggert","","","","","","","","","","","","0000-00-00","0000-00-00","0.00","","0","","","102","Dimitri Papazov","2006-02-24","102","Dimitri Papazov","2006-02-24","1","0","0"]
However, when I do
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
}
It returns
5
You may need to do one of two things when returning JSON from PHP.
Either set your content type in PHP before echoing your output so that jQuery automatically parses it to a javascript object or array:
header('Content-type: application/json');
or specify that jQuery should treat the returned data as json:
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
dataType: 'json',
success: function(data)
{
var test = data[3]; // should be "Tiggert"
$('#client-detail-box').html(test);
}
});
Be aware, that in your current PHP script, in the event that your query fails, you will be json_encodeing an undefined variable.
Also, your PHP code is entirely open to SQL injection. Make sure you sanitize your $id, either by casting it to (int) or by escaping it before sending it through in your query.
Have you tried using JSON.parse on the value you are getting back from PHP?
e.g.
$.ajax(
{
url: "echoClientData.php?selected_id=" + HTMLid,
type: 'GET',
success: function(data)
{
test = JSON.parse(data); // should be "Tiggert"
$('#client-detail-box').html(test[3]);
}
});
That seems like it would be a fix.