Can't pass array through ajax [duplicate] - javascript

This question already has answers here:
Javascript POST not working - Sending Javascript array to PHP
(4 answers)
Closed 4 years ago.
Trying to have data passed to a php script so the said data can be added to the session.
The debug console log returns are the following:
the quant array is correct and typeof is object, the JSON.stringified data's type is string , lastly success from the ajax success.
In the PHP script var_dump return is NULL
$('#bigsubmit').click(function() {
var quant = [];
$('.input-number').each(function() {
var tmp = {};
tmp.id = this.id;
tmp.qu = $(this).val();
quant.push(tmp);
});
console.log(quant);
var data = JSON.stringify(quant);
console.log(typeof(data));
$.ajax({
type: "POST",
url: url,
data: {
data: data
},
success: function() {
console.log("success");
}
});
the php script (url var)
<?php
session_start();
$_SESSION['test'] = $_POST['data'];
var_dump($_SESSION['test']);
?>

Your success callback function isn't taking in a parameter, try changing to this,
success:function(data) {
console.log(data);
}

Related

how to properly use else if in javascript [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 2 years ago.
i have this script for submitting a form using jquery ajax, everything works fine except i can only get two responses, the loading part is implemented but the rest of them i can only get the else statement. the else if, none is working.
the json statement works just fine. and the data is passed to php successfully but the responses are not according.
(function($) {
'use strict';
const FormFunction = function(){
const checkSelectorExistence = function(selectorName) {
if(jQuery(selectorName).length > 0){return true;}else{return false;}
};
let registerForm = function() {
if(!checkSelectorExistence('.registration-form')){return;}
jQuery('.registration-form').on('submit', function( event ) {
event.preventDefault();
let response = $('.loading').addClass('show').show();
jQuery(this).find(".message").addClass('active').show('slow');
const formData = new FormData(this);
const formAction = jQuery(this).attr('action');
jQuery.ajax({
type: 'POST',
url: formAction,
data: formData,
contentType: false,
cache: false,
processData:false,
dataType: 'json',
beforeSend : function(){
$('.info').addClass('show').show('slow');
},
complete : function(){
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
success : function(data)
{
if(data.status === 1){
response = $('.success').addClass('show').show('slow');
}
else if(data.status === 2) {
response = $('.taken').addClass('show').show('slow');
}
else if(data.status === 0){
response = $('.empty').addClass('show').show('slow');
}
else {
response = $('.error').addClass('show').show('slow');
}
$('.registration-form .message').html(response).delay(5000).hide('slow');
$('.registration-form')[0].reset();
},
error : function(data){
$('.error').addClass('show').show('slow');
$('.registration-form')[0].reset();
},
});
});
}
/* Functions Calling */
return {
afterLoadThePage:function(){
registerForm();
},
}
}(jQuery);
/* jQuery Window Load */
jQuery(window).on("load", function (e) {FormFunction.afterLoadThePage();});
})(jQuery);
Based on some comments that we traded I managed to test it out and found out, what is the root of your problem. Even thought you are setting dataType as JSON, what you actually pass from PHP is a string of value "{\"status\":1}". This is currently the content of your data variable in Success function of your AJAX call.
Adding following line of code at begging of your Success function will do what you want it to do: data = JSON.parse(data);. This will parse string returned by PHP into an JSON object in JS which will create data.status instance holding desired value of number type.
I did some test on my end and it worked as expected with IF and ELSE IF as well.

Passing an array of strings from JS to PHP

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.)

How to access only one object send by json not the whole array in ajax success function?

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

Best practice when changing PHP Data to JS Data via AJAX (especially arrays)

(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.

Array to php and retrieve [duplicate]

This question already has answers here:
Javascript array for AJAX POST send
(2 answers)
Closed 9 years ago.
I need help, I can't find the solution. I have a javascript array which I need to pass to a php script that will store all the array values (max 3) on Session variables. My javascript array comes from a string.split call:
var indentificators = id.split("_");
What I need is some help on how to do the Ajax call and then how to get every element of the array one by one.
My main problem is the format that this data has to be sent and how to retrieve it.
PD: I would post my current ajax call code but I think it would not help, it´s all messed up.
JSON is your answer here.. Are you using a javascript library like jQuery or MooTools?
jQuery:
How do I encode a javascript object as JSON?
url = 'target.php';
data = {identificators: JSON.stringify(identificators) };
jQuery.post( url, data, , function( response ) {
//response handling
});
MooTools:
url = 'target.php';
data = { identificators: JSON.encode(identificators) };
howto post (Async) in mootools:
http://mootools.net/docs/core/Request/Request
In php:
$phpArray = json_decode($_POST['identificators']/$_POST['identificators']);
You can format your answer to send as JSON String
For example:
Javascript array:
var indentificators = id.split("_"); // [0] => 'Stack', [1] => 'Overflow'
so you can do this:
var response_to_send = "{\"var1\":" + indentificators[0] + ", \"var2\": " + indentificators[1] + "}";
here you receive this string in your php script (supposing the ajax request is successful and the value of the string in POST is 'values'):
$values = json_decode($_POST['values'])
echo $values[0]; // This print 'Stack' echo $values[1]; // This print 'Overflow'
I hope this is what your searching
var array = id.split("_");
data = JSON.stringify(array);
var url = 'you/url'
$.ajax({
type: "POST",
url: url,
data: {array: data},
});
Finaly I solved it:
var identificadors = id.split("_");
$.ajax({
url: './phpScripts/comunicador.php?method=sessioList',
type: "POST",
data: ({data: identificadors}),
success: function(){
alert('cool');
}
});
Then at my php page:
function sessioList() {
$data = $_POST['data'];
$_SESSION['list_id_product'] = $data[0];
$_SESSION['list_id_tarifa'] = $data[1];
$_SESSION['list_index'] = $data[2];
}
As I said, my main problem was the format for the data to be sent and how to get it.
Thanks all, I really appreciate it.

Categories