I am posting form data from create.php as below using $.ajax.
$(document).ready(function () {
var request;
$("#create-pto").submit(function(e) {
// Abort any pending request
if (request) {
request.abort();
}
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: 'index.php',
type: 'POST',
contentType : 'application/json',
data: serializedData
}).done(function (response, textStatus, jqXHR) {
// Log a message to the console
console.log("Hooray, it worked!");
});
e.preventDefault();
});
});
I can see the posted data and i can log post success.
But in index.php could not retrieve posted data.
This is what i am trying in index.php
var_dump($_POST);
Form :
<form class="form-horizontal" id="create-pto" >
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control- label">App ID</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="app-id" id="app-id" placeholder="App ID">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">App Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="app-name" id="app-name"
placeholder="App Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Instance Name</label>
<div class="col-sm-4">
<input type="text" class="form-control" id="inputPassword3" name="ins-name"
placeholder="Instance Name">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="create" class="btn btn-success">Create PTO</button>
</div>
</div>
</form>
Pls help.
Try changing the contentType on your JavaScript code:
contentType : 'application/x-www-form-urlencoded',
And if you want to keep the contentType to json, try this way on your PHP file:
echo file_get_contents('php://input');
If you use .serialize() you need to change contentType to 'application/x-www-form-urlencoded'.
If you want to keep contentType: 'application/json' you have to use JSON.stringify instead.
Also note that JSON strings in POST requests are retreived using file_get_contents('php://input'); not $_POST
Change your
contentType : 'application/json'
to
dataType: "JSON"
It will start work.. I tested code on my system.
try type:GET instead of type:POST,also call var_dump($_GET) in index.php
Related
I'm trying to update a file using a PUT method with ajax. For whatever reason I can't send a request in my controller. I created a custom validator to check whether a file is missing or a certain input request is missing. It keeps on returning 422 file is missing and name is missing. What do I miss? Here's my code below.
<script>
$(document).ready(function() {
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#news_id').on('submit', function(e) {
e.preventDefault();
var data = new FormData();
var newsletter_name = $('#newsletter_name').val();
var newsletter_file = $('#newsletter_file')[0].files[0];
data.append('newsletter_name', newsletter_name);
data.append('newsletter_file', newsletter_file);
var id = $('#hidden_id').val();
console.log(newsletter_file);
$.ajax({
url: '/admin/newsletter/' + id,
type: 'PUT',
data: data,
contentType: false,
processData: false,
beforeSend: function(data) {
},
success: function(data) {
console.log('success');
},
error: function(data) {
console.log(data)
},
});
});
});
</script>
Here's my html code
<div class="container mt-5">
<div class="col-md-6">
<form action="" method="" enctype="multipart/form-data" id="news_id">
#method('PUT')
<div class="form-group">
<label for="newsletter_name">Name</label>
<input type="text" value="{{$newsletter->newsletter_name}}" name="newsletter_name" id="newsletter_name" class="form-control" placeholder="" aria-describedby="helpId">
<input type="hidden" name="hidden_id" id="hidden_id" value="{{$newsletter->newsletter_id}}">
<input type="hidden" name="_method" value="PUT">
</div>
<div class="input-group mb-3">
<div class="custom-file">
<input name="newsletter_file" type="file" class="custom-file-input" id="newsletter_file" aria-describedby="inputGroupFileAddon03">
<label class="custom-file-label" for="newsletter_file">Choose file</label>
</div>
</div>
<div>
<button class="btn btn-primary btn-block" type="submit">UPDATE</button>
</div>
</form>
</div>
</div>
Add data.append('_method', 'PUT'); then change your request type to type: 'POST'
Because some browser can't send a PUT request, so Laravel can do receive a PUT request by receiving _method data.
I want to post edit form data to codeigniter controller using angularjs
this is my angularjs controller where i collect and post form data
$scope.editlist = function(id){
$http({
method:'post',
url:'http://localhost/Angular_demo/admin/index.php/welcome/get_edit_data/'+
id
}).then(function success(response){
$scope.sid = parseInt(response.data[0]['id']);
$scope.firstname = response.data[0]["first_name"];
$scope.lastname = response.data[0]['last_name'];
$scope.email = response.data[0]['email'];
});
}
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:'id='+ id + '&first_name='+firstname+
'&last_name='+lastname+'&email='+email,
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
My view where i bind and post form data
<form name="editItem" class="form-horizontal">
<input ng-model="sid" type="hidden" placeholder="Name" name="name"
class="form-control" />
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">First
Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="firstname"
id="inputEmail3" placeholder="First name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">Last
Name</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="lastname"
id="inputEmail3" placeholder="Last Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-
label">Email</label>
<div class="col-sm-10">
<input type="text" class="form-control" ng-model="email"
id="inputEmail3" placeholder="Email">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="button" class="btn btn-default" data-
dismiss="modal">Close</button>
<button type="submit" ng-disabled="editdata.$invalid"
class="btn btn-primary create-crud" data-dismiss="modal" ng-
click="saveEdit(sid,firstname,lastname,email)">Submit</button>
</div>
</div>
</form>
This is my codeigniter controller where i want to get form data
public function update_data(){
$requests = json_decode(file_get_contents('php://input'), TRUE);
$ids= array('id' =>$requests['id']);
echo json_encode($ids);
}
When i submit my form data will show null in my controller,so please help how to get form data in controller.
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:'id='+ id + '&first_name='+firstname+
'&last_name='+lastname+'&email='+email,
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
This should be like this:-
$scope.saveEdit = function(id,firstname,lastname,email){
$http({
method:'post',
data:{"id": id,"first_name":firstname,
"last_name":lastname,"email":email}
url:'http://localhost/Angular_demo/admin/index.php/welcome/update_data'
}).then(function success(response){
console.log(response.data);
});
}
Since the codeigniter code uses json_decode, the $http service should use a JavaScript object to post the data:
$scope.saveEdit = function(id,firstname,lastname,email) {
var url = 'http://localhost/Angular_demo/admin/index.php/welcome/update_data';
var data = {
id: id,
first_name: firstname,
last_name: lastname,
email: email,
};
$http.post(url, data
).then(function success(response){
console.log(response.data);
});
}
The AngularJS framework will automatically encode the JavaScript object as a JSON string.
I am trying to create a form for submitting resume.
I need the candidate name, email , resume cover and the resume(file).
var candidateName = $('#candidateName').val();
var candidateEmail = $('#candidateEmail').val();
var candidateMessage = $('#candidateMessage').val();
var file_data = $('#candidateResume').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', candidateName);
form_data.append('id', candidateEmail);
form_data.append('msg', candidateMessage);
console.log(form_data);
$.ajax({
url: "cvForm.php",
type: "POST",
data: {candata: form_data},
success : function(data){
console.log(data);
},
contentType: false,
processData: false
});
nothing is being returned in my cvForm.php file when I
var_dump($_POST) or
var_dump($_FILES)
when I
var_dump($_POST['candata']) - it says undefined index
The HTML
<form id="cvSubmit" class="mui-form">
<div>
<span class="form-success-msg" id="cv-form-success-msg">
Thanks for reaching out to us. We will get back to you shortly.
</span>
</div>
<div class="row">
<div class="col-sm-6">
<div class="mui-textfield mui-textfield--float-label">
<input type="text" id="candidateName" class="mui--is-empty mui--is-untouched mui--is-pristine">
<label>Name<span class="red-text">*</span></label>
<span class="error" id="cv-name-error">Please enter your name</span>
</div>
<div class="mui-textfield mui-textfield--float-label">
<input type="email" id="candidateEmail" class="mui--is-empty mui--is-untouched mui--is-pristine">
<label>Email<span class="red-text">*</span></label>
<span class="error" id="cv-email-error">Oops!! Looks like its an incorrect email id. Try again</span>
</div>
<div class="row">
<div class="col-xs-12 file-attachment-wrapper">
<input class="file-addach" type="file" id="candidateResume">
<span>We accept .DOCX,.Doc,pdf,.Txt upto 2 MB.</span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="mui-textfield mui-textfield--float-label">
<label>Message<span class="red-text">*</span></label><br><br>
<textarea id="candidateMessage" rows="5" class="mui--is-empty mui--is-untouched mui--is-pristine"></textarea>
<span class="error" id="cv-message-error">That's not very clear...could you rephrase</span>
</div>
<button type="button" class="mui-btn mui-btn--raised red-btn" onclick="cvSubmit()"> SEND </button>
</div>
</div>
</form>
Please help. I see this is a common question but none of the solution seems to work for me. Some code refreshes the page, which I don't want to happen.
Remove this line from your JS:
contentType: false,
That's telling jQuery to not set the content-type HTTP header. That header tells PHP how to parse the POSTed body.
Also, formdata can be sent directly:
data: form_data,
Then, in PHP, you should find for example $_POST['name'] available.
You need to pass form_data in its normal form, instead of a property of another JSON object:
$.ajax({
url: 'cvForm.php',
type: 'post',
data: form_data,
processData: false,
success : function(data){
console.log(data);
}
});
Now inside of your PHP script, you will have access to $_POST['name'], $_POST['id'] and $_POST['msg']. Similarly, $_FILES['file'] is now available too.
Try this. It might help you.
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form id="cvSubmit" class="mui-form">
<div>
<span class="form-success-msg" id="cv-form-success-msg">
Thanks for reaching out to us. We will get back to you shortly.
</span>
</div>
<div class="row">
<div class="col-sm-6">
<div class="mui-textfield mui-textfield--float-label">
<input type="text" id="candidateName" class="mui--is-empty mui--is-untouched mui--is-pristine">
<label>Name<span class="red-text">*</span></label>
<span class="error" id="cv-name-error">Please enter your name</span>
</div>
<div class="mui-textfield mui-textfield--float-label">
<input type="email" id="candidateEmail" class="mui--is-empty mui--is-untouched mui--is-pristine">
<label>Email<span class="red-text">*</span></label>
<span class="error" id="cv-email-error">Oops!! Looks like its an incorrect email id. Try again</span>
</div>
<div class="row">
<div class="col-xs-12 file-attachment-wrapper">
<input class="file-addach" type="file" id="candidateResume">
<span>We accept .DOCX,.Doc,pdf,.Txt upto 2 MB.</span>
</div>
</div>
</div>
<div class="col-sm-6">
<div class="mui-textfield mui-textfield--float-label">
<label>Message<span class="red-text">*</span></label><br><br>
<textarea id="candidateMessage" rows="5" class="mui--is-empty mui--is-untouched mui--is-pristine"></textarea>
<span class="error" id="cv-message-error">That's not very clear...could you rephrase</span>
</div>
<button type="submit" class="mui-btn mui-btn--raised red-btn"> SEND </button>
</div>
</div>
</form>
<script>
$(document).ready(function(){
$("#cvSubmit").submit(function(e) {
e.preventDefault();
var candidateName = $('#candidateName').val();
var candidateEmail = $('#candidateEmail').val();
var candidateMessage = $('#candidateMessage').val();
var file_data = $('#candidateResume').prop('files')[0];
var form_data = new FormData();
form_data.append('file', file_data);
form_data.append('name', candidateName);
form_data.append('id', candidateEmail);
form_data.append('msg', candidateMessage);
console.log(form_data);
$.ajax({
url: "cvForm.php",
type: "POST",
data: form_data,
success : function(data){
console.log(data);
},
contentType: false,
processData: false
});
});
});
</script>
</body>
</html>
After this code, I was able to see the data in console
Changes the submit button to type 'submit' and handled the event handler for form submit and e.preventDefault() prevents from page refresh.
Hope it helps!
I try to get data from ajax pass from front page to my controller but i got only string to my controller so how can i separate it one by one.
this is form:
<form class="form-horizontal form" action="<?php print base_url() ?>insertCategory" method="post" enctype='multipart/form-data'>
<div class="box-body">
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
<input type="text" name='name' required class="form-control" id="inputEmail3" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="inputEmail3" class="col-sm-2 control-label">name</label>
<div class="col-sm-10">
<input type="text" name='test' required class="form-control" id="inputEmail3" placeholder="Name">
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Category Detail</label>
<div class="col-sm-10">
<textarea id="txtEditor" ></textarea>
</div>
</div>
<div class="form-group">
<label for="inputPassword3" class="col-sm-2 control-label">Image</label>
<div class="col-sm-10">
<input type="file" name="img" required class="form-control" >
</div>
</div>
</div>
<!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-info pull-right submit">Submit</button>
</div>
<!-- /.box-footer -->
</form>
this my code ajax:
$(".submit").click(function (e) {
e.preventDefault();
var data = $('.form').serialize();
var val = $("#txtEditor").Editor("getText");
var page = "<?php echo $page ?>";
var url = "<?php echo base_url(); ?>insertCategory"
$.ajax({
type: "POST",
url: url,
data:{
"data" : data
},
success: function (data) {
console.log(data);
}
});
return false;
});
and this is my controller:
public function insertCategory()
{
if($this->session->userdata('logged_in')==1){
$data = $this->input->post('data');
var_dump($data);
and this my data respond by ajax:
C:\....\AdminController.php:308:string 'name=dsfdsfs&test=dfsdf' (length=23)
Use this instead,
var_dump($_POST);
it is posted as same as post work
For reference, use this code below.
type: "POST",
url: url,
data: $('.form').serialize(),
success: function (data) {
console.log(data);
}
Use
data: $('.form').serialize()
instead of
var data = $('.form').serialize();
data:{
"data" : data
},
At the controller the contents of your form will be available in the $_POST array. So the "name" field on your form can be accessed with $_POST['name'].
That said, you will be better off using CodeIgniter's methods to retrieve this data.
For example:
$name = $this->input->post('name');
If, for learning purposes, you wanted to see everything "posted" to the controller this will do the trick.
public function insertCategory()
{
if($this->session->userdata('logged_in')==1)
{
$posted = $this->input->post(); //get all $_POST items
var_dump($posted);
}
}
use parse_str(); that can return array after parse string
public function insertCategory()
{
if($this->session->userdata('logged_in')==1){
$data = $this->input->post('data');
parse_str($data, $parseData);
var_dump($parseData);
Ok, thats basically what i got. I also tried static values.
$('#submitForm').submit(function() {
$.ajax({
type: $(this).attr('method'),
url: $(this).attr('action'),
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
What i get as response is this:
Object {readyState: 0, responseText: "", status: 0, statusText = "error"}
The php script (just a simple echo) runs as normal after that ajax call. What am i doing wrong? My submit script doesn't look all that wrong to me and i'm not doing XSS. : - (
My HTML Form looks like this:
<form action="http://dev.xxxxxxx.de/users/register" method="post" accept-charset="utf-8" class="form-horizontal" id="submitForm"> <div class="control-group">
<label class="control-label" for="inputUsername">Nickname</label>
<div class="controls">
<input type="text" name="username" id="inputUsername" value="" placeholder="Nickname" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputEmail">E-Mail</label>
<div class="controls">
<input type="text" name="email" id="inputEmail" value="" placeholder="E-Mail" />
</div>
</div>
<div class="control-group">
<label class="control-label" for="inputPassword">Passwort</label>
<div class="controls">
<input type="password" name="password" id="inputPassword" value="" placeholder="Passwort" />
</div>
</div>
<div class="control-group">
<div class="controls">
<input type="submit" class="btn" value="Account erstellen" />
</div>
</div>
</form>
You need to tell the browser not to submit the form by default with:
e.preventDefault();
So:
$('#submitForm').submit(function(e) {
e.preventDefault();
$.ajax({
type: this.method,
url: this.action,
data: $(this).serialize(),
success: function (data) {
console.log(data);
},
error: function (data) {
console.log(data);
}
});
});
Otherwise, your form will submit according to the "action" attribute, before your AJAX returns.