I have a modal form with Bootstrap that is associated with a specific item that is customized by the user before being added to the cart. I'm trying to trigger an Ajax request when the "Add to Cart" button is clicked. But the button doesn't seem to be triggering anything. I'm using a modified version of Bootstrap's sample code: http://getbootstrap.com/javascript/#modals-related-target
Any suggestions on how to get the button to trigger an ajax request properly?
UPDATE: I've added the PHP code below in case that might be the issue.
HTML:
<div class="modal-body">
<form name="formBasic" id="formBasic">
<input type="hidden" name="function" value="basic-form">
<div class="form-group">
<label for="message-text" class="control-label">Enter customized information</label>
<textarea class="form-control" id="customized-information"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary" id="basic-submit">Add to Cart</button>
</div>
Javascript:
$(document).ready(function () {
var formBasic = function () {
var formData = $("#formBasic").serialize();
$(form).ajaxSubmit({
type: 'post',
data: formData,
dataType: 'json',
url: 'http://localhost/forms.php'
error: function () {
console.log(output);
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
$('#formBasicResults').html(output.responseText);
}
});
return false;
};
$("#basic-submit").on("click", function (e) {
e.preventDefault();
formBasic();
});
});
PHP:
//formBasic Processing
function formBasic(){
$output = 'Output from Form Basic:
';
foreach ($_POST as $key => $value) {
$output .= $key . ': ' . $value . '
';
}
echo $output;
}
//FormAdvanced Processing
//. . .
if(in_array($_POST['function'], array('formBasic','formAdvanced'))){
$_POST['function']();
}else{
echo 'There was an error processing the form';
}
Your code should be:
$(document).ready(function () {
var formBasic = function () {
var formData = $("#formBasic").serialize();
$.ajax({
type: 'post',
data: formData,
dataType: 'json',
url: 'http://localhost/forms.php',
error: function () {
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
$('#formBasicResults').html(output.responseText);
}
});
return false;
};
$("#basic-submit").on("click", function (e) {
e.preventDefault();
formBasic();
});
});
Issues:
1- Missing comma on line:
url: 'http://localhost/forms.php'
2- form not defined:
$(form).ajaxSubmit({
Working fiddle: http://jsfiddle.net/p9v2eg4u/2/
$('#basic-submit').click(function() {
var formData = $("#formBasic").serialize();
console.log(formData);
added a console.log(); of the value of form data
$('#formBasic').ajaxSubmit({
type: 'POST',
data: formData,
dataType: 'JSON',
url: 'http://localhost/forms.php',
added missing comma after URL
error: function () {
alert("There was an error processing this page.");
return false;
},
complete: function (output) {
console.log(output);
another console.log of output object
$('#formBasicResults').html(output.responseText);
},
success: function(output) {}
consider using success instead of complete, complete will execute if success or error.
});
return false;
});
Related
I am trying to submit a form using ajax in Laravel 5.5
The problem is the page is refreshing and not submitting data in the database. I need to store data in the database without refreshing the page.
Here is my code:
Controller
public function new_timing_table(Request $request)
{
if (Request::ajax()) {
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "yes";
} else {
$msg = "yes";
}
return ['msg'=> $msg];
}
View
<form id="timeForm" class="form-horizontal form-material" >
<div class="form-group">
{{ csrf_field() }}
<div class="col-md-12 m-b-20">
<label> Table Name</label>
<input type="text" id="timing_tables_name" class="form-control"
name="timing_tables_name" />
</div>
<div class="modal-footer">
<input type="button" value="Replace Message" id='btnSelector'>
</div>
</div>
</form>
Ajax script
const xCsrfToken = "{{ csrf_token() }}";
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': xCsrfToken
}
});
jQuery(document).ready(function() {
jQuery('#btnSelector').click(function(e) {
event.preventDefault();
getMessage();
});
});
var getMessage = function() {
var timing_tables_name = $("input[name=timing_tables_name]").val();
$.ajax({
type: 'post',
url: '/new_timing_table',
dataType: 'json', //Make sure your returning data type dffine as json
data: timing_tables_name,
//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);
}
}
});
}
Router
Route::post('/new_timing_table','Timing_TableControoler#new_timing_table');
You got a typo or a mistake in your script.
jQuery('#btnSelector').click(function(e){
// An error here - it should be e.preventDefault();
event.preventDefault();
getMessage();
});
My code is working now after adding beforeSend: function (request) in Ajax script
var getMessage = function(){
var timing_tables_name = $("#timing_tables_name").val();
console.log(timing_tables_name);
$.ajax({
type:'GET',
url:'/new_timing_table', //Make sure your URL is correct
dataType: 'json', //Make sure your returning data type dffine as json
data:
{
timing_tables_name
},
beforeSend: function (request) {
return request.setRequestHeader('X-CSRF-Token', $("meta[name='csrf-
token']").attr('content'));
},
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
}
}
});
}
and editing the controller to be simple as this one
public function new_timing_table(Request $request){
$timing_tables = new Timing_Table;
$timing_tables->timing_tables_name = $request->timing_tables_name;
$timing_tables->save();
$msg = "This is a simple message.";
return ['msg'=> $msg];
}
Thank you all for your help
This is my code for Javascript Ajax Jquery send data do purchase item.
$('.reserve-button').click(function(e){
var book_id = $(this).parent().data('id');
e.preventDefault();
$.ajax({
url: "/php/insertpurchase.php",
type: "POST",//type of posting the data
data: {"bookID": book_id},
success: function (data) {
alertify.alert("This item was add to your cart.", function(){
alertify.message('OK');
});
},
error: function (result, status, err) {
console.log('error', err, status);
},
timeout : 15000//timeout of the ajax call
});
});
This is HTML code for submit.
<div class="col-md-4">
<?php $bookID = $row['id'];?>
<div class= "obutton feature2" data-id="<?php echo $bookID;?>">
<button class="reserve-button"><?php echo $row['price'];?></button>
In PHP dont receive POST value ->
if(isset($_POST['bookID']))
{
$idProduct = $_POST['bookID'];
I think you should to define this code:
success: function (data) {
console.log(data);
});
Replace of this code:
success: function (data) {
alertify.alert("This item was add to your cart.", function(){
alertify.message('OK');
});
Now you see what result you get in the console.
First of all, I have to say that I'm beginner with using Ajax... So help me guys.
I want to insert the data into db without refreshing the page. So far, I have following code...
In blade I have a form with an id:
{!! Form::open(['url' => 'addFavorites', 'id' => 'ajax']) !!}
<img align="right" src="{{ asset('/img/icon_add_fav.png')}}">
<input type="hidden" name = "idUser" id="idUser" value="{{Auth::user()->id}}">
<input type="hidden" name = "idArticle" id="idArticle" value="{{$docinfo['attrs']['sid']}}">
<input type="submit" id="test" value="Ok">
{!! Form::close() !!}
And in controller I have:
public function addFavorites()
{
$idUser = Input::get('idUser');
$idArticle = Input::get('idArticle');
$favorite = new Favorite;
$favorite->idUser = $idUser;
$favorite->idArticle = $idArticle;
$favorite->save();
if ($favorite) {
return response()->json([
'status' => 'success',
'idUser' => $idUser,
'idArticle' => $idArticle]);
} else {
return response()->json([
'status' => 'error']);
}
}
I'm trying with ajax to insert into database:
$('#ajax').submit(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"{{ url('addFavorites') }}",
dataType="json",
data:$('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
}
error: function(data){
alert("Error")
}
});
});
Also in my web.php I have a route for adding favorites. But when I submit the form, it returns me JSON response like this: {"status":"success","idUser":"15","idArticle":"343970"}... It actually inserts into the db, but I want the page not to reload. Just to display alert box.
As #sujivasagam says it's performing a regular post action. Try to replace your javascript with this. I also recognized some syntax error but it is corrected here.
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
You could just replace <input type="submit"> with <button>instead and you'll probably won't be needing event.preventDefault() which prevents the form from posting.
EDIT
Here's an example of getting and posting just with javascript as asked for in comments.
(function() {
// Loads items into html
var pushItemsToList = function(items) {
var items = [];
$.each(items.data, function(i, item) {
items.push('<li>'+item.title+'</li>');
});
$('#the-ul-id').append(items.join(''));
}
// Fetching items
var fetchItems = function() {
$.ajax({
type: "GET",
url: "/items",
success: function(items) {
pushItemsToList(items);
},
error: function(error) {
alert("Error fetching items: " + error);
}
});
}
// Click event, adding item to favorites
$("#ajax").click(function(event) {
event.preventDefault();
$.ajax({
type: "post",
url: "{{ url('addFavorites') }}",
dataType: "json",
data: $('#ajax').serialize(),
success: function(data){
alert("Data Save: " + data);
},
error: function(data){
alert("Error")
}
});
});
// Load items (or whatever) when DOM's loaded
$(document).ready(function() {
fetchItems();
});
})();
You are using button type "Submit" which usually submit the form. So make that as button and on click of that call the ajax function
Change your button type to type="button" and add onclick action onclick="yourfunction()". and just put ajax inside your funciton.
Replace input type with button and make onClick listener. Make sure you use this input id in onclick listener:
So:
$('#test').on('click', function(event){
event.preventDefault()
... further code
I would also change the id to something clearer.
I can't get the ajax response when submitting a modal dialog form. It works perfectly when the form is not modal.
The form:
<div id="form2" style="display: none">
<form id="objectInsert" action="element/create" method="POST" enctype="multipart/form-data">
<div class="form-group">
<label for="name">Name</label>
<input class="form-control" type="text" name="name" id="name"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea class="form-control" name="description"></textarea>
</div>
</form>
Here i get the ajax success part in the console!
$("#objectInsert").submit(function(e) {
e.preventDefault();
resetErrors();
var form = this;
var url = $(this).attr('action');
var data = new FormData($(this)[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//Working
},
error: function() {
console.log('there was a problem checking the fields');
}
});
});
Here i get the ajax error part in the console! can someone tell me where i'm doing wrong?
$("#add_element").click(function(){
$("#form2").dialog({
modal:true,
width:400,
buttons:{
Send:function(e){
e.preventDefault();
var form = $("#objectInsert");
var url = form.attr('action');
var data = new FormData(form[0]);
$.ajax({
type: 'POST',
url: url,
data: data,
dataType: 'json',
cahe:false,
processData: false,
contentType: false,
success: function(resp) {
console.log(resp);//not working
},
error: function(xhr, status, error) {
console.log('there was a problem checking the fields');
console.log(xhr);
console.log(error);
}
});
return false;
},
Cancel:function(){
$(this).dialog("close");
}
}
});
});
The controller
public function create() {
try{
$this->form = new Form();
$this->form->post('name');
$this->form->val('isEmpty', 'name');
$this->form->post('description');
$this->form->val('isEmpty', 'description');
$this->form->fetch();
$this->form->submit();
$data = $this->form->get_postData();
$this->model->insert($data);
echo json_encode('success');
} catch (Exception $ex) {
$errors = $this->form->get_error();
$_SESSION["errors"] = $errors;
//This is for ajax requests:
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH'])
== 'xmlhttprequest') {
echo json_encode($_SESSION['errors']);
exit;
}
foreach ($_SESSION["errors"] as $errors){
echo $errors;
echo '<br/>';
}exit;
}
}
see this code you have not closed the function block
success: function(resp) {
console.log(resp);//not working
},//This is not closed for success function
error: function() {
console.log('there was a problem checking the fields');
}
I am new with jquery and ajax, so please be patient.
I have this link:
<a href="#message" style="text-decoration:none" class="common2 simple3" >Message</a>
that shows this pop up when clicked:
<div id="message" class="modalDialog">
<div>
<h3>Create A Message</h3>
<form id="msgForm" name="msgForm" action="#" method="post">
<textarea id = 'msgContent' cols="48" rows="10" ></textarea>
<br>
<div id="create_btn">
<a href='' id = 'send' class="common simple2" style='margin-left:50px;text-decoration: none;'>Send</a>
</div>
<div id="cancel_btn">
<a href="#close" class="common simple2" style='margin-left:40px;text-decoration: none;'>cancel</a>
</div>
</form>
</div>
</div>
when I entered text in the textarea and show its content by alert(msgContent) in the script below, it shows
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'message.php?message='+ msgContent,
type: 'GET',
dataType: 'json',
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
but when I try to pass it to a php page through ajax, it won't pass. What could be wrong?
this is message.php
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,$message)";
if (!mysqli_query($connection,$sql))
{
die('Error: ' . mysqli_error($connection));
}
You need to read the value from $_GET:
$message = $_GET['message'];
Or use the post method, with data attribute:
$(document).ready(function()
{
$("#send").click(function(e)
{
e.preventDefault();
var msgContent = $("#msgContent").val();
alert(msgContent);
$.ajax({
url: 'subscribe.php',
type: 'POST',
data: {message: msgContent},
//dataType: 'json', from your php I don't that that you are looking for json response...
context: this,
success: function(result)
{
//if (result == true)
$(this).html('Send');
}
});
})
})
Your JS should be this:
$(document).ready(function() {
$("#send").click(function(e) {
e.preventDefault();
var msgContent = $("#msgContent").val();
$.ajax({
url: 'message.php',
type: 'POST',
dataType: 'json',
data: {message: msgContent},
context: this,
success: function(result) {
alert('Message has been sent');
}
});
});
});
And your PHP this:
$message = $_POST['message'];
$result = false;
$sql="INSERT INTO MESSAGE_LOG (sender,recepient, message)
VALUES($viewer,$viewed,'$message')";
if (!mysqli_query($connection,$sql)) {
die('Error: ' . mysqli_error($connection));
}