Unable to pass formData with other parameters in jQuery - javascript

I am trying to pass formData along with other parameters to a PHP script.
Using the $.post method, I was getting an 'Illegal Invocation' error. So I abandoned the $.post method and went to $.ajax method.
As follows:
$('#uploadBtn').on('click', function()
{
var formData = new FormData($('#uploadfile')[0]); // the form data is uploaded file
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
var parameters =
{
formData:formData,
booking:booking,
partner:partner
}
$.ajax({
url: 'process/customer.php',
data: parameters, // <- this may be wrong
async: false,
contentType: false,
processData: false,
cache: false,
type: 'POST',
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
});
On the PHP side, I'm trying to get the parameters object like so:
<?php
if(isset($_POST['parameters']))
{
echo "Hello";
$value = $_POST['parameters'];
// I can get the other 2 parameters like this
$company = htmlspecialchars(trim($value['booking']));
$partner = htmlspecialchars(trim($value['partner']));
// not sure how to get the uploaded file information
}
?>
Basically, I am uploading a file to be saved to a directory. But the problem is, I cannot send anything over to the PHP side. I am getting this warning:
"jquery.js:2 [Deprecation] Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/."
I need to be able to send the 'parameters' object over to the PHP script, then access it for processing.
How can I achieve this using the $.ajax method? Then how do I access the formData once on the PHP side?

The parameters is the object you are POSTing. the key value pairs will be based on it's properties. Try accessing them like $_POST['formData'] and $_POST['booking'].
Also... please rework your code to remove the async:false ... TBH this should never have been put into jQuery and is absolutely terrible. Don't feel bad, it's the first thing every newcomer tries when they first start using ajax, myself included. You're going to cause the UI thread to hang for the duration, preventing all user interaction during the call.
EDIT
I didn't realize you are trying to post a file at first, so this is not a complete answer as I don't think you are accessing it correctly. But The important part of this answer is that there is no parameters index of $_POST (which is why not even your echo "hello" is coming back).
if you POST an object that looks like
{
key1 : "value1",
key2 : "value2"
}
they will come through to php as
$_POST['key1'];//"value1";
$_POST['key2'];//"value2";
important to note, files posted to the server are typically found in the $_FILES superglobal. (don't know if AJAX changes that, but I imagine not)
EDIT2
Combining the two... this is the general idea. Make your html + JS look like...
$('#form').on('submit', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('fileInput').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
form_data.append("booking ",booking);
form_data.append("partner",partner);
$.ajax({
url: 'process/customer.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
return false;//prevent default form submission
});
<form id='form'>
<input type='file' id='fileInput' />
<label for='bookingNum'>Booking Num: </label>
<input type='text' id='bookingNum' name='bookingNum' />
<label for='partnerCode'>Partner Code:</label>
<input type='text' id='partnerCode' name='partnerCode' />
<button id='uploadBtn'>Submit</button>
</form>
and try it with your php code like
<?php
if($_POST['bookingNum']){
var_dump($_POST['bookingNum']);
}
if($_POST['partnerCode']){
var_dump($_POST['partnerCode']);
}
if($_FILES['file']){
var_dump($_FILES['file']);
}

$('#uploadBtn').on('click', function()
{
var form_data = new FormData();
form_data.append("file", document.getElementById('ID').files[0]);
var booking = $('#bookingNum').val();
var partner = $('#partnerCode').val();
form_data.append("booking ",booking);
form_data.append("partner",partner);
$.ajax({
url: 'process/customer.php',
method:"POST",
data: form_data,
contentType: false,
cache: false,
processData: false,
success: function(data)
{
console.log(data);
},
error: function(jqHHR, textStatus, errorThrown)
{
console.log('fail: ' + errorThrown);
}
});
});

Related

Data is empty when passing a variable from JS to PHP with Ajax

I'm trying to pass a simple string variable with an onclick event, the request is successful but I get an empty response on the console, and the xvar variable is no coming through so I get the "NO DATA" p tag. This is my first time using Ajax so I tried to make it very simple to start. Here's my code:
JS
var xvar = 'D';
$('.test').click( () => {
$.ajax({
data: { xvar : xvar },
type: "POST",
url: 'test.php',
success: function(data, textStatus, XMLHttpRequest)
{
console.log('Success: '+data)
},
error: function(XMLHttpRequest, textStatus, errorThrown){
console.log("The request failed."+errorThrown);
}
});
});
test.PHP
$xvar = (isset($_POST['xvar'])) ? $_POST['xvar'] : '<p>NO DATA</p>';
echo $xvar;
I'm using JQuery 3.5.1 that is included with Wordpress. I'll appreciate any feedback.
EDIT
I managed to get the response on test.php as seen
here:
But I when I try to render the value with print_r is not shown.
$res = $_POST;
print_r($res);
On the data of your Ajax, try to add the quotes in the key of the data. Like this:
data: { "xvar" : xvar },

Problema sending json file from javascript to laravel controller

im having problems trying to send a JSON file from javascript to Laravel controller, when i press my button from the view i didnt get any response.
This is my code, i appreciate any help or suggestion, thnks.
This is the the JS code:
var horarios= { Lunes: arrLunes, Martes: arrMartes, Miercoles: arrMiercoles, Jueves:arrJueves, Viernes:arrViernes};
var schedule = JSON.stringify(horarios);
//console.log(schedule);
var varurl= 'http://localhost/registerEntrance';
$.ajax({
type: "POST",
url: varurl,
data: {json:schedule},
dataType:'json',
success: function(res) {
var message = res.mesg;
if (message) {
$('.flash').html(message).fadeIn(300).delay(250).fadeOut(300);
};
}
});
When i press my button, doesnt happend anything. The next id the route and the controller code, the JSON file not arrive there yet.
Route::post('registerEntrance', array('as' => 'registerEntrance','uses' => 'CursoController#regisEnt'));
public function regisEnt(){
if(Request::ajax()) {
$data = Input::all();
return $data;
}
}
Thnks for any help.
What are you using to debug your requests? Have you checked your storage/logs/framework/laravel.log (if your log is HUGE you can always delete it and re-run your request)
Working with AJAX can get tricky when it comes to debugging your requests.
My recommendation would be
Open up your browser Inspector, and monitor Network Requests
Analyze the request you're sending.
Set debug to true under config/app.php to actually see a debug
Hope this helps!
I get resolv my problem, i post it if someone is getting a similar inconvenience.
In my view i wasnt create a form.
{!! Form::open(['route' => ['route'], 'method' => 'POST', 'id' =>'form-name']) !!}
{!! Form::close() !!}
This part create a implicit token that is necesary in laravel for use ajax method.
My code JS was modified for getting and send the csrf token.
var form = $('#form-name');
var myurl = form.attr('action');
crsfToken = document.getElementsByName("_token")[0].value;
$.ajax({
url: myurl,
type: 'POST',
data: {data:data},
datatype: 'JSON',
headers: {
"X-CSRF-TOKEN": crsfToken
},
success: function(text){
bootbox.dialog({
closeButton: false,
message: "Ok!",
title: "Perfect!!",
},
error: function(data){
console.log("Error");
}
});
With this change i get arrive to my controller.
Anyway Thnks.

Django + Ajax | File Upload | Server doesn't recognise Ajax Request

I am trying to implement file upload using ajax with Django but facing some problem.
When the user tries to upload the files after selecting the file and submitting the form, then as per my understanding , an ajax request should be send to the server using POST method ,but in my case a POST request is being made to the server, but the server is not able to identify it as an ajax request and browser is redirected to http://<server>:<port>/upload/ and the contents on this page are as follows.
{"status": "error", "result": "Something went wrong.Try Again !!"}
Django Version: 1.6.2
Python Version: 2.7.5
Also, testing on Django Development Server.
views.py
def upload(request):
logging.info('Inside upload view')
response_data = {}
if request.is_ajax():
logging.info('Is_AJAX() returned True')
form = UploaderForm(request.POST, request.FILES)
if form.is_valid():
logging.info('Uploaded Data Validated')
upload = Upload( upload=request.FILES['upload'] )
upload.name = request.FILES['upload'].name
upload.save()
logging.info('Uploaded Data Saved in Database and link is %s' % upload.upload)
response_data['status'] = "success"
response_data['result'] = "Your file has been uploaded !!"
response_data['fileLink'] = "/%s" % upload.upload
return HttpResponse(json.dumps(response_data), content_type="application/json")
response_data['status'] = "error"
response_data['result'] = "Something went wrong.Try Again !!"
return HttpResponse(json.dumps(response_data), content_type='application/json')
Template
<form id="uploadForm" action="/upload/" method="post" enctype="multipart/form-data">
{% csrf_token %}
<input id="fileInput" class="input-file" name="upload" type="file">
<input type="submit" value="Post Images/Files" />
</form>
Javascript 1:
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
Javascript 2
var options = {
url: '/upload/',
type: "POST",
error: function(response) {
alert('Something went Wrong. Try Again');
},
success: function(response) {
if ( response.status == 'success' ) {
alert('success');
}
}
};
$('#uploadForm').ajaxSubmit(options);
Question:
1) Why is Django not able to recognize the ajax request and value of request.is_ajax() is always False.
2) Even if the server doesn't recognize ajax request why is my browser getting redirected to another page ?
There is another similar question here but with no result.
This works for me. You need a jquery.form.js
$("#uploadForm").submit(function(event) {
$(this).ajaxSubmit({
url:'{% url upload_file %}',
type: 'post',
success: function(data) {
console.log(data)
},
error: function(jqXHR, exception) {
console.log("An error occurred while uploading your file!");
}
});
return false;
});
Here's the similar question here with answers.
Make sure that javascript code block
$('#uploadForm').submit(function(){
var formData = new FormData($(this)[0]);
$.ajax({
url: '/upload/',
type: 'POST',
data: formData,
async: false,
success: function (data) {
alert(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
loaded after your uploadForm html form in DOM on page. In your case seems you trying to bind submit handler with form element which not yet loaded so when you click, it send simple POST request.
1) why is_ajax() not working?
Have you included the JQuery form plugin (jquery.form.js) ? ajaxSubmit() needs that plugin.
Take a look at http://jquery.malsup.com/form/
If it's already done, you might take a look at the HTTPRequest object
Django Documentation says HttpRequest.is_ajax()
Returns True if the request was made via an XMLHttpRequest. And if you are using some javascript libraries to make the ajax request, you dont have to bother about this matter. Still you can verify "HTTP_X_REQUESTED_WITH" header to see if Django received an XMLHttpRequest or not.
2) Why page redirects?
As I said above, JQuery form plugin is needed for handling the ajax request and its call back. Also, for ajaxSubmit() you need to override the $(#uploadForm).submit()
$('#uploadForm').submit( function (){
$(this).ajaxSubmit(options);
return false;
});
Hope this was helpful :)

cakephp 2.2 retrieve json data in controller

I'm trying to send JSON data from a web page using JQuery, like this:
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: '{username: "wiiNinja", password: "isAnub"}',
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
In cake2.2, I have a controller named Ajax that has a method named "login", like this:
public function login($id = null)
{
if ($this->RequestHandler->isAjax())
{
$this->layout = 'ajax'; // Or $this->RequestHandler->ajaxLayout, Only use for HTML
$this->autoLayout = false;
$this->autoRender = false;
$response = array('success' => false);
$data = $this->request->input(); // MY QUESTION IS WITH THIS LINE
debug($data, $showHTML = false, $showFrom = true);
}
return;
}
I just want to see if I'm passing in the correct data to the controller. If I use this line:
$data = $this->request->input();
I can see the debug printout:
{username: "wiiNinja", password: "isCool"}
I read in the CakePHP manual 2.x, under "Accessing XML or JSON data", it suggests this call to decode the data:
$data = $this->request->input('json_decode');
When I debug print $data, I get "null". What am I doing wrong? Is my data passed in from the Javascript incorrect? Or am I not calling the decode correctly?
Thanks for any suggestion.
============= My own Edit ========
Found my own mistake through experiments:
When posting through Javascript, instead of this line:
data: '{username: "wiiNinja", password: "isAnub"}',
Change it to:
data: '{"username": "wiiNinja", "password": "isAnub"}',
AND
In the controller code, change this line:
$data = $this->request->input('json_decode');
To:
$data = $this->request->input('json_decode', 'true');
It works.
Dunhamzzz,
When I followed your suggestions, and examine the "$this->request->params" array in my controller code, it contains the following:
array(
'plugin' => null,
'controller' => 'ajax',
'action' => 'login',
'named' => array(),
'pass' => array(),
'isAjax' => true
)
As you can see, the data that I'm looking for is not there. I've already got the the proper routes code. This is consistent with what the documentation for 2.x says here:
http://book.cakephp.org/2.0/en/controllers/request-response.html
So far, the only way that I found to make it work, is as stated above in "My own Edit". But if sending a JSon string to the server is not the right thing to do, I would like to fix this, because eventually, I will have to handle third party code that will send JSon objects.
The reason you are struggling wit the data is because you are sending a string with jQuery, not a proper javascript object (JSON).
$.ajax({
type: "post", // Request method: post, get
url: "http://localhost/ajax/login",
data: {username: "wiiNinja", password: "isAnub"}, // outer quotes removed
dataType: "json", // Expected response type
contentType: "application/json",
cache: false,
success: function(response, status) {
alert ("Success");
},
error: function(response, status) {
alert('Error! response=' + response + " status=" + status);
}
});
Now the data will be available as a PHP array in $this->request->params.
Also for sending a JSON response, please see this manual page. Most of your code there can be reduced to just 2 lines...
//routes.php
Router::parseExtensions('json');
//Controller that sends JSON
$this->set('_serialize', array('data'));

JQuery $.ajax() post - data in a java servlet

I want to send data to a java servlet for processing. The data will have a variable length and be in key/value pairs:
{ A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
The data doesn't need to be formated this way, it is just how I have it now.
var saveData = $.ajax({
type: "POST",
url: "someaction.do?action=saveData",
data: myDataVar.toString(),
dataType: "text",
success: function(resultData){
alert("Save Complete");
}
});
saveData.error(function() { alert("Something went wrong"); });
The $.ajax() function works fine as I do get an alert for "Save Complete". My dilemna is on the servlet. How do I retrieve the data? I tried to use a HashMap like this...
HashMap hm = new HashMap();
hm.putAll(request.getParameterMap());
...but hm turns out to be null which I am guessing means the .getParameterMap() isn't finding the key/value pairs. Where am I going wrong or what am I missing?
You don't want a string, you really want a JS map of key value pairs. E.g., change:
data: myDataVar.toString(),
with:
var myKeyVals = { A1984 : 1, A9873 : 5, A1674 : 2, A8724 : 1, A3574 : 3, A1165 : 5 }
var saveData = $.ajax({
type: 'POST',
url: "someaction.do?action=saveData",
data: myKeyVals,
dataType: "text",
success: function(resultData) { alert("Save Complete") }
});
saveData.error(function() { alert("Something went wrong"); });
jQuery understands key value pairs like that, it does NOT understand a big string. It passes it simply as a string.
UPDATE: Code fixed.
Simple method to sending data using java script and ajex call.
First right your form like this
<form id="frm_details" method="post" name="frm_details">
<input id="email" name="email" placeholder="Your Email id" type="text" />
<button class="subscribe-box__btn" type="submit">Need Assistance</button>
</form>
javascript logic target on form id #frm_details after sumbit
$(function(){
$("#frm_details").on("submit", function(event) {
event.preventDefault();
var formData = {
'email': $('input[name=email]').val() //for get email
};
console.log(formData);
$.ajax({
url: "/tsmisc/api/subscribe-newsletter",
type: "post",
data: formData,
success: function(d) {
alert(d);
}
});
});
})
General
Request URL:https://test.abc
Request Method:POST
Status Code:200
Remote Address:13.76.33.57:443
From Data
email:abc#invalid.ts
you can use ajax post as :
$.ajax({
url: "url",
type: "POST",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify({ name: 'value1', email: 'value2' }),
success: function (result) {
// when call is sucessfull
},
error: function (err) {
// check the err for error details
}
}); // ajax call closing
For the time being I am going a different route than I previous stated. I changed the way I am formatting the data to:
&A2168=1&A1837=5&A8472=1&A1987=2
On the server side I am using getParameterNames() to place all the keys into an Enumerator and then iterating over the Enumerator and placing the keys and values into a HashMap. It looks something like this:
Enumeration keys = request.getParameterNames();
HashMap map = new HashMap();
String key = null;
while(keys.hasMoreElements()){
key = keys.nextElement().toString();
map.put(key, request.getParameter(key));
}
To get the value from the servlet from POST command, you can follow the approach as explained on this post by using request.getParameter(key) format which will return the value you want.

Categories

Resources