Sending JSON to PHP via AJAX is failing - php

I am trying to send a JSON string to a PHP file via ajax. The issue is that the variable I'm posting over is not being delivered when I use the JQUERY ajax method as shown below:
<DOCTYPE html>
<html>
<head>
<title>Assignment 4</title>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<div class="col-sm-4"></div>
<div class="col-sm-4">
<form action="json.php" method="POST">
<div class="form-group">
<label for="email">Username:</label>
<input type="text" class="form-control" id="userid" name="userid">
</div>
<div class="form-group">
<label for="pwd">Password:</label>
<input type="password" class="form-control" id="pwd" name="pwd">
</div>
<button type="submit" class="btn btn-default" id='btn' onclick="JSONstring()">Submit</button>
</form>
</div>
<div class="col-sm-4"></div>
<script>
function JSONstring() {
obj = {
username: "",
password: "",
}
obj.username = document.getElementById('userid').value;
obj.password = document.getElementById('pwd').value;
console.log(obj.username + ", " + obj.password);
var jsonObj = JSON.stringify(obj);
$.ajax({
type: 'POST',
url: 'json.php',
data: {
json: jsonObj
},
dataType: 'json'
});
}
</script>
</body>
</html>
Oddly enough when I try and AJAX the old fashioned way, I am able to get the RAW POST data that I would expect:
var jsonObj = JSON.stringify(obj);
request = new XMLHttpRequest();
request.open("POST", "json.php", true);
request.setRequestHeader("Content-type", "application/json");
request.send(obj);
My php file is simply trying to get the variable and dump it:
<?php
$directions = json_decode($_POST['json']);
var_dump($directions);
?>
Can someone please point me in the right direction?

dataType only means that you expect a JSON response.
Try using contentType instead.
$.ajax({
type: 'POST',
contentType: "application/json",
url: 'json.php',
data: {
json: jsonObj
},
dataType: 'json'
});

Related

Send $_POST and $_FILES together using AJAX data field so that PHP can grab the value?

I have the following form which has
a text field
date field
a file browser.
I am using AJAX to send the $_POST data values to another PHP file to insert into a MySQL database. But I want to move the $_FILES too.
In the $.ajax field, there is data: whereby I can assign those data to be transferred to another PHP file.
I am able to do it with the text field and date fields. How to do it for the $_FILES? My codes are as below
AJAX
<script>
$("#submit").click(function() {
var prjId = $('#prjId').val();
var updatedDate = $('#updatedDate').val();
$.ajax({
type: 'POST',
url: "process.php",
data: {prjId: prjId,updatedDate: updatedDate},
success: function(response) {('#resulting').html(response);}
});
});
</script>
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<link rel="icon" type="image/png" href="images/version-control.png">
<meta charset="utf-8">
<link href='https://fonts.googleapis.com/css?family=Raleway:400,300,700,900' rel='stylesheet' type='text/css'>
<link href='https://fonts.googleapis.com/css?family=Montserrat:400,700' rel='stylesheet' type='text/css'>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<!-- jQuery library -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!-- Latest compiled JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<link rel="stylesheet" type="text/css" href="style.css">
<body>
<body>
<div class="container" id="contactform">
<form method="post" enctype="multipart/form-data">
<div class="form-group row">
<label class="col-sm-3 col-form-label">Project ID</label>
<div class="col-sm-7"><?php if(isset($_POST['prjId'])){echo '
<input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId" value="'.$_POST['prjId'].'">';}else{echo'
<input type="text" class="form-control" placeholder="Project ID" name="prjId" id="prjId">';}?>
</div>
</div>
<div class="form-group row">
<label class="col-sm-3 col-form-label">Updated Date</label>
<div class="col-sm-7"><?php if(isset($_POST['udatedDate'])){echo '
<input type="date" class="form-control" name = "updatedDate" id="updatedDate" value="'.$_POST['udatedDate'].'">';}else{echo '
<input type="date" class="form-control" name = "updatedDate" id="updatedDate">';}?>
</div>
</div>
<fieldset class="form-group ">
<label class="btn btn-default tempPerm" id="techLabelText">
<input class="tempPerm" style="" type="file" name="file" id="techInputBoxValue" />
</label>
</fieldset>
</form>
<div class="cover">
<div id="result"></div>
<input name="submit" id="submit" tabindex="5" value="Send Mail" type="submit" style="width:200px;">
</div>
</div>
</body>
</html>
PHP
<?php include ("../db.php");?>
<?php
$prjId = $_POST['prjId'];
$updatedDate = $_POST['updatedDate'];
if(isset($prjId)){
$sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
mysqli_query($conn, $sql);
}
?>
The code below automatically includes all fields from the form without manually adding them using the append function.
Also added $(document).ready(function() for fail safe. So the javascript code only takes effect when the whole document is ready.
You can try tinker with these working template.
<script>
$(document).ready(function() {
$("#submit").click(function() {
var FD = new FormData($('form')[0]);
$.ajax({
type: 'POST',
url: "process.php",
processData: false,
contentType: false,
data: FD,
success: function(response) {
$('#resulting').html(response);
}
});
});
});
</script>
process.php
<?php include ("../db.php");?>
<?php
$prjId = $_POST['prjId'];
$updatedDate = $_POST['updatedDate'];
if(isset($_POST['prjId'])){
$target_dir = "uploads/";
$target_file = $target_dir.basename($_FILES["file"]["name"]);
$save_file = basename($target_file); // this holds the filename to save.
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
$is_uploaded = move_uploaded_file($_FILES["file"]["tmp_name"], $target_file));
// Modify this query string to add the file uploaded as well.
// Change the query string to use prepared statements for failure safe and for security reasons.
$sql="INSERT INTO tbl_uploads(prjId, date) VALUES('$prjId','$updatedDate')";
mysqli_query($conn, $sql);
}
?>
^ Added a simple file upload handler.
You can use formdata to send your files along with your request like this:
<script >
$("#submit").click(function() {
var formData = new FormData();
var prjid = $('#prjId').val();
var updatedDate = $('#updatedDate').val();
formData.append( 'file', input.files[0]);
formData.append('prjId', prjid);
formData.append('updatedDate', updatedDate);
$.ajax({
type: 'POST',
url: "process.php",
data: formData,
contentType: false,
cache: false,
processData:false,
success: function(response) {
$('#resulting').html(response);
}
});
});
</script>
If you submit form using ajax it will not pass $_FILES
you have to create object for that using FormData
note : please add enctype="multipart/form-data in form tag
<form id="upload" enctype="multipart/form-data">
please refer : jQuery AJAX file upload PHP
Thanks

Internal Server error during file uploading in laravel5.3

I am trying to upload a file in laravel.But every time i hit the submit button it gives me the internal server error in the console. I have checked the rote with a get request to check if the controller function is working properly and it works fine. Can any say what is the problem?
here is my code samples
route code
Route::post('/storefile','PublicationController#storeFile');
controller
public function storeFile(Request $request){
if($request->ajax()){
echo "got";
}
else echo "not ajax";
}
view
#extends('layouts.app')
#section('stylesheet')
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet" type="text/css" />
<link type="text/css" href="/css/bootstrap-tagging.css" rel="stylesheet">
#endsection
#section('content')
<div class="validation-system">
<div class="validation-form">
<form id="test-form" action="/storepublication" method="post" enctype="multipart/form-data" >
{!! csrf_field() !!}
<div class="col-md-3 form-group1">
<label class="control-label">Upload Paper</label>
<input type="file" name="file" id="paper">
</div>
<div class="col-md-3 form-group1">
<input type="submit" id="submit" name="submit" class="btn btn-primary" value="Add">
</div>
</form>
</div>
</div>
#endsection
#section('scripts')
<script>
$(document).ready(function() {
$("#test-form").submit(function (event) {
event.preventDefault();
var file_data = $('#paper').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
$.ajax({
url: "/storefile",
type: "post",
data: form_data,
processData: false,
contentType: false,
success: function (res) {
document.getElementById("response").innerHTML = res;
}
});
});
});
</script>
#endsection
Try to replace this
var file_data = $('#paper').prop('files')[0];
by this
var file_data = $('#paper').files[0];

Jquery pass value to radio button

I used jquery ajax code to run search function.
here's my ajax so far :
$('button[type="search"]').click(function(e) {
$.ajax({
url: "{{ route('fine.search') }}",
type: "POST",
data: {
'_token' : '{{csrf_token() }}',
'driver_id' : $('select[name="driver_id"]').val(),
'fine_date' : $('input[name="fine_date"]').val(),
},
success: function(data) {
if(data.status == true) {
var result= $('#search-result');
$.each(data.getCarbyDriver, function(i, data) {
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'});
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
});
$('#search-result').append(PlateEle, StartEle, EndEle);
}
},
error: function(data) {
}
});
});
and the data being returned like this on my network (inpect element) :
car_id:5
driver_id:1
end_time:"2016-11-16 18:00:00"
plate_no:"DFE82846J"
start_time:"2016-11-16 08:00:00"
working_date:"2016-11-16 00:00:00"
here's the form blade code so far :
<div class="row top">
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label class="control-label">Driver Name:</label>
{!! Form::select('driver_id', $driver, null, array('class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group">
<label>Fine Date:</label>
{!! Form::text('fine_date', null, array('id' => 'datetimepicker', 'class' => 'form-control')) !!}
</div>
</div>
<div class="col-xs-4 col-sm-4 col-md-4">
<div class="form-group filter-btn">
<button class='btn btn-info' type='search'>Search</button>
</div>
</div>
</div>
<div class="row mid ">
<div class="col-xs-4 col-sm-4 col-md-4">
<div id="search-result"></div>
</div>
</div>
the issue is I can't save. it throws error car_id' cannot be null'.
how do i pass car_id into my radio, so once i clicked on radio button it save car_id by plate_no
im using laravel 5.3
It's unclear to me where you have PlateEle, StartEle and EndEle defined. Are those global vars defined elsewhere in your javascript?
Either way, as I understand it, car_id is being returned by the ajax POST, so it's in the data var returned to your success function?
If you want to set the value in the radio element you're creating dynamically I think it would be this:
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'}).val(data.car_id);
Here is an example I mocked up. I am creating a data object like what I believe you're saying is being returned. When I load this page I get a radio input created. Does this work for you?
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var result= $('#search-result');
//mocking up what I assume your data object looks like
var data = {};
data.car_id=5;
data.driver_id=1;
data.end_time="2016-11-16 18:00:00";
data.plate_no="DFE82846J";
data.start_time="2016-11-16 08:00:00";
data.working_date="2016-11-16 00:00:00";
PlateEle = $('<input/>').attr({ type: 'radio', name:'rad'}).val(data.car_id);
console.log(PlateEle);
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
$('#search-result').append(PlateEle, StartEle, EndEle);
});
</script>
</head>
<body>
<div id="search-result"></div>
</body>
</html>
To save the value on your input radio this could should make the trick:
$.ajax({
url: "{{ route('fine.search') }}",
type: "POST",
data: {
'_token' : '{{csrf_token() }}',
'driver_id' : $('select[name="driver_id"]').val(),
'fine_date' : $('input[name="fine_date"]').val(),
},
success: function(data) {
if(data.status == true) {
var result= $('#search-result');
$.each(data.getCarbyDriver, function(i, data) {
PlateEle = $('<input type="radio" name="rad" val="'+data.car_id+'">'+data.car_id+'</input>');
$("#search-result").html(data.plate_no);
StartEle = $('<div />').html(data.start_time);
EndEle = $('<div />').html(data.end_time);
});
$('#search-result').append(PlateEle, StartEle, EndEle);
}
},
error: function(data) {
}
});
Well, adding or changing value of radio buttons is simple. For your ID in database you could also use some data-* attribute on your radio button. But remember, data-* on your form elements will not be sent to the server, if the form is submitted in browser. For more details see my working code example below:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Test Radio Button</title>
<script type="text/javascript" src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
var $rdBtn = null;
var $txtReader = null;
var $txtRdBtnValueReader = null;
function doReady() {
$rdBtn = $("#myRdBtn");
$txtReader = $("#txtDataReader");
$txtRdBtnValueReader = $("#txtRdBtnValueReader");
$("#btnSetValue")
.click(function () {
// note the jQuery .val("some text") issue at this point. You will need .attr("value") for setting
// .val() is just helpful for reading the current value!
$rdBtn.attr("value", "my new value");
$txtRdBtnValueReader.attr("value", $rdBtn.val());
});
$("#btnSetDataValue")
.click(function () {
$rdBtn.data("mykey", "myval");
$txtReader.attr("value", $rdBtn.data("mykey"));
});
}
$(document).ready(doReady);
</script>
</head>
<body>
<button type="button" id="btnSetValue">set Value</button>
<button type="button" id="btnSetDataValue">set data-* value</button>
<div id="myRadioButtonWrapper">
<label for="myRdBtn">your value choice</label>
<input type="radio" id="myRdBtn" name="myRdBtn" value="to be replaced" />
<br />
<label for="txtRdBtnValueReader">radio value</label>
<input type="text" id="txtRdBtnValueReader" name="txtRdBtnValueReader" readonly />
<br />
<label for="txtDataReader">data-mykey value</label>
<input type="text" id="txtDataReader" name="txtDataReader" readonly />
</div>
</body>
</html>
It is also a common way if you need more data assigned to an input field to serialize its value as json. So, that you could have a whole object sent to the server. It's easy to parse again in PHP. Maybe this could help you, too. Good luck!

how to asynchronously get data using ajax and php

i am new in ajax. i want to display the text entered inside the input to another div element.here is the image given below:
here is my code :
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<script >
/* Get from elements values */
var values = $(this).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async:true,
data: values ,
success: function (response) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
</script>
</body>
</html>
here is php code:
<?php
$bar = $_POST['bar']
?>
please help me to fix the problem & also minimize the code if possible.thanks
Client-side
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form>
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" value="Go">
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<!-- For testing purposes comes here the JSON object (stringified) -->
<div id="jsonstring" style="font-family:monospace;">Json object</div>
<script type="text/javascript">
var values = $("form").serialize();
$("form").on("submit", function( event ) {
event.preventDefault();
var values = $( this ).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async: true,
data: values,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
success: function(json) {
$('#result').html((json.content) ? (json.content) : '???');
$('#result').prop('title', json.title);
$('#jsonstring').html('Json object: '+JSON.stringify(json));
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
</script>
</body>
</html>
Server-side
<?php
$bar = (isset($_POST['bar'])) ? $_POST['bar'] : '';
$result = array(
'title' => 'This is the result from an AJAX call',
'content' => 'This is the result: <span style="color:red;">' . $bar . '</span>',
);
echo json_encode($result);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<form name="form">
<label for="bar">Enter Text</label>
<input id="bar" name="bar" type="text" value="" />
<input type="submit" id="submit" value="click" >
</form>
<!-- The result of the search will be rendered inside this div -->
<div id="result">Text Output: </div>
<script >
/* Get from elements values */
$("#submit").on("click", function(){
var values = $(this).serialize();
$.ajax({
url: "testajax.php",
type: "post",
async:true,
data: values ,
success: function (response) {
$('#result').html((response);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log(textStatus, errorThrown);
}
});
});
</script>
</body>
</html>

Ajax/PHP login form - developing an android app(Jquery.mobile) using phonegap

My Index.html file code as follows:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Mindcorpus - Placement</title>
<link href="style.css" rel="stylesheet" type="text/css"/>
<script src="jquery.js" type="text/javascript"></script>
<script src="jquery-mobile.js" type="text/javascript"></script>
<script src="/cordova.js" type="text/javascript"></script>
<script>
$(function()
{
$('#frm').submit(function()
{
var username = $('#textinput').val();
var username = $.trim(username);
var password = $('#passwordinput').val();
var password = $.trim(password);
if(username=='')
{
$('.error').html('Please enter username');
return false;
}
else if(password =='')
{
$('.error').html('Please enter password');
return false;
}
else
{
var user = $('[name=username]').val();
var pass = $('[name=password]').val();
$.ajax({
type: 'POST',
url: 'http://localhost/mc-new/admin/mobile1/process.php',
data: { username: user, password: pass},
success: function(data){
alert(data.success);
},
error: function(){
alert('error!');
}
});
return false;
}
});
});
</script>
</head>
<body>
<div data-role="page" id="page">
<div data-role="header">
<h1><img src="images/logo.png" /></h1>
</div>
<div data-role="content">
<div class="error"></div>
<form action="" method="post" id="frm">
<div data-role="fieldcontain">
<input type="text" name="username" placeholder="Username" id="textinput" value="" />
</div>
<div data-role="fieldcontain">
<input type="password" name="password" placeholder="******" id="passwordinput" value="" />
</div>
<button data-icon="arrow-r" type="submit">Submit</button>
</form>
</div>
<div data-role="footer">
<h4 style="font-weight:normal">Powered By: Mind Processors</h4>
</div>
</div>
</body>
</html>
And my process.php file is:
<?php
if(isset($_POST['username']) || isset($_POST['password']))
{
$data['success'] = 'Done';
echo json_encode($data);
}
?>
This functions is properly working when I use localhost on my browser. BUt when I use Dreamweaver and build & Emulate this site. It always alert error. The Ajax is not functioning in emulator. The request is not passed to process file. Please help me & sort out this problem.
You need to specify in the ajax that the expected return data type is JSON and also cross domain has to be enabled.
Try the below code for the ajax,
$.ajax({
type: 'POST',
url: 'http://localhost/mc-new/admin/mobile1/process.php',
crossDomain: true,
data: { username: user, password: pass},
dataType: 'json',
success: function(data){
alert(data.success);
},
error: function(){
alert('error!');
}
And also add the following in your php file,
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Max-Age: 1000');
header('Content-Type: application/json');
if(isset($_POST['username']) || isset($_POST['password']))
{
$data['success'] = 'Done';
echo json_encode($data);
}
?>
Hope this helps to someone who falls onto this question, looking for an answer.

Categories