Sending an array of objects to PHP function with jQuery.ajax request - javascript

There is an array of objects like this:
rectangle[0].width = w;
rectangle[0].height = h;
rectangle[1].width = w;
rectangle[2].height = h;
rectangle[3].width = w;
rectangle[3].height = h;
...
How we may to send this array to PHP function with jQuery.ajax request and vise versa, modified array from PHP function as response?
I mind that JS code may be:
request = $.ajax({
type : "POST",
url : "post.php",
data : {rec :rectangle}
});
request.done(function(msg) {
alert(msg);
});
request.fail(function(jqXHR, textStatus) {
alert("Function inaccessible: " + textStatus)
});
and PHP:
if (isset($_POST["rec"]) {
$rec = $_POST["rec"];
$arr_length = count($rec);
$response = $arr_length;
}
echo $response;
Please, demonstrate the true form of request. Thanks.

Very easy:
<script>
var myarray = new Array();
var params = { myarray: myarray };
var paramJSON = JSON.stringify(params);
$.post(
'test.php',
{ data: paramJSON },
function(data) {
var result = JSON.parse(data);
}
</script>
php side:
if(isset($_POST["data"]))
{
$data = json_decode($_POST["data"]);
$myarray = $data->myarray;
foreach($myarray as $singular)
{
// do something
}
}

Related

ajax response returns every value as a single character

I am trying to figure out where I go wrong in this request. I have an ajax post request and I receive the response as single character. For example instead of "name":"john" I get:
n
a
m
e
j
o
h
n
This is my code:
$.ajax({
url: 'test.php',
type: "POST",
data: ({
name: 'john'
}),
success: function(data) {
var JSONString = data;
var JSONObject = JSON.parse(JSONString);
console.log(JSONString);
load(JSONString);
},
error: function() {
alert('error');
}
});
}
<?php
$db = new SQLite3('database.db');
$userAnswer = $_POST['name'];
$results= $db->query("SELECT * FROM 'database' where name='".$userAnswer."'");
$data= [];
while ($res= $results->fetchArray(1))
{
array_push($data, $res);
}
echo json_encode($data);
?>
function load(res) {
var JSONObject = res;
var arr = Object.values(JSONObject);
for (var i = 0; i < arr.length; i++) {
}
}
}

AJAX keep showing wrong data from array

I have a loop that calls multiples AJAX to find out if there's any booking in the database or not. JS will pass the data from an array to AJAX and find it out in database through SQL query.
However, the data returned from the AJAX is correct, and if it's there in database, i want to to show the data returned from AJAX and the current value of array in current loop, but still the data that i show from the array is the last index of array.
javascript :
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
for (var j = 0; j < lap.length; j++){
for (var i = 0;i < jam.length; i++){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
}
return false;
}
PHP File:
<?php
ob_start();
$error=""; // Variable To Store Error Message
$connection = mysqli_connect(/*credential*/);
$tgl = $_POST['date'];
$time = $_POST['time'];
$lap = $_POST['lapangan'];
//Query
$query = mysqli_query($connection, "SELECT * FROM lapangan_book WHERE tanggal='$tgl' and jam='$time' and lapangan='$lap'");
$rows = mysqli_num_rows($query);
$data = mysqli_fetch_array($query);
if($rows > 0){
echo $data['lapangan'];
}else{
echo "0";
}
?>
The output should be
Lapangan A
22lapA
22Lapangan A
But keep showing
Lapangan A
22lapBat
22Lapangan Batminton
Yes, this is happening because of the Asyncroniouse behavior of ajax. There is two tricks you have to send asynchronous request by async: false or you have to call the recursive function after success response from ajax request.
Trick 1- Pass option aysnc: false in ajax request, but some browser will throws warning in synchronous request of ajax
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
},
error: function () {
$('#output').html('ERROR!');
},
});
}
Trick 2: Recursive function, this is most accurate way of calling
function getButtonInfo() {
var jam = [7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22];
var lap = ['Lapangan A','Lapangan B','Lapangan Batminton'];
var lapId = ['lapA','lapB','lapBat'];
var i=0;
var j=0;
var ajaxCall= function(){
var lapIdFix = jam[i]+lapId[j];
var lapId2 = jam[i]+lap[j];
var lap1 = lap[j];
if(jam[i] < 10){
var jamFix = '0'+jam[i]+':00:00';
}else{
var jamFix = jam[i]+':00:00';
}
$.ajax({
type: "POST",
url:'get-button-avail-ajax.php',
async:false,
data: {
date: document.getElementById('tgllapA').value,
time: jamFix,
lapangan: lap[j]
},
complete: function (response) {
if(response.responseText != "0"){
document.getElementById(lapIdFix).disabled = true;
$('#output').html(response.responseText );
$('#output1').html(lapIdFix);
$('#output2').html(lapId2);
}else{
$('#output3').html(response.responseText);
}
//$('#output').html(response.responseText);*
var recursiveCall=true;
i=i+1;
if(i>=jam.length){
j=j+1;
if(j>=lap.length) recursiveCall= false;
else i=0;
}
if(recursiveCall===true)
{
ajaxCall();
}
},
error: function () {
$('#output').html('ERROR!');
},
});
}
ajaxCall();
return false;
}
I have written code for your understanding might be your have to made come modification in this code

Unable to see the source of the problem with the code for sending data to PHP file

I am very sorry to appear much ignorant but I have experienced this problem for long and I am now completely unable to understand why my JQuery function is not working.
I need this code to send data to PHP file which I am sure its working. I have tried to code everything with php but I have found there are place that I will have to include ajax.
$(document).ready(function(){
$('#sending').on('submit', function(event){
event.preventDefault();
if(($('#receiver_id1').val() == '0') && ($('#receiver_id2').val() == '0') && ($('#receiver_id3').val() == '0'))
{
alert("Please fill in the recipient!");
return false;
}
else if($.trim($("#message").val()) == '')
{
alert("You cannot send an empty message.");
return false;
}
else if($('#subject').val() == '')
{
var retVal = confirm("Are you sure to send a message without a subject?");
if( retVal == true ) {
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
type:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
} else {
return false;
}
} else
{
var receiver_id1 = $('#receiver_id1').val();
var receiver_id2 = $('#receiver_id2').val();
var receiver_id3 = $('#receiver_id3').val();
var receiver_name1 = $('#receiver_id1').text();
var receiver_name2 = $('#receiver_id2').text();
var receiver_name3 = $('#receiver_id3').text();
var from_user_name = '<?php echo $from_user_name;?>';
var from_user_id = '<?php echo $from_user_id;?>';
var subject = $('#subject').val();
var message = $('#message').val();
$.ajax({
url:"messaging.php",
type:"POST",
data:{receiver_id1:receiver_id1, receiver_id2:receiver_id2, receiver_id3:receiver_id3, receiver_name1:receiver_name1, receiver_name2:receiver_name2, receiver_name3:receiver_name3, from_user_name:from_user_name, from_user_id:from_user_id, subject:subject, message:message},
success:function(data)
{
$('#receiver_id1').val("0");
$('#receiver_id2').val("0");
$('#receiver_id3').val("0");
$('#subject').val("");
$('#message').val("");
var employee_id = $(this).attr("id");
$.ajax({
url:"select.php",
method:"post",
data:{employee_id:employee_id},
success:function(data){
$('#employee_detail').html(data);
$('#popup').modal("show");
}
});
},
error: function(jqxhr, status, exception) {
alert('Exception:', exception);
}
});
}
});
});
I really need help. I absolutely need this script to work. Thanks in advance.

display data js from datebase sql [duplicate]

This question already has answers here:
How do I return the response from an asynchronous call?
(41 answers)
Closed 5 years ago.
I would like to push my value of textbox to sql and then display it.
I read a lot topics but still nothing. I have always problem to explain my problems but I hope u will see what i want to do escpecialy when u look at db2.php
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: "POST",
url: "db2.php",
data: {'name': nw },
success: function (json) {
jss = json.PYT;
oss = json.ODP;
console.log(jss);
}
});
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
and my db2.php .
<?php
header('Content-type: application/json');
include 'connect.php';
if (isset($_POST['name'])) {
$name = $_POST['name'];
$queryResult = $connect->query("select * from Chatbot where '$name' LIKE
CONCAT('%',PYT,'%')");
$result = array();
while($pomoc = $queryResult->fetch_assoc()){
$result[] = $pomoc;
}
}
echo json_encode($result);
Now my result is {}, echo is null.
console.log(nw)
VM289:1 dsasa
undefined
I know how to get just output from ajax but if i want to push this data everything goes wrong. Best regards
UPDATE. Now I would like to get jss value out of this function to the other one.
var jss = {}; //(first line code)
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
nw = newMessage;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
UPDATE 2
var jss2 = {};
var nw;
$(function(){
username();
$("#textbox").keypress(function(event){
if ( event.which == 13) {
if ( $("#enter").prop("checked") ){
$("#send").click();
event.preventDefault();
}
}
});
$("#send").click(function(){
var username = "<span class ='username' = >Klient: </span>";
var newMessage = $("#textbox").val();
$("#textbox").val("");
var prevState = $("#container").html();
if( prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + username + newMessage);
$("#container").scrollTop($("#container").prop("scrollHeight"));
ai(newMessage);
});
})
function send_message(message){
var prevState = $("#container").html();
if(prevState.length > 3){
prevState = prevState + "<br>";
}
$("#container").html(prevState + "<span class = 'bot'>Chatbot: </span>" + message);
}
function username(){
$("#container").html("<span class = 'bot'>Chatbot: </span>Hi!");
}
function myFunction() {
var x = document.getElementById("textbox").value;
}
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
}
});
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
I think this is what you need to do with your function so that you can use the jss variable properly, once the ajax request has completed:
function ai(message){
var jss;
message = message.toLowerCase();
nw = message;
$.ajax({
type: 'POST',
url: 'db2.php',
data: {
'name': nw,
},
success: function(data){
jss = data[0].PYT;
console.log(jss);
if ((message.indexOf(jss)>=0) || (message.indexOf("?")>=0)){
send_message(Answer);
return;
}
else{
send_message("Nope ");
}
}
});
}
Any code which relies on the jss variable must not be executed until after the ajax call has completed. Since ajax calls run asynchronously, the only way to guarantee this is for that code to be included in (or triggered from) the "success" callback function in your ajax request.

Loading data from controller to chart Jquery/ MVC/ C#

I have the following controller code to return chart data to jquery.
UPDATE: I have modified the code as suggested, but still getting error.
public JsonResult GetLeaveDataForPieChart(int user_id)
{
List<EmployeeLeaveHeader> elh1 = new List<EmployeeLeaveHeader>();
List<ChartEvent> ch = new List<ChartEvent>();
elh1 = itlbg1.EmployeeLeaveHeaders.Where(f => f.Employee_ID == user_id).ToList();
foreach (var item in elh1)
{
ChartEvent ce = new ChartEvent();
ce.value = (item.leaveAvailable * 100).ToString();
ce.color = item.CompanyLeaves.LeaveTypes.color;
ce.highlight = "#ffffff";
ce.label = item.CompanyLeaves.LeaveTypes.typeDescription + " Leave Available";
ch.Add(ce);
ChartEvent ce1 = new ChartEvent();
ce1.value = (item.leaveTaken * 100).ToString();
ce1.color = item.CompanyLeaves.LeaveTypes.color_light;
ce1.highlight = "#ffffff";
ce1.label = item.CompanyLeaves.LeaveTypes.typeDescription + " Leave Taken";
ch.Add(ce1);
}
return Json(ch, JsonRequestBehavior.AllowGet);
}
I need to retrieve data in jquery so that it is in the required format to be passed to pie data.
(document).ready(function () {
user_id = $("#user_id_1").text();
$.ajax({
url: '/Leave/GetLeaveDataForPieChart/',
cache: false,
data: { user_id: user_id },
type: "GET",
datatype: "json",
success: function (data) {
alert(data);
var pieChartCanvas = $("#pieChart").get(0).getContext("2d");
var pieChart = new Chart(pieChartCanvas);
var PieData = $.each(data, function (idx, obj) {
var leave = new Object();
leave.value = obj.value;
leave.color = obj.color;
leave.highlight = obj.highlight;
leave.label = obj.label;
alert(leave);
return leave;
});
var pieOptions = {
//pie options..
};
pieChart.Doughnut(PieData, pieOptions);
}
});
Can anyone explain how to convert the json data to javascript object to be passed to the pie chart?
Here is how you parse JSON string into object.
var jsonObject = JSON.parse(jsonString);
here is how you use jquery to fetch the data and use it for your chart
$.ajax({
url: '/<Controller>/GetLeaveDataForPieChart/',
cache: false,
data: { user_id: <UserID> },
type: "GET",
success: function (data, textStatus, xmlHttpRequest) {
data = JSON.parse(data);
//....
//....
//Chart
//....
//....
//....
}
});

Categories

Resources