I'm programming an web page and I really stucked trying to send an Array of JSON objects to my PHP backend script.
this is my javascript code (using jQuery):
var toSend = new Array();
$("input[type=checkbox]").each(
function (indice, item)
{
var dom = $(item);
var domJSON = {
id: dom.attr("value"),
checked: (dom.attr("checked") == "checked" ? true : false)
};
//put object as JSON in array:
toSend.push($.toJSON(domJSON));
}
);
$.ajax({
type:"POST",
url: "salvar_escala.php",
data: {checkbox: toSend},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
And in PHP I have this:
//Grab the array
$arrayFromAjax = $_POST['checkbox'];
foreach($arrayFromAjax as $aux) {
$temp = json_decode($aux, true);
$id = $temp['id'];
$value = $temp['checked'];
//This line doesn't print anything for $id and $value
echo "Id: $id | Value: $value<br />";
//This line prints an crazy string, but with right values
echo "CHEKBOX[] => $b<br />";
}
In this code, I'm decoding my objects to json, putting then in an array and sending. I also tried but objects in array (without json), and then, convert the array to json, and send them like that:
$.ajax({
type:"POST",
url: "salvar_escala.php",
dataType: "json",
data: {checkbox: $.toJSON(toSend)},
success: function(response) {
$("#div_salvar").html(response);
},
error: function() {
alert("Erro");
}
}
);
But in this case, it's worse, the error function is called.
You should be able to do the following in PHP
<?php
$checkboxes = json_decode($_POST['checkbox']);
foreach($checkboxes as $checkbox) {
$id = $checkbox['id'];
$val = $checkbox['value'];
print $id . ': ' . $val;
}
The problem is that you're trying to loop through a JSON string without first decoding it into a PHP array.
Related
When sending data to an ajax post call I get "NULL" returned.
I am sending a lot more data (which all works), but left it out of the snippet to make it more clear.
When I log the var in my console, it shows up. When I check the network tab if the data is properly sent, it shows up. When I var_dump the $_POST in PHP it returns NULL.
Jquery
function get_cars_ajax() {
var filterAdvertentienummer = 119005595; // is number
$.ajax({
type: 'POST',
url: '/wp/wp-admin/admin-ajax.php',
dataType: 'html',
data: {
'action' : 'get_cars_filter',
'filterAdvertentienummer ' : filterAdvertentienummer,
},
success: function(data) {
if(data != '') {
// DO SOMETHING
} else {
// DO NOTHING
}
},
error: function(data) {
console.log(data);
}
}
PHP
function get_cars_filter() {
global $post;
$context = Timber::get_context();
var_dump($_POST['filterAdvertentienummer']); // = NULL
echo $_POST['filterAdvertentienummer']; // = empty string
if (isset($_POST['filterAdvertentienummer'])) {
$advertentienummer = $_POST['filterAdvertentienummer'];
} else {
$advertentienummer = "";
}
$queryList = '?skip='.$current_page.'&limit='.$limit.'&sort='.$sort.'&order='.$order;
if ($advertentienummer != "") {
$queryList = $queryList . "&advertentienummer=" . $advertentienummer;
} else {
var_dump($advertentienummer);
}
$args = array(
'headers' => array(
'accept' => 'application/json'
)
);
$results = wp_remote_retrieve_body(wp_remote_get('http://IP/cars'.$queryList, $args));
return $results;
}
I noticed a mistake in your ajax code.
Your code line:
'filterAdvertentienummer ' : filterAdvertentienummer,
you have added one space in the variable name so it's not gonna be readable by PHP.
Modified code :
'filterAdvertentienummer' : filterAdvertentienummer
Now PHP will read this variable as a string. You can convert strings in int with PHP.
I'm trying to send a username from the view to the controller through Ajax like this :
$('#exampleFormControlSelect1').change(function(){
var username =$('#exampleFormControlSelect1').val();
$.ajax({
type: 'POST',
dataType: "json",
url: "Panier/loadPanier",
data: {username: username},
success: function(result){
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
},
});
});
and I try to use the sent value to do some work:
public function loadPanier()
{
$res = [];
$username = $this->input->post('username');
$panier_data = $this->model_panier->getPanierData($username);
foreach ($panier_data as $k => $v) {
$idPiece = $v['idPiece'];
$qte = $v['quantity'];
$piece_data = (array)$this->model_catalogue->getDetail($idPiece);
$price = (int)$piece_data['Unit Price'];
$montant = $qte * $price;
array_push($res, array(
'idPiece' => $idPiece,
'Description' => $piece_data['Description'],
'qte' => $qte,
'prix HT' => round($piece_data['Unit Price'], 3),
'montant' => $montant
));
}
return $res;
}
In my URL I'm getting this error :
Invalid argument supplied for foreach()
but here's what I'm noticing by doing var_dump($username):
C:\wamp64\www\PortalDealer\application\controllers\Panier.php:66:null
So my data is not passing!
Can you help me with this?
EDIT
showcase the result of this part of the code :
var_dump($_REQUEST);
$res = [];
$username = $this->input->post('username');
var_dump($username);
$panier_data = $this->model_panier->getPanierData($username);
var_dump($panier_data);
The below code should send your data to Panier/loadPanier/.
$('#exampleFormControlSelect1').change(function(){
var val1 =$('#exampleFormControlSelect1').val();
$.ajax({
method: "POST",
url: "Panier/loadPanier/",
data: { username: val1}
}).done(function( result ) {
$("#tbodyid").empty();
var data1 = JSON.parse(result);
console.log(data1) ;
});
});
You were seeing null every time you did var_dump() because you were trying to load the page independently. The page will only give you the POST value if you are going to the page thru the form, in this case, the form is javascript. When you load a page with POST method in javascript, the response is sent to the same page with ajax so you can work with your code without having to refresh the page.
Also: You cannot return data to javascript. You have to print it out to client side so that your javascript's JSON parser can read it. Therefore, instead of return $res; :
echo json_encode($res);
I have tried different ways to make this work but it is still not working. data[0].urgency is undefined. I tried to stringify data but a bunch of \n in between the result (see below).
Thank you in advance.
My ajax code:
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
console.log(data.length);
console.log(data[0].urgency);
}
});
}
My PHP code:
<?php
session_start();
ob_start();
require_once('../../mysqlConnector/mysql_connect.php');
$results = array();
$query="SELECT COUNT(initID) AS count, urgency, crime, initID, TIMESTAMPDIFF( minute,dateanalyzed,NOW()) AS minuteDiff FROM initialanalysis WHERE commanderR='0' AND stationID='{$_SESSION['stationID']}';";
$result=mysqli_query($dbc,$query);
while ($row = $result->fetch_assoc()){
$count = $row['count'];
$urgency = $row['urgency'];
$crime = $row['crime'];
$initID = $row['initID'];
$minuteDiff = $row['minuteDiff'];
$results[] = array("count" => $count, "urgency" => $urgency, "crime" => $crime, "initID" => $initID, "minuteDiff" => $minuteDiff);
}
echo json_encode($results);
?>
Result of PHP:
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4743"}]
I think the result is in wrong format? I'm not sure.
This is the result of console.log(data), there is a comment tag of html and I don't know why:
<!-- -->
[{"count":"9","urgency":"Low","crime":"Firearm","initID":"6","minuteDiff":"4761"}]
Use a JSON parser for validate the json response like JSON.parse
function ValidateJsonString(str) {
try {
JSON.parse(str);
} catch (e) {
return false;
}
return true;
}
Update your ajax call like this
function ajaxCall() {
$.ajax({
type: "POST",
url: "../nav/post_receiver.php",
success: function(data) {
data= jQuery.parseJSON(data);
console.log(data.length);
console.log(data[0].urgency);
}
});
}
I am trying to create a validation to check if my data already exist or not using Ajax. It's works, but now I want to add JSON inside my Ajax php file and retrieve the array inside of the JSON, unfortunately it doesn't work as expected.
Take a look at my JQuery below :
$("#button").click(function(e) {
e.preventDefault();
var tempcode = $('#someobject').val();
$.ajax({
method:"POST",
dataType: "text",
url:'example.php',
data:{
Code: tempcode
},
success:function(data){
var my = JSON.parse(data);
alert(my.Title);
}
});
});
And below is example.php :
$AJAXCode = $_POST['Code'];
$myObj = array();
$strSQL = mysql_query("select * from sometable where Code ='$AJAXCode'");
$check = mysql_num_rows($strSQL);
if ($AJAXCode == NULL) {
$myObj->Title= "Choose Something";
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
} else {
if ($check != 0) {
$myObj->Title= "Already Exist !";
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
} else {
$myObj->Title= "You are good !!!";;
$myObj->Total = $check;
$myJSON = json_encode($myObj);
echo $myJSON;
}
}
As you can see at my JQuery scripts, I am trying to call "Title" inside my JSON array, but it doesn't work. Am I missing something ?
This is the result in Console.log, no error show up just this:
Firstly, you initialize your object the wrong way. Use instead of $myObj = array(); one of the following:
$myObj = (object) array();
or
$myObj = new StdClass();
For more information and more ways to create your object, look up this link.
Next, change the dataType attribute to:
dataType: "json"
in order to tell your script that your PHP response is encoded as JSON. You can use now your response the regular way, with JSON.parse(), try:
console.log(JSON.parse(data));
Replace Below Code :
$("#button").click(function(e) {
e.preventDefault();
var tempcode = $('#someobject').val();
$.ajax({
method:"POST",
dataType: "json",
url:'example.php',
data:{
Code: tempkode
},
success:function(data){
console.log(data.Title); // Example
}
});
});
Change variable tempkode to tempcode in data
I have this jQuery code that adds to an array inside an $each loop:
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
new_file_edits.push(JSON.stringify(new_edit));
jQuery new_file_edits array output
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
and im trying to post it to call.php like this:
$.ajax({
type: "POST",
url: "/call.php",
data: "edit_files="+ arrayVarHere,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
alert(+msg);
}
});
In the PHP file call.php i have this code:
if(isset($_POST['edit_files'])){
$edit_array = $_POST['edit_files'];
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
but i get this error and i cant figure out how to fix it, been googling it for a while now...
error:
Warning: Invalid argument supplied for foreach() in /home2/dddd/public_html/call.php on line 237
Line 237: foreach($edit_array as $key => $value){
Any help is much appreciated!
-Morten
EDIT 1:
I changed $edit_array = $_POST['edit_files']; to $edit_array = array($_POST['edit_files']);
And now it outputs:
{"file_id":"1857","file_realname":"dddd[1].mp4","file_folder":"/"},
{"file_id":"1856","file_realname":"aaaa[1].jpg","file_folder":"/"},
{"file_id":"1855","file_realname":"ssss[1].jpg","file_folder":"/"}
How do i go from here with the foreach($edit_array as $key => $value){ part?
Edit 2:
i build my arrayVarHere like this:
$.each( $selected_files_array, function( index, value ){
//i get $file_id, $new_file_realname and $new_file_folder with some code here
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
arrayVarHere.push(JSON.stringify(new_edit));
});
change your code like this:
data: "edit_files="+ arrayVarHere,
call json data by json_decode in call.php
if(isset($_POST['edit_files'])){
$edit_array = json_decode($_POST['edit_files'],true); //return array
$file_array = array();
foreach($edit_array as $key => $value){
$file_array[$key] = $value;
}
print_r($file_array);
die();
}
in your ajax alert should be
success: function(msg){
alert(msg); //remove plus sign ,this can output `NaN`
}
check edit_array is array print_r($edit_array);
check contentType is used form data then correct otherwise used json type
if form data then check data: edit_files[]: arrayVarHere,
It returns this array
Array ( [0] => [{"file_id":"1857","file_realname":"aq53pop_460sv[1].mp4","file_folder":"/"},{"file_id":"1859","file_realname":"aKqbD8Q_460sv[1].mp4","file_folder":"/"},{"file_id":"1856","file_realname":"aDopymK_700b[1].jpg","file_folder":"/"}] )
how can i loop the array and access file_id value etc?
The way you are passing Data to PHP may not be that ideal. Here is what might get you started:
PHP: call.php
<?php
$data0 = isset($_POST['data_0']) ? json_decode($_POST['data_0'], true) : null;
$data1 = isset($_POST['data_1']) ? json_decode($_POST['data_1'], true) : null;
$data2 = isset($_POST['data_2']) ? json_decode($_POST['data_2'], true) : null;
$arrData = array(
'data0' => $data0,
'data1' => $data1,
'data2' => $data2,
);
foreach($arrData as $dataKey=>$dataObject){
$tempFileID = $dataObject->file_id;
$tempFileName = $dataObject->file_realname;
$tempFileFolder = $dataObject->file_folder;
// DO SOMETHING WITH THESE DATA AND THEN BUILD UP A RESPONSE FOR AJAX + SEND IT...
// UNCOMMENT TO SEE THE DATA IN YOUR NETWORKS CONSOLE BUT
// IF YOU DO THIS (SINCE YOU EXPECT JSON RESPONSE) YOUR AJAX WILL RESPOND WITH AN ERROR...
// var_dump($dataObject);
}
// RESPOND WITH THE SAME DATA YOU RECEIVED FROM AJAX: JUST FOR TESTING PURPOSES...
die( json_encode($arrData));
?>
JAVASCRIPT: BUILDING THE DATA FOR PHP
<script type="text/javascript">
var dataForPHP = {};
var iCount = 0;
$.each( $selected_files_array, function( index, value ){
var keyName = "data_" + iCount;
new_edit = {};
new_edit['file_id'] = $file_id;
new_edit['file_realname'] = $new_file_realname;
new_edit['file_folder'] = $new_file_folder;
dataForPHP[keyName] = new_edit;
iCount++;
});
</script>
JAVASCRIPT: AJAX REQUEST
<script type="text/javascript">
$.ajax({
type : "POST",
url : "/call.php",
datatype : "JSON",
data : dataForPHP,
contentType: "application/x-www-form-urlencoded;charset=UTF-8",
success: function(msg){
if(msg){
alert("Ajax Succeeded");
console.log(msg);
}
}
});
</script>