Ajax form Issue - php

I am trying to do a simple ajax form post. I think there is an issue with my code at the $.ajax lines. Once the code hits the $.ajax portion, console.log() fails to work and the form just redirects conventionally to the ajax-report-comment.php page and not through ajax. Up to this part my console.log function reports data and doesn't redirect to the page.
Does any one see what I am doing wrong here? Essentially on success I want it to alert the user of successful report.
Thanks in advance!
Code:
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('form.ajax').on('submit',function() {
var that = $(this),
url = that.attr('action'),
method = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
});
</script>
</head>
<body>
<form method="post" action="ajax-report-comment.php" class="ajax">
<input type="submit" value="Report" />
<input class="field" type="hidden" name="report_user_id" id="report_user_id" value="5"/>
<input class="field" type="hidden" name="report_comment_id" id="report_comment_id" value="33543"/>
</form>
</body>
</html>

I'm pretty sure return false; to cancel default actions is deprecated in modern versions of jQuery (if you use the migrate plugin, you will see warnings about that), so you should use:
$('form.ajax').on('submit',function(e) {
e.preventDefault();
// the rest of your code

I wanted to add to #jeroen answer a bit:
Use event.preventDefault() as he suggests, but also check into .serialize().
You could replace this entire block of code (from your code above):
// Replace this entire block with jQuery's serialize
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
With:
var data = $(this).serialize();

Thanks to Jeroen I was able to find that error of anonymous function. I had method where I should have had type in the var.
Corrected functioning js code:
$(document).ready(function(){
$('form.ajax').on('submit',function(e) {
e.preventDefault();
var that = $(this),
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value) {
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
});

Related

PHP keeps picking up last element of radio buttons

I have the following problem:
I'm submitting my data from radio buttons to a ajax request so I can move the data to the database.
-html
<form class="siteInfo" action="ajax/site.php?nr=<?php echo $_GET['nr']; ?>" method="POST">
<input type="radio" name="transport_transport_id" value="1"> <span class="value">1</span><br/>
<input type="radio" name="transport_transport_id" value="2"> <span class="value">2</span><br/>
<input type="radio" name="transport_transport_id" value="3" tabindex="21"> <span class="value">3</span><br/>
-The page that ajax posts to
foreach($_POST as $key => $val) {
if(!empty($val)) {
$result[$key] = $val;
//This should be passed to database update function
}
}
var_dump($_POST);
$site->setSiteFields($siteNumber, $result);
-The ajax
$('.siteInfo').on('change', function() {
var that = $(this);
url = that.attr('action'),
type = that.attr('method'),
data = {};
that.find('[name]').each(function(index, value){
var that = $(this),
name = that.attr('name'),
value = that.val();
data[name] = value;
});
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});
The ajax returns the response it gets from the pickup page but doesn't matter what radio button I pick, I only get the last value returned. Anybody can tell me what goes wrong?
Thanks in advance!
Try this
$('.siteInfo').on('change', function() {
var that = $(this);
url = that.attr('action'),
type = that.attr('method'),
data = {};
data[name] = that.find("input[name='transport_transport_id']:checked").val();
$.ajax({
url: url,
type: type,
data: data,
success: function(response) {
console.log(response);
}
});
return false;
});

Laravel 5.2 - How to pass variables (arrays and ints) from view to controller?

I am trying to pass data from Javascript code to a Controller but I cant get the variables data in the Controller Code.
I have a view that has a Js file associated that checks when the submit button is clicked and creates some arrays with data to be sent to the server.
I have tried a lot of solutions (commenting the form and defining a attribute to the button with the URL, using the form post action , using $.post in javascript) but i cant seem to get it working.
I have included code to better illustrate what I am trying to do.
Import View code:
<form id="importar" class="form-horizontal" role="form" method="POST" action="{{ url('/importarLista1') }}">
{{ csrf_field() }}
<input type="text" class="form-control" name="startFrom" id="startFrom" value="">
<div class="col-md-4">
<button class="btn btn-primary" id="importar" data-href="{{ url('/importarLista1') }}">
<i class="fa fa-btn fa-sign-in"></i>Importar
</button>
</div>
</form>
JavaScript Code:
var fdata= "startFrom="+ startFrom;
fdata+= "&idList="+ idList;
fdata+= "&nomeCampos="+ nomeCampos;
fdata+= "&posicaoCampos="+ posicaoCampos;
$.ajax({
type:'POST',
url: $( this ).attr( 'data-href' ) /*$( this ).prop( 'action' ) $( this ).attr( 'data-href' )*/,
data:fdata,
dataType:'json',
cache:false,
success:function (data){
alert(data);
}
});
nomeCampos and posicaoCampos are arrays created using javascript and have values assigned to them so they are not empty
JavaScript Code Edit1 Updated code from answer
$('#importar').submit(function() {
if($('#startFrom').val()=='') {
var startFrom = 0;
}else{
var startFrom = $('#startFrom').val();
}
var nomeCampos = new Array();
var posicaoCampos = new Array();
$('tbody tr').each( function(){
$('td', this).each(function(e){
posicaoCampos[e] = $(this).attr('idc');
});
return false;
});
var idList = $('#idList').val();
var fdata= "_token="+ $( this ).find( 'input[name=_token]' ).val();
fdata+= "&startFrom="+ startFrom;
fdata+= "&idList="+ idList;
fdata+= "&nomeCampos="+ nomeCampos;
fdata+= "&posicaoCampos="+ posicaoCampos;
e.preventDefault();
$.post( // short hand for $.ajax({ type:'POST'
$(this).attr('action'), // url, from form
$(this).serialize(), // form data, name and value
function(data) {
// on success...
alert(data);
}
);
}); // end form.submit
Controller Code
protected function importList1(Request $request){
echo $_POST['startFrom'];
exit();
if($request->ajax()) {
$data = Input::all();
print_r($data);die;
}
print_r($request->all());
}
Route
Route::post('/importarLista1','ContactsList\ContactListController#importList1');
Example Solution
This is what my final code looks like
JavaScript
function preparePostData(){
var token = $( '#importar' ).find('input[name=_token]').val();
var startFrom = 0;
var idList = $('#idList').val();
var nomeCampos = new Array(); // not sure where this is getting used?
var posicaoCampos = new Array();
if($('#startFrom').val()=='' || $('#startFrom').val()<=0 ) {
var startFrom = 0;
}else{
var startFrom = $('#startFrom').val()-1;
}
var nomeCampos = new Array();
var posicaoCampos = new Array();
$('thead tr th').each(function(e){
for(var i = 0; i < nomeCampos.length; i++){
if(nomeCampos[i]==$('select', this).val()){
$.Notification.autoHideNotify('error', 'top right', 'STATUS', 'Não pode selecionar Campos Iguais');
exit();
}
}
nomeCampos[e] = $('select', this).val();
});
$('tbody tr').each( function(){
$('td', this).each(function(e){
posicaoCampos[e] = $(this).attr('idc');
});
return false;
});
var file_data=$('input:file')[0].files;
var postdata=new FormData();
postdata.append('_token',token);
postdata.append('startFrom',startFrom);
postdata.append('idList',idList);
postdata.append('nomeCampos',nomeCampos);
postdata.append('posicaoCampos',posicaoCampos);
postdata.append('file',file_data[0]);
return postdata;
}
$('#importar').submit(function(e) {
e.preventDefault();
fdata=preparePostData();
$.ajax({
type:'POST',
url: $(this).prop('action'), // url, from form
data:fdata,
processData: false,
contentType: false,
success:function(data) {
window.location.replace(data.url);
}
});
}); // end form.submit
Controller
if ($request->session()->token() !== $request->get('_token')) {
return Response::json(array(
'status' => 'error',
'msg' => 'Invalid token'
));
}
$idCompany = $request->session()->get('current_company');
$skipValue = $request->get('startFrom');
$idList = $request->get('idList');
$arrayPos = $request->get('posicaoCampos');
$arrayCampos = $request->get('nomeCampos');
And do what you need to do
This is my approach when using forms for ajax in a laravel application, as I'm sure it is for many others...
You have your form:
HTML
<form id="importar" class="form-horizontal" role="form" method="POST" action="{{ url('/importarLista1') }}">
{{ csrf_field() }}
<input type="text" class="form-control" name="startFrom" id="startFrom" value="">
<div class="col-md-4">
<button class="btn btn-primary" id="importar" data-href="{{ url('/importarLista1') }}">
<i class="fa fa-btn fa-sign-in"></i>Importar
</button>
</div>
</form>
if you're submitting all your data from one form, rather than doing this to prep your data:
var fdata= "startFrom="+ startFrom;
fdata+= "&idList="+ idList;
fdata+= "&nomeCampos="+ nomeCampos;
fdata+= "&posicaoCampos="+ posicaoCampos;
You can instead listen for the form submission (You may need to update/add to the form's button to type="submit") and use the serialize() method to grab all the data. (This would of course only work if everything is in one form and it's not clear to me if that is the case for you.)
So you could do something like this:
JS
$('form').submit(function() {
e.preventDefault();
$.post( // short hand for $.ajax({ type:'POST'
$(this).attr('action'), // url, from form
$(this).serialize(), // form data, name and value
function(data) {
// on success...
alert(data);
}
);
}); // end form.submit
PHP/Controller code
protected function importList1(Request $request){
// return the data back as ajax
return response()->ajax([
'data' => $request->all()
]);
}
Hope that helps!
Some extra advice, when getting started with using laravel and ajax together, if on chrome, you want to get the developer tools open. You can of course use firebug in firefox.
Using the developer tools, before hitting submit on your form, check the network tab then hit submit and see what happens. You should see a new post request. You can then click on the post request your form creates in the network tab to inspect what is going on and what comes back.
In short, the developer tools are invaluable for debugging ajax requests, because you will not get any feedback on the screen. You may also want to check out the chrome extension named postman for testing your ajax requests.
Edit
As you're not solely using the form for the data in your post call, serializing the form data won't be sufficient.
I extracted your code to prepare the data for the post call to a separate function to make it more readble and called the function when the form is submitted.
The data is passed to the $.post method as an object rather than a string.
I wrote the code just in my text editor, I didn't test it out. So there may be some mistakes, try and play around with it if you encounter any.
JS
$('#importar').submit(function() {
e.preventDefault(); // stop the form from submitting data
// prep data for ajax post
var postData = preparePostData(); // call function to get data
// perform ajax post
$.post( // short hand for $.ajax({ type:'POST'
$(this).attr('action'), // url, from form
postData, // form data, name and value
function(data) {
// on success...
alert(data);
}
);
}); // end form.submit
function preparePostData() {
var token = $( this ).find('input[name=_token]').val();
var startFrom = 0;
var idList = $('#idList').val();
var nomeCampos = new Array(); // not sure where this is getting used?
var posicaoCampos = new Array();
if ($('#startFrom').val()=='') {
var startFrom = 0;
} else {
var startFrom = $('#startFrom').val();
}
$('tbody tr').each( function(){
$('td', this).each(function(e){
posicaoCampos[e] = $(this).attr('idc');
});
return false;
});
var postData = {
_token: token,
startFrom: startFrom,
idList: idList,
nomeCampos: nomeCampos,
posicaoCampos: posicaoCampos
};
return postData;
}

Post variable before redirect?

I am currently building on a CMS. I want to send a page-id or site-id to the next page on redirect. I tried doing it using the jQuery POST function:
$(document).ready(function(){
$('.sender').on('click','a',function(){
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: { siteid:siteid },
success: function(response){
console.log('check');
},
error: function(){
console.log('error');
}
});
});
});
But because the request is sent at the same time as the redirect, it does not seems to work.
Because I am using the apache rewrite_engine to redirect stuff, I cannot use GET.
Apart from session_variables, what are my options?
I want to keep it safe, so I don't want much info to be visible/available!
To achieve this you need to wait for the AJAX request to complete before the page is redirected. Try this:
$(document).ready(function(){
$('.sender').on('click', 'a', function(e){
e.preventDefault(); // stop the default redirect
var url = $(this).attr('href');
var n = url.indexOf('#') + 1;
var siteid = url.substr(n, url.length);
$.ajax({
url: 'pages.php',
type: 'POST',
data: {
siteid: siteid
},
success: function(response){
console.log('check');
window.location.assign(url); // redirect once the AJAX has successfully completed
},
error: function(){
console.log('error');
}
});
});
});
I'm not sure to clearly understand why you need but I think this can answer your problem.
If what you need is to transfert informations using a real POST method, just create an hidden form with method="POST" and fill it on click event.
<script type="text/javascript">
$(document).ready(function(){
$('.sender').on('click','a',function(event){
event.preventDefault();
var url = $(this).attr('href');
var n = url.indexOf('#')+1;
var siteid = url.substr(n,url.length);
$('input[name="siteid"]').val(siteid);
$('#redirectForm').submit();
});
});
</script>
<form id="redirectForm" action="pages.php" method="POST">
<input type="hidden" name="siteid" value=""/>
</form>

Ajax autosave multiple fields

I have a page that has fields editable via contenteditable. I am autosaving the fields via ajax after the user edits the field. The problem is, I have multiple fields on the same page and when I try to autosave more than one field, either one field won't work or gets overwritten with the same content as the other field.
This is the code that I am using to update the database and it works exactly how I want it to for the "name" field.
$('.editname').keyup(function() {
delay(function(){
var name= $('.editname').text();
$.ajax({
type:"post",
url:"update.php",
data:"name="+name,
success:function(data){
console.log('success!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
However if I try to edit it like the following or duplicate it and give it a different name, it will not work properly to update another field along with the first field.
$('.editname').keyup(function() {
delay(function(){
var name= $('.editname').text();
$.ajax({
type:"post",
url:"update.php",
data:"name="+name,
success:function(data){
console.log('success!');
}
});
}, 500 );
});
$('.editsummary').keyup(function() {
delay(function(){
var summary= $('.editsummary').text();
$.ajax({
type:"post",
url:"update.php",
data:"summary="+summary,
success:function(data){
console.log('success!');
}
});
}, 500 );
});
var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
What am I doing wrong in the above block of code?
Looks like a usual error developers get into when they copy and paste code.
var name= $('.editsummary').text();
This should read:
var summary = $('.editsummary').text();
EDIT
This is how you do it properly. Have one generic auto-save handler and re-use it.
For example (html/js):
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">
// When Page Loads
$(document).ready(function()
{
// Handle Auto Save
$('.autosaveEdit').keyup(function() {
var fieldName = $(this).attr('name');
var fieldValue = $(this).val();
delay(function() {
$.ajax({
type: "post",
url: "update.php",
data: { fName: fieldName, fValue: fieldValue },
success: function(data) {
console.log('success!');
}
});
}, 500 );
});
});
var delay = (function() {
var timer = 0;
return function(callback, ms) {
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();
</script>
Firstname: <input type="text" class="autosaveEdit" name="firstname" />
<br />
Lastname: <input type="text" class="autosaveEdit" name="lastname" />
Now, on your update.php
<?php
// Get the post data
$fieldName = isset($_POST['fName']) ? $_POST['fName'] : '';
$fieldValue = isset($_POST['fValue']) ? $_POST['fValue'] : '';
// Now save the $fieldValue against $fieldName in your db (if neither is empty)
So, in my example form, if I start editing the "firstname" input field, the auto-save will post the following to update.php:
print_r($_POST)
Array
(
[fName] => firstname
[fValue] => hello
)
I've tweaked your example a little to get it to work with JS Fiddle:
http://jsfiddle.net/eHz4t/
<div class="editname" contenteditable="true">my name</div>
<div class="editsummary"contenteditable>my summary</div>
It works properly. You can open the network console and see the traffic being sent.

getting values from textbox using jquery [output via php variable]

main.php:
<SCRIPT type="text/javascript">
$("#btnSubmit").click(function () {
alert("What will i put here!");
});
</SCRIPT>
<input type = "submit" id = "btnSubmit" value = "Try IT!" />
<div id = "show_search2">
</div>
output.php:
<?php $val = $_POST['btnSubmit'];
echo "<H1>$val</H1>"; ?>
What specific jQuery functionality can get the value of the btnSubmit and access it through $_POST and output it to the div show_search2? I used prototype.js but it provides conflict with my other JS scripts in the index.
Note: all my script source is included in index and that's why I didn't include the source in this post.
Do you mean something like this:
$("#btnSubmit").click(function (e) {
e.preventDefault();
var submitVal = $(this).val();
$.ajax({
type: "POST",
url: "url_of_your_output.php",
data: {btnSubmit : submitVal},
success: function(response) {
$("#show_search2").html(response); //response from output.php
}
});
});

Categories