Javascript working on console, but not onclick event - javascript

I'm fairly new with JavaScript, I'm trying to give access to users to update products stock for WooCommerce. I've made "Update" button to run the script, but it won't run, the page only refreshes. But when I execute the script from console, it works (eg. js_update_stock('20');)
I'm working by modifying existing plugin for WordPress, so I'm sorry if the codes are a bit scattered. If you need anything else, please let me know.
HTML side of things:
<input type="number" id="stock'. $postid . '" name="stock'. $postid .'" value="'. get_post_meta( $postid, '_stock', true ) .'">
<button class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>
I put this script on the same page:
echo '<script type="text/javascript">
function js_update_stock(product_id) {
var isnum = /^\d+$/.test(document.getElementById("stock" + product_id).value);
if(isnum){
if(confirm("Do you really want to update the stock of this product?")){
var data = {
action: \'update_stock\',
security: \'' . $ajax_nonce . '\',
id: product_id,
stock: document.getElementById("stock" + product_id).value
};
// since 2.8 ajaxurl is always defined in the admin header and points to admin-ajax.php
jQuery.post(ajaxurl, data, function(response) {
if(response == \'true\'){
location.reload(true);
}
});
}
else{
// do nothing
}
}
else{
alert("Please enter a valid stock quantity");
}
}
</script>';
AJAX Callback function:
add_action('wp_ajax_update_stock', 'update_stock_callback');
function update_stock_callback() {
check_ajax_referer( 'blahblah', 'security' );
if(isset($_POST['id'])){
$id = intval( $_POST['id'] );
$stock = intval( $_POST['stock'] );
wc_update_product_stock( $id, $stock );
echo 'true';
}
else{
echo 'false';
}
die(); // this is required to return a proper result
}
Any help is appreciated, as this has been bugging me for 2 days now. Thank you.

By default a button is of type submit so it's submitting your form, thats why your page refreshes.
You want to define button type as button so form doesn't submit.
<button type="button" class="button button-primary" style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;" onclick="js_update_stock(\''. $postid .'\')">'. __('Update','update_button') .'</button>

The page is refreshing because I guess the button you are using is in a form. So when you click on it, it will launch the request for the form and leave the page.
So to prevent that, you will just need to add the click event to your function and cancel it before the page has unload :
<button class="button button-primary"
style="margin-bottom: 3px; padding-left: 24px; padding-right: 24px;"
onclick="js_update_stock(event, \''. $postid .'\')">
'. __('Update','update_button') .'
</button>
And for javascript :
function js_update_stock(e, product_id) {
e.preventDefault();
// more code...
Javascript event prevent default on W3schools
I hope this solved your problem ;)

For most of the new browsers, default type of button element is "Submit".
That means, when click on it, your form will get submitted before calling your "onclick" function. Also, in your form you may not have specified action attribute, and that's why form is submitting to self.
You can specify type attribute for your button element to "button" specifically and it will now call to your "onclick" function.
For more information on button default type according to browser, visit :
What is the default button type?

Instead of button tag, you can use :
<a href='javascript:void(0);' id='updateBtn' class='btn btn-default'>Update</a>
$(document).ready(function () {
$('#updateBtn').on('click', function () {
// Make AJAX call here.
// Your logic will come here.
$.ajax({
url: 'Add url here',
data: 'Add data which is need to be update in json',
type: 'POST',
dataType: 'json',
success: successCallback,
complete: completeCallback,
error: errorCallback
})
});
var successCallback = function () {
// AJAX success callback
}
var completeCallback= function () {
// AJAX complete callback
}
var errorCallback= function () {
// AJAX error callback
}
});
NOTE: Also make sure you are not redirecting from backend(PHP) and just giving back response with statusCode.

Related

How to validate form created in bootbox message?

I am using bootbox.js. It allows user to create a form in it's 'message' part. But, I'd like to do some validation using jquery before I click submit button.
This is the bootbox:
bootbox.confirm({
title : "Choose Item:",
message :
"<?php
echo "<form id='f_item'>";
echo "<h3>Item: </h3><br/>";
foreach($item as $row_item){
echo "<input type='checkbox' name='item' class='cek_item' value='".$row_pic->item."' />";
}
echo "</form>";
?>",
buttons : {
cancel : { label: '<i class="fa fa-times"></i> Batal' },
confirm : { label: '<i class="fa fa-check"></i> OK'}
},
callback: function (result) {
//If OK button is pressed
if(result == true){
/*SENT FORM CODE*/
}
}
});
Without adding some validation form submit is working. But, I do not know where to put the validation script.
This is a test script
$(".cek_item").on('change',function(event){ alert($(this).val()+" is choosen"); });
where do I should put this script?
THe validation I'd like to do is:
If first item is first checked, the rest of the item is cannot be
checked.
If not the first item is first checked, then user cannot check the
first item.
You're kind of abusing the bootbox.confirm function, as it's not really meant to have form content. That being said, you would add your validation where you have /*SENT FORM CODE*/ - if you return false from that callback the modal won't close, so something like:
callback: function (result) {
//If OK button is pressed
if(result == true){
/*SENT FORM CODE*/
$("#f_item").validate();
if($("#f_item").valid()) {
/* form is valid */
}
else {
/* form is not valid */
return false;
}
}
}
This assumes you're also using jQuery Validation.

AJAX call not working - PHP, MySQL, jQuery/Ajax

I have the following problem:
What i'm trying to accomplish is:
User clicks on a submit/image type button
Ajax call handles the submit, calls another PHP script to update a record in a MySQL table, all without reloading the page ( obviously )
My PHP code is working fine without the AJAX, as it will reload and update the record. but somehow the ajax call is not working and/or returning any error.
My code:
$(function() {
$('#like_form').submit(function(event) {
event.preventDefault(); // Preventing default submit button
var formEl = $('#like_form');
var submitButton = $('input[type=submit]', formEl);
$.ajax({
async: true,
type: 'POST',
url: formEl.prop('action'),
accept: {
javascript: 'application/javascript'
},
beforeSend: function() {
submitButton.prop('disabled', 'disabled');
}
}).done(function(data) {
submitButton.prop('disabled', false);
$("#like").fadeOut();
$("#like").fadeIn();
});
});
});
<!-- LIKE een gebruiker -->
<form action="" id="like_form" method='POST' enctype="multipart/form-data">
<input onmouseover="this.src='img/heart2.png'" onmouseout="this.src='img/heart.png'" name='like' id="like" src='img/heart.png' type="image" />
</form>
my PHP (just in case):
<?php
include_once "dbconnection.php";
//if like button (submit button) clicked
if ($_POST){
$conn = DatabaseConnection::getConnection();
$sql = "UPDATE dating_members
SET likes = likes + 1
WHERE member_id = 3";
$stmt = $conn->prepare($sql);
$stmt->execute();
}
?>
I figured out what the problem is, Kind of silly I didn't notice but better late than never.
I had to 'include' the JS script at the end of my PHP page in order to catch my onsubmit function and therefore disable the default event a.k.a submit button submitting my form and page reload / POSTs to the other PHP file.
Everything is working fine now

Sending php generated form data via Ajax from Dialog box

Hi Guys any help on this? I have a dialog box triggered by a button click that calls my php script to generate a form which needs to be filled and submitted. I want to do the sending and conformation via Ajax. I have been recoding and researching for a few days but nothing on StackExchange or other websites help me with it.
Here's the code:
Dialog box snippet;
$k('#CreateTable').click(function(e){
e.preventDefault();
var Call = $k('#CreateTable').attr('value');//.attr('id');
var util = $k(this).attr('id');//.attr('id');
$k('#dialog').dialog({
autoOpen: false,
title: 'Running Utility for: '+Call,
modal: true,
width: 450,
close: function(event, ui) {
$k("#dialog").dialog('destroy');//event.target
}//END CLOSE
}).dialog('open');
var utility = { 'utility' : util };
$k.ajax({
type: "post",
url: "inc/runUtilities.php",
dataType: "html",
data: utility,
success: function(data) {
$k('#DlgTxt').html(data).fadeIn('slow');
}
});
//return false;
});//END DIALOG
The PHP snippet;
$show .= "<form id='cContact' name='cContact' method='post'>";
// action='".$_SERVER['REQUEST_URI']."'
$show .= '<table align="center" width="425" border="0">
';
$query = "SHOW COLUMNS FROM `".$_SESSION['WorkTable']."`";
if($output = mysqli_query($this->MySQLCxn->MySQLCxn, $query))
{
$columns = array();
while($row = mysqli_fetch_assoc($output))
{
if($row['Field'] == 'id') {}
else
$show .= '
<tr>
<td width="175"><div align="right">'.#$row['Field'].':</div></td>
<td width="155">
<input type="text" name="'.#$row['Field'].'" placeholder="'.#$row['Field'].'" />
</td>
<td width="115"> </td>
</tr>
';
}
}
$show .= '
<tr>
<td>Submit </td><td>
<button type="button" id="cContactSbmt" onclick="doSubmitForm(this); return false;" name="cContactSbmt" value="cContactSbmt">Create contact</button>
<!-- <input type="submit" class="button" value="Save" name="submit"> -->
</td> <td> </td>
</tr>
</table></form>
<div id="thanks">
</div>
';
And the JQuery that i am currently using trying to have it call my php to process the form being sent.
var $j = jQuery.noConflict();
(function($j){
$j(document).ready(function() {
$j("#cContactSbmt").click(function(e){//'click',
e.preventDefault();
alert('cContactSbmt clicked...');
$j.ajax ({
type:"POST",
url:"inc/runUtilities.php",
data: $j(this).serialize(),
success: function(msg){
$j("#thanks").html(msg)
$j(this).modal('hide');
},
error: function(){
alert("failure");
}
});
});
});
})($j);
For some reason its not working nothing showing up in the console as well.
again: i have a dialog box that gets populated via Ajax with a php generated from that needs to get submitted to another php script that is to process it and reply to the dialogs.
Any suggestions?
your php ist not outputting ("echoing") anything. you need to echo whatever you want to return to your ajax-call.
update: plus for debugging try to log the returned data in every success callback, for example:
success: function(data) {
console.log(data);
}
You may need to add an echo to the end of your php snippet..
echo $show;
This echoed html will then be available in your ajax function in the success callback function... as the variable "data"
success: function(data) {
$k('#DlgTxt').html(data).fadeIn('slow');
}
Also you may need to use jQuery .on() in your click function..to submit the form..
http://api.jquery.com/on/
$j("body").on("click", "#cContactSbmt", function(){
});
Hope this helps....
Hi Guys so I got it working with the following changes:
On the form;
<button id="cContactSbmt" onClick="doContactsCreate(\'#cContact\')" type="button" class="form-submit" name="cContactSbmt" value="cContactSbmt">Create contact</button>
I added the onclick method with a callback to a function doContactsCreate(\'#cContact\'), which has the id of the form passed to it.
function doContactsCreate(obj)
{
alert(obj+': cContactSbmt clicked...');
/* */
var frmData = $k(obj).serialize();
$k.ajax ({
type:"POST",
url:"inc/runUtilities.php",
data: frmData,
success: function(data){
$k("#thanks").html(data);
console.log(data);
$k(obj).modal('hide');
},
error: function(){
alert("failure");
}
});
}
I've just enclosed the JQuery code in this function definition and placed it outside the
(function($k){
$k(document).ready(function() {
//rest of JQuery code
})($k);
Don't know why but i think that was the main problem

Update database with html link click using ajax php mysql

I've read through a number of similar questions and tried my hand at putting it to work on my website, but it is not working (when you click the link there is no response on the console and the database is not updated).
Here's what I want to do: I want users to rate a comment +1 by clicking an icon next to the comment. I want that to update my mysql comment_table column called rating with rating+1. When I do it without AJAX (ie, just set the form action to a php page?id=10) it works fine. I can't get the AJAX to update the database though.
My main page with the comment:
<span class="glyphicon glyphicon-chevron-up"></span>
The javascript below that link:
<script type="text/javascript">
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
rating: rating,
id: <?php echo $thisperspective_row['id']; ?>,
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
</script>
and my rating.php file is
<?php
require_once('connectiontodatabase.php');
/* simple comment up and down voting script */
$mode = $_GET['mode'];
$rating = $_GET['rating'];
$id = $_GET['id'];
if ($mode=="vote")
{
// The name of the
$cookie = "nameofmycookie".$id;
if(isset($_COOKIE[$cookie]))
{
echo '<div class="alert alert-warning"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button> Sorry You have already rated this comment within the last 14 days.</div>';
}
else
{
$expiry = 1209600 + time(); // 14 day expiry
setcookie ($cookie, "voted", $expiry);
mysql_query ("UPDATE comment_table SET rating = rating+$rating WHERE id=$id", $connection);
}
}
?>
The php runs fine and all the variables are listed properly when I view the source. However, when I click the link, there is no response at all and the console does not output the response. What am I doing wrong? Thanks in advance!
Firstly you should change the way you are detecting the click event. Check out this fiddle. Then secondly you need to pass all the variables through in one JSON string using the data option. Your code should look something like this:
<span class="glyphicon glyphicon-chevron-up clickable"
data-rating="1"
data-id="<?php echo $thisperspective_row['id']; ?>"></span>
<script type="text/javascript">
$('.clickable').on('click', function() {
var data = {
mode: "vote",
rating: $(this).data('rating'),
id: $(this).data('id')
};
$.ajax({
type: 'GET',
url: 'rating.php',
data: data,
success: function(response) {
console.log(response);
}
});
});
</script>
First off all, check that you are loading jQuery, then use this code
function updateRating(rating, id){
$.ajax({
type: "GET",
url: "rating.php",
mode: "vote",
data: { rating: rating, id: id },
success: function(response) {
console.log(response);
}
});
return false; // Prevent the browser from navigating to the-script.php
};
is working for me.
note that I removed ` inside Ajax, since you are already sending the params in the function, also to send params you have to use data:, you can see more examples here Ajax jQuery

jQuery Validation Plugin: same form, different validation submitHandler

I am using a single form in two different scenarios - Create and Edit.
I do something like
<?php
if($status == 'new')
echo '<button id="btnSubmit" type="submit" class="btn">Submit!</button>';
else
echo '<button id="btnEdit" type="submit" class="btn">Edit!</button>';
?>
What I want to achieve on my javascript end is to validate the form and call the correct web service according to which button is pressed. I am using the jQuery Validation Plugin found here.
Javascript
$('#myForm').validate({
submitHandler: function(data) {
$.ajax({
url: "service1.php"
...... other AJAX stuff ..........
});
}
}
$('#btnSubmit').click(function() {
// call service1.php
});
$('#btnEdit').click(function() {
// call service2.php
});
The method for validate can be a single function and you can set a flag(For example you will get an id in the edit page) to identify edit page or add page. So that you can check the flag in submit handler and submit the form to where it needs to be submitted. I'm not familiar with PHP and i hope this might help you.
Based on Marikkani's suggestion, I have implemented the below and it works. Hope it helps someone with a similar problem using Javascript and PHP.
In my form file I used a hidden div to store the type (new or edit).
<input type="hidden" id="type" value="<?php echo $type; ?>" />
Thereafter, in my javascript file I retrieve this value and check before calling the respective ajax.
$('#resForm').validate({
submitHandler: function(form) {
var type = $('#type').val();
if(type == 'new') {
$.ajax({
url: "service1.php"
.... other AJAX stuff
});
} else { // type is edit
$.ajax({
url: "service2.php"
.... other AJAX stuff
});
}
}
});

Categories

Resources