PHP Post Data with AJAX and DataTables - javascript

When submitting forms, I ran across problems in getting POST data in my server-side PHP script. I narrowed it down to a little bit of JQuery/JavaScript that loads JSON data via AJAX into a DataTable.
The form is as follows:
<form class="form-horizontal" action="./scripts/lookup.php" method="post" role="form" id="lookupForm">
<div class ="form-group">
<label for="inputLookup" class="col-sm-2 control-label">Username</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="inputLookup" name="lookup_name" placeholder="John.Doe" required/>
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<input id="submitUserLookupBtn" name="submitUserLookup" type="submit" value="Lookup" class="btn btn-primary"/>
</div>
</div>
</form>
And then the script:
$("#lookupForm").submit(function (e) {
e.preventDefault();
$.ajax({
type: 'POST',
url: './scripts/lookup.php',
dataType: 'json',
success: function(s) {
LUUTable.fnClearTable();
for(var i = 0; i < s.length; i++) {
LUUTable.fnAddData([
s[i][0],
s[i][1],
s[i][2],
s[i][3],
s[i][4],
s[i][5],
s[i][6],
s[i][7]
]);
}
},
error: function(e) {
if (e.responseText != '') {
console.log("Error: " + e.responseText);
} else {
console.log("Warning: No data to return.");
}
}
});
});
Whenever that code snippet is run, the PHP does not get POST data, however once I comment the script out, POST data is sent to the server. The problem, however, is that this code snippet is where I handle the JSON data returned by the server.
What could be the reason for this causing data not to POST, and how might I either further troubleshoot or mitigate this issue?
Much appreciated!

You are sending the data twice to the ./script/lookup.php
<form class="form-horizontal" action="./scripts/lookup.php" method="post" role="form" id="lookupForm">
and in the Ajax script. Change the above line to
<form class="form-horizontal" role="form" id="lookupForm">
Just keep the url, and type: post in the ajax call in the javascript.

Serialize your form data and send the values in your AJAX:
$("#lookupForm").submit(function (e) {
e.preventDefault();
var formValues = $(this).serialize(); // serialize the form data
$.ajax({
type: 'POST',
url: './scripts/lookup.php',
data: formValues, // send serailized form data here
dataType: 'json',

Related

Returning response from JSON request using Ajax form on Laravel blade template

Ok, so i have a API based on Laravel, i'm trying to return its JSON response in a view with it's own form data.
HTML:
<form id="translate" action="translate" method="GET">
<div class="form-group"><label for="from" name="from">Translate from</label><select class="form-control" id="from"><option value="latin" selected="selected">Latin alphabet</option><option value="deepling">Jekhr</option></select></div>
<div class="form-group"><label for="message" name="message">Message</label><textarea class="form-control" id="message"></textarea></div>
<div class="form-group"><div class="form-row"></div></div>
<button class="btn btn-primary btn-block" type="submit">Translate!</button>
</form>
Base API URL:
http://localhost/translate?text=Hello World&method=Latin&pronunciation
So i'm trying to write a Ajax request to get JSON response with form data and display it on DOM table, like:
Translated Message = $json["translated"]
Pronunciation = $json["pronounce"]
Can anyone help me?
Edit:
Here's a solution that I got based on comment:
$("#translate").submit(function(e) {
e.preventDefault();
var form = $(this);
var url = form.attr('action');
$.ajax({
type: "GET",
url: url,
data: form.serialize(),
success: function(data)
{
$('#translateTable tbody tr').remove();
$('#translateTable tbody').append("<tr><td>Request</td><td>" + data.requested + "</td></tr><tr><td>Translation</td><td>" + data.translated + "</td></tr><tr><td>Pronounce</td><td>" + data.pronounce + "</td></tr>");
$('#translateTable').show();
}
});
});

PHP Ajax Submit Form Return Data

I have the following form in my HTML page:
<form id="submission" action="testresponse.php" method="post">
<input id="URL" name="URL" type="text">
<button name="Submit" type="submit">Submit</button>
</form>
testresponse.php just contains <?php print_r($_POST); ?> to print all the post variables.
I am trying to submit the form and have it return the values on the same page that the page was submitted (i.e. return the POST variables somewhere above the form)
I used the following jQuery code:
$( document ).ready(function() {
var frm = $('#submission');
frm.submit(function (ev) {
$.ajax({
type: frm.attr('method'),
url: frm.attr('action'),
data: frm.serialize(),
success: function (data) {
console.log(data.responseText);
}
});
ev.preventDefault();
});
});
But for some reason data.responseText always returns blank
Is there a way to have my form send a POST request to a PHP page and return the result?
Change from
console.log(data.responseText)
to
console.log(data)

AJax not calling php file correctly, html forms

UPDATE:
This is the error:
412 (Precondition Failed)
I am trying to call a php script from ajax, I currently have the below ajax, which when the button in the form (also below) is clicked will call a php script passing it the form data, which will then be submitted to the database.
However, it is not working; and what's more I am just getting a blank error back, so I do not even know what is going wrong.
Could someon please point me in the right direction?
Thanks.
HTML form:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<!--<input id="report-submit" value="" name="submit" type="submit" onclick="submitReport()"/> -->
<button id="report-submit" name="submit" onclick="submitReport()"></button>
</form>
AJax call:
function submitReport()
{
var ID=$('#reportedID').val();
var reason=$('#reason-box').val();
var formData = "ID="+ID+"&reason="+reason;
alert(formData);
//This code will run when the user submits a report.
$.ajax(
{
url: 'submit_report.php',
type: "POST",
data: formData,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
}
Now I have already tested the php script, and that works fine, the problem started when I added the ajax call so I know it is something to do with the ajax not the php.
This should correct the problem with submitting:
Your jQuery Ajax call won't succeed because the POST data isn't supplied in the correct format.
If the ajax should succeed the form is also posted resulting in a 405 error.
<button id="report-submit" name="submit" onclick="submitReport(event)"></button>
function submitReport(event)
{
event.preventDefault();
....... // your code
}
Now the default action of your form will be prevented (resulting in a 405 error). And only the ajax request is submitted.
In the button element we pass the event object on to the function. We use event.preventDefault() to make sure the button doesn't run it's default action, which is submitting the form.
You could also prevent this by deleting the form element as a wrapper, but maybe you want to use other features (like validation) on the form.
Form data in a jQuery ajax request needs to be an object called data:
var formData = {"ID" : ID, "reason" : reason};
jQuery will reform this to a correct query string for the submit.
I would do it like this:
<form name="report-form" id="report-form" action="" method="POST">
<textarea id="reason-box" type="text" name="reason-box" cols="40" rows="5" maxlength="160"></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" type="submit" name="submit" value="submit"></button>
</form>
<script type="text/javascript">
jQuery("document").ready(function(){
var $ = jQuery
$("form").submit(function(){
var data = "";
data = $(this).serialize() + "&" + $.param(data);
$.ajax({
type: "POST",
url: "submit_report.php",
data: data,
success: function(data)
{
alert("Report Submitted!");
},
error: function(xhr,err)
{
alert(err.message);
alert("responseText: "+ xhr.responseText);
}
});
return false;
});
});
</script>
and then use $reason=$_POST['reason-box']; and $ID=$_POST['reportedID']; inside your PHP script
this is optional to choose the form for submitting data or you can do it without the HTML form this is what i do
<textarea id="reasonbox" type="text" name="reason-box" cols="40" rows="5" maxlength="160" onkeypress=""></textarea>
<input id="reportedID" name="reportedID" type="text" />
<button id="report-submit" ></button>
and the using folloing javascript and jquery style
<script type="text/javascript">
$(function() {
$("#report-submit").click(function(){
try
{
$.post("your php page address goes here like /mypage.php",
{
//in this area you put the data that is going to server like line below
'reasonbox':$("#reason-box").val().trim(),
'reportedID':$("#reportedID").val().trim()
}, function(data){
data=data.trim();
//this is data is sent back from server you can send back data that you want
//like message or json array
});
}
catch(ex)
{
alert(ex);
}
});
});
</script>
I hope it helps

How to properly get form data with JQuery and formData

I am trying to upload some form data using ajax and php but for some reason my data is not being catch or passed.
Here is what I have:
form.html ( basic form with 3 text inputs and 1 file)
<form class="form" id="superform" action="nada.php" method="post" enctype="multipart/form-data">
<div class="form-group">
<label for="tituloQuiz">Resultado:</label>
<input type="text" class="form-control resultado" id="titulo" name="titulo" placeholder="Ex: Paris">
</div>
<div class="form-group">
<label for="desc">Descrição do Site:</label>
<textarea class="form-control" id="desc" name="descricao" placeholder="Ex:"></textarea>
</div>
<div class="form-group">
<label for="desc">OG FB DESC:</label>
<textarea class="form-control" id="facedes" name="descricao" placeholder="facebook description"></textarea>
</div>
<div class="form-group">
<label for="imggrande">Imagem</label>
<input type="file" id="imggrande" name="imgres">
<p class="help-block">Imagem usada na página de resultado e Facebook 600 x 400.</p>
</div>
<button type="button" class="btn btn-primary btn-lg addres">Adicionar Resultado</button>
<button type="button" class="btn btn-danger btn-lg">Próxima Etapa</button>
</form>
And here is the JS that makes the ajax call:
myjs.js
$("document").ready(function(){
$('.row').on('click','.addres',function(){
console.log('Click Detectado');
var formulario = $('#superform');
var formData = new FormData(formulario);
$.ajax({
type: "POST",
url: "addres.php",
data: formData,
async: false,
success: function(data) {
console.log('Funcionou');
},
error: function(data) {
console.log('Erro no formulario');
},
cache: false,
contetType: false,
processData: false
});
});
});
Nothing is being passed and the POST call is empty (See screenshots below).
**addres.php**
<?php
var_dump($_FILES);
var_dump($_POST);
?>
$.ajax({
url: 'address.php',
type: 'POST',
data: new FormData($('#superform')[0]), // The form with the file inputs.
processData: false, // Using FormData, no need to process data.
contentType:false
}).done(function(){
console.log("Success: Files sent!");
}).fail(function(){
console.log("An error occurred, the files couldn't be sent!");
});
When one sets the contentType option to false, it forces jQuery not to add a Content-Type header, otherwise, the boundary string will be missing from it. Also, when submitting files via multi-part/form one must leave the processData flag set to false, otherwise, jQuery will try to convert your FormData into a string, which will fail.
read from php using
$_FILES['file-0']
(There is only one file, file-0, unless you specified the multiple attribute on your file input, in which case, the numbers will increment with each file.)
Additional info:
See for yourself the difference of how your formData is passed to your php page by using console.log().
var formData = new FormData($('#superform')[0]);
console.log(formData);
var formDataSerialized = $('#superform').serialize();
console.log(formDataSerialized);
Hope this helps.
extra information read this upload files asynchronously
Note : formData doesn't work in IE 9
You can use .serializeArray() to get the data in array format and then convert it into an object. like this:
function getFormData(formId) {
let formData = {};
let inputs = $('#'+formId).serializeArray();
$.each(inputs, function (i, input) {
formData[input.name] = input.value;
});
return formData;
}

submitting a form via AJAX

I have a form that looks as following:
<form accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
<div class="field">
<label for="username">Email:</label>
<input class="text" id="passwordEmail" name="username" required="required" size="30" type="text">
<div class="field-meta">Put in your email, and we send you instructions for changing your password.</div>
</div>
<div class="field">
<input id="submitPasswordRequest" class="full-width button" name="commit" tabindex="3" type="submit" value="Get Password">
</div>
<div class="field center">
Nevermind, I Remembered
</div>
I am trying to do the post via AJAX, so I did a simple test like this:
$("#submitPasswordRequest").click(function() {
var username = $('#passwordEmail').value();
console.log(username);
/*
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: { username: username}, // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
*/
return false;
});
However it seems that the click function is not triggered and it goes to posting the form via the regular form action. What am I doing wrong here? I want to handle this via AJAX.
When you click upon the button, you simply submit the form to the back-end. To override this behavior you should override submit action on the form. Old style:
<form onsubmit="javascript: return false;">
New style:
$('form').submit(function() { return false; });
And on submit you want to perform an ajax query:
$('form').submit(function() {
$.ajax({ }); // here we perform ajax query
return false; // we don't want our form to be submitted
});
Use jQuery's preventDefault() method. Also, value() should be val().
$("#submitPasswordRequest").click(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/1/
You can also listen for the form's submit event:
$("form").submit(function (e) {
e.preventDefault();
var username = $('#passwordEmail').val();
...
});
Full code: http://jsfiddle.net/HXfwK/2/
jquery and ajax
$('form id goes here).submit(function(e){
e.preventDefault();
var assign_variable_name_to_field = $("#field_id").val();
...
if(assign_variable_name_to_field =="")
{
handle error here
}
(don't forget to handle errors also in the server side with php)
after everyting is good then here comes ajax
datastring = $("form_id").serialize();
$.ajax({
type:'post',
url:'url_of_your_php_file'
data: datastring,
datatype:'json',
...
success: function(msg){
if(msg.error==true)
{
show errors from server side without refreshing page
alert(msg.message)
//this will alert error message from php
}
else
{
show success message or redirect
alert(msg.message);
//this will alert success message from php
}
})
});
on php page
$variable = $_POST['field_name']; //don't use field_id if the field_id is different than field name
...
then use server side validation
if(!$variable)
{
$data['error']= true;
$data['message'] = "this field is required...blah";
echo json_encode($data);
}
else
{
after everything is good
do any crud or email sending
and then
$data['error'] = "false";
$data['message'] = "thank you ....blah";
echo json_encode($data);
}
You should use the form's submit handler instead of the click handler. Like this:
$("#formID").submit(function() {
// ajax stuff here...
return false;
});
And in the HTML, add the ID formID to your form element:
<form id="formID" accept-charset="UTF-8" action="{{ path("fos_user_resetting_send_email") }}" method="post">
You need to prevent the form from submitting and refreshing the page, and then run your AJAX code:
$('form').on('submit',function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "/resetting/send-email",
data: $('form').serialize(), // serializes the form's elements.
success: function( data ) {
console.log(data); // show response from the php script.
}
});
return false;
});

Categories