I am beginner in javascript and ajax and I just cant figure out how to display a message on some condition.
Lets say a user can increase or decrease the quantity of the product he wants to buy. I have made that (not saying it was easy). But if the product is out of stock he cant increase the quantity anymore. How can I show that in the message. For example if a user tries to increase the quantity, but the product is out of stock I want to display the message below on the same ajax call.
This is the controller:
public function addQuantityAction( Request $request ) {
$response = new JsonResponse();
$requestData = $request->request->all();
$productid = $requestData['product'];
$quantity = $requestData['quantity'];
/** logic*/
$em = $this->getDoctrine()->getManager();
$product = $em->getRepository('MpShopBundle:Product')->find($productid);
$qtyAvailable = $product->getStockAvailable();
$session = $this->getRequest()->getSession();
$cart = $session->get('cart', array());
if ( $qtyAvailable > $cart[ $productid ] ) {
$cart[ $productid ] = $cart[ $productid ] + 1;
$qtyAvailable = $qtyAvailable - 1;
$response->setData(array('success'=>true,'message'=>'Qunatity increased','amount' => $cart[ $productid ]));
$session->set('cart', $cart);
} else {
$response->setData(array('success'=>false,'message'=>'Out of stock'));
}
return $response;
}
The Ajax:
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
And the twig:
<div class="input-append">
<input class="span1" style="max-width:34px" placeholder="{{ key }}" value="{{ item }}" id="appendedInputButtons" size="16" type="text" data-id="{{ key }}"/>
<i class="icon-minus"></i>
<i class="icon-plus"></i>
<button class="btn btn-danger" type="button"><i class="icon-remove icon-white" style="color:white"></i></button>
<p> display message here </p>
</div>
You can also add class depands on success or error status of operation.
Ajax
$(document).ready(function () {
$(document).on('click', '.add', function (e) {
$this = $(this);
$.ajax({
type: 'POST',
url: 'add',
dataType: 'JSON',
data: {product: $this.parent('.input-append').find('input').data('id'),quantity: $this.parent('.input-append').find('input').val()},
success: function (data) {
if(data.success == false){
alert('error')
}else{
if(data.message != 'undefined') {
$('#ajax_response--message').html(data.message)
}
$('.test').load(" .test");
$('.sidebar').load(" .sidebar");
$('.top').load(" .top");
}
}
});
<div class="input-append">
Twig
<p id="ajax_response--message"> display message here </p>
</div>
Related
To preface this question, I have a basic understanding of PHP and AJAX. I was asked to design a simple form that would ask the user to select one of two car manufacturers, which would return all models of the selected make from the multidimensional array created in the data.php file. So far this is what I was able to come up with:
index.php
<body>
<form id="form">
<label for="make">
Make
<select name="make" id="make">
<option value="" selected="selected">None</option>
<option value="Ford">Ford</option>
<option value="BMW">BMW</option>
</select>
</label>
<input name="submit" value="Submit" type="submit" id="submit">
</form>
<h2>Models:</h2>
<div id="results"></div>
</body>
data.php
<?php
$data = array(
array('make' => 'Ford', 'model' => 'Fiesta'),
array(''make' => 'Ford', 'model' => 'Focus'),
array('make' => 'Ford', 'model' => 'Mustang'),
array('make' => 'BMW', 'model' => '320'),
array('make' => 'BMW', 'model' => 'X3'),
array('make' => 'BMW', 'model' => 'X5'),
);
?>
ajax.php
<?php
require_once( 'data.php' );
$myJSON = json_encode($data);
echo $myJSON;
?>
function.js
$(document).ready(function() {
"use strict"
console.log("Document loaded...");
$('#submit').click(function( event ) {
event.preventDefault();
console.log("Submit button was clicked");
run_ajax();
});
var run_ajax = function() {
var results = $( '#results' );
var formData = $( '#make' );
$.ajax({
type: 'get',
url: 'ajax.php',
data: formData,
dataType: 'json',
beforeSend: function() {
console.log("Before Send");
},
success: function( response ) {
console.log("Success");
},
});
var xmlhttp = new XMLHttpRequest();
var carModel;
xmlhttp.onreadystatechange = function() {
myObj = JSON.parse(this.responseText);
for (x in myObj) {
console.log("testing");
carModel += myObj[x].model + "<br>";
document.getElementById("results").innerHTML = carModel;
};
};
};
});
I am able to get the Success message to display in the console but I cannot get anything to display in the 'results' div in index.php. Does anyone know where I am going wrong? I have searched related topics but couldn't find anything regarding pulling data from a local file. Thanks in advance for any and all help!
Got it working now, thanks for the help everyone!
function run_ajax(make) {
var results = $( '#results' );
var msg = "";
$.ajax({
type: 'get',
url: 'ajax.php',
data: make,
dataType: 'json',
beforeSend: function() {
console.log("Before Send");
},
success: function( response ) {
console.log("Success!");
for(var x in response) {
if(response[x].make == make) {
msg += response[x].model + "<br>";
}
}
if(msg == "") {
msg = "No matches found!";
}
document.getElementById("results").innerHTML = msg;
},
});
};
I have a form in a modal:
<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal">
Add user
</button>
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog" role="document">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Modal title</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post" id="saveperson">
<label for="newcat">Project Name</label>
<input type="text" name="newcat" value="">
<label for="description">Description</label>
<input type="text" name="description" value="">
<input type="submit" name="user" value="Submit">
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
On submit I run the js:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
And then this should run in process.php
<?php
header ( "Content-Type: application/json");
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
// Category added successfully
die ( json_encode ( array ( "success" => 1)));
} else {
// Error while creating new category
die ( json_encode ( array ( "success" => 0)));
}
} else {
// That category already exists
die ( json_encode ( array ( "success" => 0)));
}
?>
But after the submit, nothing happens and the data isn't saved in the db, meaning isn't working. If I use this php tho in a standard php without ajax, it works and saves the data in the db
<?php
header ( "Content-Type: application/json");
if( isset( $_POST['user'] ) ) {
if( !empty( $_REQUEST['newcat'] ) ) {
$cat_ID = get_cat_ID( sanitize_title_for_query($_POST['newcat']) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = sanitize_text_field($_POST['newcat']);
$cat_desc = sanitize_text_field($_POST['description']);
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
wp_insert_category( $my_cat );
}
}
}
?>
There is an error in the browser console:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
else {
$('.modal-body').html("Error!");
}
}
});
event.preventDefault();
});
});
Notice the
else {
$('.modal-body').html("Error!");
}
Error:
Uncaught SyntaxError: Unexpected token else
Remove the else block, it should work
It should be:
$(document).ready(function() {
$('#saveperson').submit(function(event) { //Trigger on form submit
var postForm = { //Fetch form data
'name' : $('input[name=newcat]').val(),
'desc' : $('input[name=description]').val() //Store name fields value
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
});
Here is the fiddle
Did u try this?
$( "#saveperson" ).submit(function( event ) {
let form = $( this );
let formData = new FormData(form[0]);
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'process.php',
data : formData,
success : function(data) {
$('.modal-body').html("Done!");
}
});
event.preventDefault();
});
The issue was I was running wordpress standard functions from an external php file and it doesn't work. In order to achieve what i was doing, I had to use
function.php and wordpress ajax
add_action( 'wp_footer', 'ajax_Person' );
function ajax_Person() { ?>
<script type="text/javascript">
jQuery("#createCat").on("click", function(e){
e.preventDefault();
person();
});
function person(){
jQuery.ajax({
url: '<?php echo admin_url('admin-ajax.php'); ?>',
type: 'post',
data: { action: 'data_person', catName: jQuery('#newCat').val(), catDesc: jQuery('#descRiption').val() },
success: function(data) {
}
});
}
</script>
<?php }
add_action('wp_ajax_data_person' , 'data_person');
add_action('wp_ajax_nopriv_data_person','data_person');
function data_person(){
$catname = $_POST['catName'];
$catdesc = $_POST["catDesc"];
$cat_ID = get_cat_ID( sanitize_title_for_query($catname) );
// Check if category exists
if($cat_ID == 0) {
$cat_name = $catname;
$cat_desc = $catdesc;
$cat_slug = sanitize_title_with_dashes($cat_name);
$my_cat = array(
'cat_name' => $cat_name,
'category_description' => $cat_desc,
'category_nicename' => $cat_slug,
'category_parent' => 0
);
if( wp_insert_category( $my_cat ) ) {
echo 'Category added successfully';
} else {
echo 'Error while creating new category';
}
} else {
echo 'That category already exists';
}
}
I have this shopping cart wherein I can add or subtract the quantity of a specific item. The problem is I don't know how to determine if the user has pressed the plus button or the minus button.
HTML code of the plus/minus
<td>
<div class="input-group" style="width: 100px !important;">
<span class="input-group-btn">
<button class="btn btn-danger btn-minus" type="button">-</button>
</span>
<input class="form-control table-shopping-qty" type="text" id = "<?php echo $cartrow['id']?>" value="<?php echo $cartrow['qty']?>" style="padding-left:5px;text-align: center;"/>
<span class="input-group-btn">
<button class="btn btn-success btn-plus" type="button">+</button>
</span>
</div><!-- /input-group -->
</td>
AJAX Function
function updateShoppingCart(){
var productid = $(".table-shopping-qty").attr("id");
dataString = {productid: productid};
$.ajax({
type: "POST",
url: "<?php echo base_url(); ?>"+"listproductscontroller/editcart_item",
data: dataString,
cache: false,
success: function(){
swal('Success!', 'Cart updated!', 'success');
}, error: function(){
swal('Oops!', 'Something went wrong. Please try again later', 'error');
}
});
}
Controller
public function editcart_item(){
$id = $this->input->post('productid');
if($this->session->userdata('cartsession')){
$cartsession = $this->session->userdata('cartsession');
foreach($cartsession as $row){
if($row['id'] == $id){
$updated = array('id'=>$row['id'], 'qty'=>$row['qty'] - 1);
}else{
$updated = array('id'=>$row['id'], 'qty'=>$row['qty']);
}
}
$this->session->set_userdata('cartsession', $updated);
}
if($this->session->userdata('cartsession')!=NULL){
if($this->cartdata = $this->ProductModel->getProductToCart($this->session->userdata('cartsession'))){
$this->session->set_userdata('globalcart', $this->cartdata);
}
}
}
load url helper in controller.using $this->load->url('url');.Then
function updateShoppingCart(){
var productid = $(".table-shopping-qty").attr("id");
dataString = {productid: productid};
$.ajax({
type: "POST",
url: "<?php echo base_url('listproductscontroller/editcart_item');?>",
data: dataString,
cache: false,
success: function(data){
alert("success");
}, error: function(){
alert("failed");
}
});
Don't forget to set
$_config['base_url'] ="your_domain_name";
i have this ajax form validation code igniter. my view is something like this
<?php
echo form_open('Provinces/create',array('id' => 'form-user'));
?>
<label for="PROVINCE" class="col-sm-2 control-label col-sm-offset-2">Province Name:</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="PROVINCE" name="PROVINCE" value = "<?= set_value("PROVINCE"); ?>">
</div>
<button class="btn btn-info fa fa-save" type="submit">  Save</button>
<a href = '<?php echo base_url().'Provinces/index'; ?>' class = 'btn btn-danger fa fa-times-circle'>  Cancel</a>
<?php
echo form_close();
?>
and i have this javascript
<script>
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
url = "<?php echo site_url('Provinces/ajax_add')?>";
// ajax adding data to database
$.ajax({
url : url,
type: "POST",
data: $('#form').serialize(),
dataType: "JSON",
success: function(data)
{
alert('success');
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error adding / update data');
}
});
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
</script>
i have found this code on google and just customized it. but the problem is, i am not that familiar with ajax, the part where the form validation fails, work perfectly fine, but when it is succes, even though it shows alert('success'); it doesnt add the value in the database. i need to finish this projects in a few weeks. please help.
here is where i get the validations,
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
also here is my ajax_add
public function ajax_add()
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}
and here is my model,
public function save($data)
{
$this->db->insert($this->table, $data);
return $this->db->insert_id();
}
i have solved it. just did put
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
into my controller, which makes my controller
public function create(){
$data = array('success' => false, 'messages' => array());
$this->form_validation->set_rules('PROVINCE','Province Name','trim|required|max_length[30]|callback_if_exist');
$this->form_validation->set_error_delimiters('<p class="text-danger"','</p>');
if($this->form_validation->run($this)){
$data['success'] = true;
$data = array(
'PROVINCE' => $this->input->post('PROVINCE'),
);
$insert = $this->Provinces_Model->save($data);
echo json_encode(array("status" => TRUE));
}else{
foreach ($_POST as $key => $value) {
# code...
$data['messages'][$key] = form_error($key);
}
}
echo json_encode($data);
}
and my javascript
$('#form-user').submit(function(e){
e.preventDefault();
var me = $(this);
// perform ajax
$.ajax({
url: me.attr('action'),
type: 'post',
data: me.serialize(),
dataType: 'json',
success: function(response){
if (response.success == true) {
// if success we would show message
// and also remove the error class
$('#the-message').append('<div class="alert alert-success">' +
'<span class="glyphicon glyphicon-ok"></span>' +
' Data has been saved' +
'</div>');
$('.form-group').removeClass('has-error')
.removeClass('has-success');
$('.text-danger').remove();
// reset the form
me[0].reset();
$('.alert-success').delay(500).show(10, function() {
$(this).delay(3000).hide(10, function() {
$(this).remove();
});
})
}else{
$.each(response.messages, function(key, value) {
var element = $('#' + key);
element.closest('div.form-group')
.removeClass('has-error')
.addClass(value.length > 0 ? 'has-error' : 'has-success')
.find('.text-danger')
.remove();
element.after(value)
});
}
}
});
});
You dont't need to use uppercase when accessing your controller
just use
url = "<?php echo site_url('provinces/ajax_add')?>";
Validation the request data before inserting
try
public function ajax_add()
{
$response = array(
'success' => false
) ;
$this->load->library('form_validation');
// add your validation
$this->form_validation->set_rules('PROVINCE', 'PROVINCE', 'required');
if ($this->form_validation->run() == FALSE)
{
$data = array(
'PROVINCE' => $this->input->post('PROVINCE')
);
$insert = $this->Provinces_Model->save($data);
if($insert){
$response['success'] = TRUE ;
$response['message'] = 'Record created successfully' ;
}
else{
$response['message'] = 'Unable to create record' ;
}
}
else
{
$response['message'] = 'Invalid data' ;
}
echo json_encode($response);
}
Then check for the 'message' index in your ajax response in the javascript code
This will give an idea of where there is problem, whether its from the
view or
controller or'
Model
I'm using this setup to show if light is turned on or off:
http://www.jquery2dotnet.com/2012/11/jquery-light-switch-on-off-using-css3.html
How can i choose wich switch state to start?
As of now I have a lightvalue in my database, 1 = on 0 = off. I use sql to retrieve this value and load the appropriate light bulb.
But how would i do this with the switch? I don't have switch1 and switch2 so i can load the one i want based on lightvalue.
here is the code:
light.js
var lightVal = document.getElementById("light-bulb2");
function getLightValue(r) {
var lightValue;
$.ajax({
url: 'Database/checklight.php',
type: "POST",
data: {room: r},
success: function(data) {
data1 = JSON.parse(data);
$.each(data1, function(key, val) {
lightValue = val.light;
lightVal.style.opacity = lightValue;
});
},
async: false
});
}
function updateLight(val, rom) {
$.ajax({
url: 'Database/updateLight.php',
type: "POST",
data: {light: val, room: room},
success: function(data) {
data2 = JSON.parse(data);
if (data2 < 1) {
alert("Not Updated");
}
},
async: false
});
}
light.php
<div id="temptre">
<div id="light-bulb" class="off ui-draggable" >
<div id="light-bulb2" style="opacity: 0">
<script src="JS/light.js">
</script>
</div></div>
<div class="cube-switch">
<span class="switch">
<span class="switch-state off">Off</span>
<span class="switch-state on">On</span>
</span>
</div>
</div>
<script>
getLightValue(<?php echo $_SESSION['sess_room']; ?>);
$('.cube-switch .switch').click(function() {
if ($('.cube-switch').hasClass('active')) {
$('.cube-switch').removeClass('active');
$('#light-bulb2').css({'opacity': '0'});
updateLight(0, <?php echo $_SESSION['sess_room']; ?>);
} else {
$('.cube-switch').addClass('active');
$('#light-bulb2').css({'opacity': '1'});
updateLight(1, <?php echo $_SESSION['sess_room']; ?>);
}
});
</script>
If you want to make switch work, then you need to trigger the click event, so that it can be switch on and off (based on value).
// call(trigger) click event on success
function updateLight(val, rom) {
$.ajax({
url: 'Database/updateLight.php',
type: "POST",
data: {
light: val,
room: room
},
success: function (data) {
data2 = JSON.parse(data);
if (data == 1) {
$('.cube-switch .switch').trigger('click', [{
forceStart: true
}]);
} else {
$('.cube-switch .switch').trigger('click', [{
forceStart: false
}]);
}
},
async: false
});
}
// change your click event to handle the passed argument
$('.cube-switch .switch').click(function (e, data) {
if (typeof data !== 'undefined') {
if (data.forceStart) {
// remove the active class, so that it can add the active class later to match switch on
$('.cube-switch').removeClass('active');
} else {
$('.cube-switch').addClass('active')
}
}
if ($('.cube-switch').hasClass('active')) {
$('.cube-switch').removeClass('active');
$('#light-bulb2').css({
'opacity': '0'
});
updateLight(0, <? php echo $_SESSION['sess_room']; ?> );
} else {
$('.cube-switch').addClass('active');
$('#light-bulb2').css({
'opacity': '1'
});
updateLight(1, <? php echo $_SESSION['sess_room']; ?> );
}
});
JSFIDDLE: http://jsfiddle.net/4rkQZ/152/
I'm not very good with php, but give div.cube-switch a class of 'active' if it's on, and remove the inline opacity style (tidy up the php by all means!)
<div href="" class="cube-switch <?php if ($on) { echo ' active'; } ?>">
<span class="switch">
<span class="switch-state off">Off</span>
<span class="switch-state on">On</span>
</span>
</div>
<div id="light-bulb" class="off ui-draggable">
<div id="light-bulb2" <?php if (!$on) { echo 'style="opacity:0"'; } ?>></div>
</div>