ajax post size limitation or server limitation - javascript

Upload large files using PHP well done. I set the value of upload_max_filesize and post_max_size in php.ini :
upload_max_filesize = 64M
post_max_size = 64M
But while large files can not be loaded using Ajax. Less than 5 KB file to be uploaded correctly with Ajax.
For large files I get the following error in my console:
Object {readyState: 4, responseText: "", status: 200, statusText: "OK"}
How do I upload large files using the code below?
My ajax code:
$("#submit-edit-order").click(function () {
//*****get data input
var formData = new FormData();
formData.append('action', 'update_order');
formData.append('order_id', $('input[name=order_id]').val());
formData.append('customer_name', $('input[name=customer_name]').val());
formData.append('customer_id', $('input[name=customer_name]').data("cid"));
formData.append('date', $('input[name=date]').val());
formData.append('order_status', $('#order_sataus').find(":selected").val());
formData.append('total_price', $('input[name=totalprice]').val().replace(/,/g, ''));
formData.append('quits', $('input[name=quits]').val().replace(/,/g, ''));
formData.append('desc', $('#desc').val());
formData.append('desc2', $('#desc2').val());
$.each($("input[type=file]"), function (i, obj) {
$.each(obj.files, function (j, file) {
formData.append('orderpic[]', file);
});
});
//ajax start and ajax complatet
ajax_loading();
$.ajax({
url: "../../includes/ajax/ajax.php",
data: formData,
processData: false,
contentType: false,
type: 'POST',
dataType: 'json',
success: function (response) {
if (response.type == 'error') {
output = '<div class="alert alert-danger" style="margin-top:12px;">' + response.text + '</div>';
} else {
location.reload();
output = '<div class="alert alert-success" style="margin-top:12px;">' + response.text + '</div>';
}
$("section").find("#results").html(output).fadeIn('slow');
},error: function(data){
console.log(data);
}
});
});
PHP code:
if($_POST['action']=='update_order'){
$order_id = $db->escape($_POST['order_id']);
$customer_id = $db->escape($_POST['customer_id']);
$date = explode("/", $_POST['date']);
$date = jDateTime::toGregorian($date[0], $date[1], $date[2]);
$date = $date[0]."/".$date[1]."/".$date[2];
$status = $_POST['order_status'];
$total_price = $_POST['total_price'];
$quits = $_POST['quits'];
$desc = $_POST['desc'];
$desc2 = $_POST['desc2'];
//file settings
$files = array();
$uploaddir = '../../uploads/orders/';
for($i=0; $i<count($_FILES['orderpic']['name']); $i++) {
//Get the temp file path
$tmpFilePath = $_FILES['orderpic']['tmp_name'][$i];
//Make sure we have a filepath
if ($tmpFilePath != "") {
//Setup our new file path
$time = time();
$ext = pathinfo($_FILES['orderpic']['name'][$i], PATHINFO_EXTENSION);
//$FilePath = $uploaddir . $time .'.'. $ext;
$FilePath = $uploaddir . $time. basename($_FILES['orderpic']['name'][$i]);
//Upload the file into the temp dir
if(move_uploaded_file($tmpFilePath, $FilePath)){
$resizeObj = new resize($FilePath);
$resizeObj -> resizeImage(200, 350, 'portrait');
$newFilePath = $uploaddir ."200_350". $time. basename($_FILES['orderpic']['name'][$i]);
$resizeObj -> saveImage($newFilePath, 100);
unlink($FilePath);
$files[] = "200_350". $time. basename($_FILES['orderpic']['name'][$i]);
}
}
}
$files = implode("|", $files);
$data = array(
"user_id"=>$customer_id,
"productImgLink"=>$files,
"totalPrice"=>$db->escape($total_price),
"quits"=>$db->escape($quits),
"orderDesc"=>$db->escape($desc),
"orderDesc2"=>$db->escape($desc2),
"status"=>$db->escape($status),
"date"=>$db->escape($date)
);
$db->where("order_id",$order_id);
$res = $db->update("orders",$data);
if (!$res) {
$output = json_encode(array('type'=>'error', 'text' => 'fail'));
die($output);
} else {
$output = json_encode(array('type'=>'message', 'text' => 'Done.'));
die($output);
}
}

Related

Submitted chat not posting and retrieving chat not working

I using the below php chat script to create chat section between two users on my web app. I am having a problem with the Ajax posting. When a user submits a chat it doesn't post or show in the chat window. I tried to inspect the error and this is the error message
Failed to load resource: the server responded with a status of 404 (Not Found)
The same error message is shown for submit.php and refresh.php.
Here's my code:
JS
//CHAT FUNCTION
var lastTimeID = 0;
$(document).ready(function() {
$('#btnSend').click( function() {
sendChatText();
$('#chatInput').val("");
});
startChat();
});
function startChat(){
setInterval( function() { getChatText(); }, 2000);
}
function getChatText() {
$.ajax({
type: "GET",
url: "refresh.php?lastTimeID=" + lastTimeID
}).done( function( data )
{
var jsonData = JSON.parse(data);
var jsonLength = jsonData.results.length;
var html = "";
for (var i = 0; i < jsonLength; i++) {
var result = jsonData.results[i];
html += '<div style="color:#' + result.color + '">(' + result.chattime + ') <b>' + result.usrname +'</b>: ' + result.chattext + '</div>';
lastTimeID = result.id;
}
$('#view_ajax').append(html);
});
}
function sendChatText(){
var chatInput = $('#chatInput').val();
if(chatInput != ""){
$.ajax({
type: "GET",
url: "submit.php?chattext=" + encodeURIComponent( chatInput )
});
}
}
chatClass.php
<?PHP
class chatClass
{
public static function getRestChatLines($id)
{
$arr = array();
$jsonData = '{"results":[';
$statement = $db->prepare( "SELECT id, usrname, color, chattext, chattime FROM chat WHERE id > ? and chattime >= DATE_SUB(NOW(), INTERVAL 1 HOUR)");
$statement->bind_param( 'i', $id);
$statement->execute();
$statement->bind_result( $id, $usrname, $color, $chattext, $chattime);
$line = new stdClass;
while ($statement->fetch()) {
$line->id = $id;
$line->usrname = $usrname;
$line->color = $color;
$line->chattext = $chattext;
$line->chattime = date('H:i:s', strtotime($chattime));
$arr[] = json_encode($line);
}
$statement->close();
$jsonData .= implode(",", $arr);
$jsonData .= ']}';
return $jsonData;
}
public static function setChatLines( $chattext, $usrname, $color) {
$statement = $db->prepare( "INSERT INTO chat( usrname, color, chattext) VALUES(?, ?, ?)");
$statement->bind_param( 'sss', $usrname, $color, $chattext);
$statement->execute();
$statement->close();
}
}
?>
submit.php
<?php
require_once( "chatClass.php" );
$chattext = htmlspecialchars( $_GET['chattext'] );
chatClass::setChatLines( $chattext, $_SESSION['usrname'], $_SESSION['color']);
?>
refresh.php
<?php
require_once( "chatClass.php" );
$id = intval( $_GET[ 'lastTimeID' ] );
$jsonData = chatClass::getRestChatLines( $id );
print $jsonData;
?>

show only one value from ajax return array

How can I display only one thing from the array. Now it shows the whole array but I only want to show the reason from the array. because the rest is't really important. I have added index.php to show what I do there. I would like that it only showed the reason from data.
test.js
$(document).ready(function() {
var date = "";
var begin = "";
var tijdsduur = "";
var aantal = "";
$('#datum').change(function() {
date = $("#datum").val();
console.log(date);
});
$('#beginTijd').change(function() {
begin = ($(this).val());
console.log(begin);
});
$('#Tijdsduur').change(function() {
tijdsduur = ($(this).val());
console.log(tijdsduur);
});
$('#aantalSloepen').change(function() {
aantal = ($(this).val());
console.log(aantal);
$.ajax({
type: "POST",
url: "index.php",
data: {
date: date,
begin: begin,
eind: tijdsduur,
quantity: aantal
},
success: function(data) {
$('#testajax').html(data);
console.log(data);
}
});
});
});
index.php
<?php
$date = "";
$begin = "";
$tijdsduur = "";
$aantal = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {
if (isset($_POST['date'])) {
print_r($_POST);
// echo "Yes, mail is set";
$date = $_POST['date'];
$begin = $_POST['begin'];
$tijdsduur = $_POST['eind'];
$aantal = $_POST['quantity'];
$eind = $begin + $tijdsduur;
$startTijd = "$date " . $begin;
$eindTijd = "$date " . $eind . ":00";
// echo $date . "<br>";
// echo "$startTijd". "<br>";
// echo "$eindTijd". "<br>";
// echo $aantal. "<br>";
$canmakereservation = "https://www.planyo.com/rest/?method=can_make_reservation&api_key=YOURKEY&resource_id=110556&start_time=$startTijd&end_time=$eindTijd&quantity=$aantal";
$cleancanmakereservation = preg_replace("/ /", "%20", $canmakereservation);
$reservationavailable = file_get_contents("$cleancanmakereservation");
$reservationAvailable = json_decode($reservationavailable, true);
// echo "$cleancanmakereservation";
echo json_encode($reservationAvailable);
}
else {
echo "No, mail is not set";
}
exit;
}
?>
console.log
Set the dataType: 'json' in ajax request like
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$.ajax({
type: "POST",
url: "indextest.php",
dataType: 'json',
data: {
date: '',
begin: '',
eind: '',
quantity: ''
},
success: function(data) {
console.log(data.date);
}
});
</script>
and in php
<?php
$data = array('date' => '10-10-2010','date2' => '10-10-2010');
echo json_encode($data);
?>

only show some data of array on ajax return

Is there a way to only show [reason] from the array and not everything inside data? somebody said that I need to use JSON but I tried contentType: "application/json" with stringify() but then success: function(data) returns my whole HTML instead of the array.
My question is how can I show only [reason] in $('#testajax').html(data); instead of everything inside data?
console.log
script.js
$(document).ready(function(){
var date = "";
var begin = "";
var tijdsduur = "";
var aantal = "";
$('#datum').change(function() {
date = $("#datum").val();
console.log(date);
});
$('#beginTijd').change(function(){
begin =( $(this).val() );
console.log(begin);
});
$('#Tijdsduur').change(function(){
tijdsduur =( $(this).val() );
console.log(tijdsduur);
});
$('#aantalSloepen').change(function() {
aantal = ($(this).val());
console.log(aantal);
$.ajax({
type: "POST",
url: "index.php",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
data: {
date: date,
begin: begin,
eind: tijdsduur,
quantity: aantal
},
success: function(data) {
$('#testajax').html(data);
console.log(data);
}
});
});
});
UPDATED index.php
<?php
$date = "";
$begin = "";
$tijdsduur = "";
$aantal = "";
if (isset($_POST['date']) && isset($_POST['quantity'])) {
if (isset($_POST['date'])) {
print_r($_POST);
echo "Yes, mail is set";
$date = $_POST['date'];
$begin = $_POST['begin'];
$tijdsduur = $_POST['eind'];
$aantal = $_POST['quantity'];
$eind = $begin + $tijdsduur;
$startTijd = "$date " . $begin;
$eindTijd = "$date " . $eind . ":00";
echo $date . "<br>";
echo "$startTijd". "<br>";
echo "$eindTijd". "<br>";
echo $aantal. "<br>";
$canmakereservation = "https://www.planyo.com/rest/?method=can_make_reservation&api_key=YOURKEY&resource_id=110556&start_time=$startTijd&end_time=$eindTijd&quantity=$aantal";
$cleancanmakereservation = preg_replace("/ /", "%20", $canmakereservation);
$reservationavailable = file_get_contents("$cleancanmakereservation");
$reservationAvailable = json_decode($reservationavailable, true);
echo "$cleancanmakereservation";
echo json_encode($reservationAvailable);
}
else {
echo "No, mail is not set";
}
exit;
}
?>
console.log(date[0].reason);
console.log(date);
Return data in json_encode from your index.php
Then in your ajax success function just get it by
success: function(data) {
console.log(data.reason); //if its comming then add it to your html.
$('#testajax').html(data.reason);
}

why can't I pass the data as json using Ajax and Jquery to the php side?

function delete_user(email)
{
//if(confirm("Do you want to remove this user with mail id: "+email))
//{
var z = {email : email}
console.log(z)
$.ajax({
url: "delete_user.php",
type: 'POST',
data: z,
success: function (data) {
console.log(data);
return false;
var i=0;
var element = "<table style='border-collapse: collapse;'>"
while(data[i] != null)
{
element = element + "<tr style='height:15px' onmouseover='rowbig(this)' onmouseout='rowsmall(this)'><td>"+data[i].fname+"&nbsp"+data[i].lname+"</td><td>"+data[i].email+"</td><td>"+data[i].dob+"</td><td><button onclick='delete_user(\""+data[i].email+"\")'><img src='delete.png' style='height:20px;width:20px'/></button></td></tr>";
i++;
}
element = element + "</table>";
$("#response").html( element );
},
cache: false,
contentType: false,
processData: false
});
//}
}
<?php
header("Content-Type:application/json");
$email ="";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
function deliver_res($status_message,$result)
{
header("$status_message");
$response['status_message']=$status_message;
$response['result']=$result;
$json_response=json_encode ($response);
echo $json_response;
}
$servername = 'localhost';
$username = 'root';
$password = '';
$dbname = 'webdata';
$conn = mysqli_connect($servername, $username, $password, $dbname);
if(isset($_POST['email']))
{
$email = test_input($_POST["email"]);
}
else
{
deliver_res("name not received","false");
exit();
}
$sqll="DELETE FROM admindata WHERE email='".$email."';";
$result = mysqli_query($conn,$sqll);
$return_arr = array();
$sqll="SELECT * FROM admindata ORDER BY id DESC ;";
$result = mysqli_query($conn,$sqll);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$row_array['fname'] = $row['fname'];
$row_array['lname'] = $row['lname'];
$row_array['email'] = $row['email'];
$row_array['dob'] = $row['dob'];
array_push($return_arr,$row_array);
}
echo json_encode($return_arr);
echo "\n";
mysqli_close($conn);
?>
I just can't seem to pass the data as JSON using AJAX and Jquery to the PHP side. Is there anything anything wrong with the syntax?

Access JavaScript Variable in PHP

I have problem to set the AJAX variable in use in my PHP code
When I change the value of area the following function will be called:
function find_map(){
var value1 = $("#area").val();
var value2 = $("#city").val();
$.ajax({
url :"find_my_map.php", // json datasource
type: "post", // method , by default get
dataType:"json",
data:
{
area_id:value1,
city_id:value2
},
success: function(data)
{
console.log(data);
$.each(data, function(index, element) {
alert("area_name:" + element.area_name);
alert("city_name:" + element.city_name);
var map_area_name= element.area_name;
var map_city_name= element.city_name;
$("#map_area_name").val(map_area_name);
$("#map_city_name").val(map_city_name);
});
},
error:function(data){
console.log(data);
}
});
}
find_my_map.php file
include_once("config.php");
if(isset($_POST['area_id']) && isset($_POST['city_id']))
{
$area_id = $_POST['area_id'];
$city_id = $_POST['city_id'];
$sql = "SELECT * FROM area a, city c WHERE a.city_id=c.city_id AND c.city_id='$city_id' AND a.area_id='$area_id'";
$qry = mysql_query($sql);
while($fetch = mysql_fetch_array($qry))
{
$area_name=$fetch['area_name'];
$city_name=$fetch['city_name'];
$data[]=array(
'area_name' => $area_name,
'city_name' => $city_name
);
}
$json_data = array($data);
echo json_encode($data);
}
this is my php code
<?php
echo $address ="here i want to use **map_area_name AND map_city_name**"; // Google HQ
$prepAddr = str_replace(' ','+',$address);
$geocode=file_get_contents('https://maps.google.com/maps/api/geocode/json?address='.$prepAddr.'&sensor=false');
$output= json_decode($geocode);
$area_latitude = $output->results[0]->geometry->location->lat;
$area_longitude = $output->results[0]->geometry->location->lng;
echo "<br><input type='text' name='area_latitude' id='area_latitude'value='".$area_latitude."'> <br>";
echo "<input type='text' name='area_longitude' id='area_longitude' value='".$area_longitude."'>";
?>

Categories

Resources