jquery form submission - ajax

Can someone show me a tutorial of using jquery to display successful form submission without refreshing the page. Something like that happens on gmail when a message is delivered and the yellow overlay that shows that you message was delivered and then fade outs.

Use jQuery+JSON combination something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'></div>
_test.php:
<?php
// Code here to deal with your form submitted data.
$arr = array( 'testDiv' => 'Form is successfully submitted.' );
echo json_encode( $arr );
?>
jsFile.js:
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
OR:
You can use jQuery Form Plugin

Related

How to call ajax function on buttonclick in laravel?

View Code:
<script>
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Here ,When I click on the button it should be replaced by the other text. But nothings appears on clicking.
Controller code:
public function index(){
$msg = "This is a simple message.";
return response()->json(array('msg'=> $msg), 200);
}
In pure js that code work fine
function getMessage(){
alert('Its working!');
}
<body>
<div id = 'msg'>This message will be replaced using Ajax.
Click the button to replace the message.</div>
<input type="button" value="Replace Message" onclick='getMessage()'>
</body>
Looks OK.
Put a breakpoint in your success and see what data is.
Or do a console.log
Mick
in your ajax code you didn't define dataType, add dataType:"json", to retrive the json data, change your ajax code as
function getMessage(){
$.ajax({
type:'POST',
url:'/getmsg',
dataType:'json',
data:{
_token = '<?php echo csrf_token() ?>'
},
success:function(data){
$("#msg").html(data.msg);
}
});
Update your code with below mentioned code, and let's try.. i will working for me..
<script type="text/javascript" charset="utf-8">
$(document).on('click', '#btnSelector', function(event) {
event.preventDefault();
/* Act on the event */
getMessage();
});
var getMessage = function(){
$.ajax({
type:'POST',
url:'/getmsg', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
console.log(data); //Please share cosnole data
if(data.msg) //Check the data.msg isset?
{
$("#msg").html(data.msg); //replace html by data.msg
}
}
});
}
</script>
<body>
<div id = 'msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" value="Replace Message" id='btnSelector'>
</body>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<body>
<div id='msg'>This message will be replaced using Ajax. Click the button to replace the message.</div>
<input type="button" id="ajax_call" value="Replace Message">
</body>
<script>
$(function () {
$('#ajax_call').on('click', function () {
$.ajax({
type:'POST',
url:'<?php echo url("/getms"); ?>',
data:'_token = <?php echo csrf_token() ?>',
success:function(data){
$("#msg").html(data.msg);
},
complete: function(){
alert('complete');
},
error: function(result) {
alert('error');
}
});
});
});
</script>
Jquery onclick function: jquery onclick function not defined
Also check: Function not calling within an onclick event

ajax request to controller to update view in laravel

I can't find a working solution for this problem:
I want to update a part of my view without reloading it,
I have a form that collects the data to be passed to the controller,
the controller needs to get the data from the DB and spit out a JSON
to the view so that it can be filled with such data.
I tried to adapt this http://tutsnare.com/post-data-using-ajax-in-laravel-5/ but it's not working at all. The data collected is not reaching the controller.
My uderstanding is the javascript part in the view should listen to the click event and send a GET request to the controller, the controller checks if the data is sent through AJAX, gets the data from DB then returns the response in JSON form, the view is then updated.
Please, does anyone have a working example or can explain?
Simple working example using JQuery:
In you routes.php file:
Route::post('/postform', function () {
// here you should do whatever you need to do with posted data
return response()->json(['msg' => 'Success!','test' => Input::get('test')]);
});
and in your blade view file:
<form method="POST" action="{{ url('postform') }}">
<input type="hidden" name="_token" value="{{ csrf_token() }}" />
<input type="text" name="test" value="" />
<input type="submit" value="Send" />
</form>
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function ($) {
$(document).ready(function()
{
var form = $('form');
form.submit(function(e){
e.preventDefault();
$.ajax({
url: form.prop('action'),
type: 'post',
dataType: 'json',
data: form.serialize(),
success: function(data)
{
console.log(data);
if(data.msg){
alert( data.msg + ' You said: ' + data.test);
}
}
})
});
});
});
</script>
As you can see, most of the logic is done in JavaScript which has nothing to do with Laravel. So if that is not understandable for you, I'd recommend to look for jQuery ajax tutorials or rtfm :)
I have experienced submitting a modal form without reloading the entire page. I let the user add option to the dropdown and then repopulate the items on that dropdown without reloading the entire page after and item is added.
you can have custom route to your controller that handles the process and can be called by javascript and will return json
Route::get('/profiles/create/waterSource',function(){
$data = WaterSource::orderBy('description')->get();
return Response::json($data);
});
then the javascript
<script>
$(document).on('submit', '.myForm-waterSource', function(e) {
$.ajax({
url: $(this).attr('action'),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(html) {
$.get('{{ url('profiles') }}/create/waterSource', function(data) {
console.log(data);
$.each(data, function(index,subCatObj){
if (!$('#waterSource option[value="'+subCatObj.id+'"]').length) {
$('#waterSource').append('<option value="'+subCatObj.id+'">'+subCatObj.description+'</option>');
}
});
$('#myModal-waterSource').modal('hide');
$('#modal-waterSource').val('');
});
}
});
e.preventDefault();
});
</script>
You can view the full tutorial at Creating new Dropdown Option Without Reloading the Page in Laravel 5

jquery form plugin doesnot working

I write a code that submit a form to another page without loading like ajax.I use jquery form plugin.but the problem is it is not working.
here is my code
<div id='preview'></div>
<form action='ajaxcall.php' id='upload_pic' enctype='multipart/form-data' method='post'>
<input type='file' id='pic' name='picture'>
<input type='button' id='sub'>
</form>
<script type="text/javascript" src='jqueryform.js'></script>
<script>
var options=
{
target:'#preview',
url:'ajaxcall.php',
success:function(){
document.getElementById("upload_pic").reset();
}
};
$(document).ready(function(){
$("#sub").click(function(){
$('#preview').html("<img src='images/loader.gif' alt='Loading.....'/>");
$('#upload_pic').ajaxForm(options).submit();
});
});
</script>
I understand that the ajaxForm() function is not working.the jquery file is above the code and working fine.After clicking button page automatically redirected to ajaxcall.php page.please help me finding out the error.Thanks in advance.
In this scenario you need to use ajaxSubmit
$(document).ready(function() {
var options = {
target : '#preview',
url : 'ajaxcall.php',
success : function() {
document.getElementById("upload_pic").reset();
}
};
$("#sub").click(function() {
$('#preview').html("<img src='images/loader.gif' alt='Loading.....'/>");
$('#upload_pic').ajaxSubmit(options);
});
});
Add one more submit function:
$(document).ready(function(){
$('#upload_pic').submit(function(e){ // <---pass event here
e.preventDefault(); //<----------------stop it here
});
$("#sub").click(function(){
$('#preview').html("<img src='images/loader.gif' alt='Loading.....'/>");
$('#upload_pic').ajaxForm(options).submit();
});
});
Try to stop the submit before the click.

How get the value from a link and send the form using mootools?

I have a such form with many links:
<form name="myform" action="" method="get" id="form">
<p>
My link
</p>
<p>
My link 2
</p>
<p>
My link 3
</p>
<input type="hidden" name="division" value="" />
</form>
I would like to send the form's value from the link that was clicked to php script and get the response (not reloading the page).
I'm trying to write a function that gets the value from a link:
<script type="text/javascript">
window.addEvent('domready', function() {
getValue = function(division)
{
var division;
division=$('form').getElements('a');
}
</script>
but I don't know how to write it in a right way. Next I would like to send the form:
$$('a.del').each(function(el) {
el.addEvent('click', function(e) {
new Event(e).stop();
$('form').submit();
});
});
How I should send it to get the response from a php file not reloading the page?
Instead of putting in javascript inline in the HTML, I would suggest using a delegated event instead. I would also send the form using an ajax call instead of a form submit.
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var formEl = document.id('form');
formEl.addEvent('click:relay(.del)', function() {
var value = this.getProperty('data-value');
new Request.JSON({
url: '/path/to/your/listener',
onSuccess: function(data) {
// ...
}
}).get({
value: value
});
});
</script>
This works for me:
<form id="form">
<a data-value="A">My link</a>
...
</form>
<script>
var links = document.id('form').getElements('a');
links.each(function(link) {
link.addEvent('click', function(e) {
e.stop();
var value = link.getProperty('data-value');
var req = new Request.HTML({
url: "/path/to/your/listener",
data: value,
onRequest: function(){
$('display').set('text', 'Search...');
},
onComplete: function() {
},
update : $('display')
}).get(
{data: value}
);
});
})
</script>

JSONP callback successful but javascript not updating .html when jQueryMobile included

I am building a PhoneGap app using jQuery Mobile. My JSONP cross domain communication works, but have an issue when jQuery Mobile is included. Without it everything works as expected, included, it stops working.
I've reduced code to simplest form - Serialize data, encode and call CrossDomain PHP file using JSONP. Execute success function. I thought it might be bad JS but "alert" works and no JS errors. But the $('#section1').html("SECTION 1 - " + data.message); doesn't update. Note: When I remove jQM it all works!
Below is the HTML and the PHP code it calls. It's as though the jQueryMobile AJAX call is interfering with the update of the .html code. Any ideas? I'm stumped.
Ajax4d.htm
<html><head><title>First jQueryMobile Example</title>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.css" />
<script src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
<script src="http://code.jquery.com/mobile/1.1.0/jquery.mobile-1.1.0.min.js"></script>
<script>
$(document).ready(function() {
$("#foo").submit(function(event) {
event.preventDefault();
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
var postData = serializedData;
var urlStr = "http://www.fohost.co/testURLd.php?";
alert (urlStr + encodeURI(postData));
$.ajax({
url: urlStr,
data: encodeURI(postData),
dataType: "jsonp",
success: function(data){
alert("SUCCESS callback before HTML update: " + data.message);
$('#section1').html("SECTION 1 - " + data.message);
}
});
});
});
</script>
</head>
<body>
<section id="register_page" data-role="page" data-theme="b">
<div data-role="content">
<form id="foo" method="get" action="">
<fieldset data-role="fieldcontain">
<label for="username">Username:</label>
<input type="text" name="username" id="username" value="Chris" placeholder="Username"/>
</fieldset>
<fieldset class="ui-grid-a"><input type="submit" value="Send" /></fieldset>
</form>
</div>
<div id="section1">SECTION</div>
</section>
</body>
</html>
testURLd.php
<?php
header("content-type: application/json");
$user = $_GET['username'];
$rtnjsonobj->success = "true";
$rtnjsonobj->user = $user;
$rtnjsonobj->message = "Stored User: " . $user;
echo $_GET['callback']. '('. json_encode($rtnjsonobj) . ')';
?>
When you use the submit() method, but fire an ajax call, you aren't prohibiting the form from submitting.
Add a return false; to the end of the $("#foo").submit method. This will prohibit the page from reloading onclick.
Use pageinit instead of document ready..
check this link..
http://jquerymobile.com/test/docs/api/events.html
try this one..
$( document ).delegate("#register_page" ,"pageinit", function() {
$("#foo").submit(function(event) {
event.preventDefault();
var $form = $(this),
$inputs = $form.find("input, select, button, textarea"),
serializedData = $form.serialize();
var postData = serializedData;
var urlStr = "http://www.fohost.co/testURLd.php?";
alert (urlStr + encodeURI(postData));
$.ajax({
url: urlStr,
data: encodeURI(postData),
dataType: "jsonp",
success: function(data){
alert("SUCCESS callback before HTML update: " + data.message);
$('#section1').html("SECTION 1 - " + data.message);
}
});
});
});

Resources