Messages in $.ajax function - javascript

I have a ajax function in my view file looks like this:
...
<div id="success" class="hidden">
<?php echo TbHtml::alert(TbHtml::ALERT_COLOR_SUCCESS, 'Maraqlar qeydə alındı.'); ?>
</div>
<br>
<div id="error1" class="hidden">
<?php echo TbHtml::alert(TbHtml::ALERT_COLOR_ERROR, 'Yalnışlıq baş verdi. Əməliyyatı icra etmək üçün ən azı bir maraq dairəsi seçilməlidir.'); ?>
</div>
<input type="button" id="checkbox" value="checkbox" class="btn btn-success" />
...
$("#checkbox").click(function() {
$.ajax({
type: 'POST',
url : '<?=Yii::app()->baseUrl;?>/ideyalar/maraglaridaxilet',
cache: false,
data: 'i='+$i+'&idm='+$idm+'&ids='+$ids,
// beforeSend:function(data){
// location.reload();
// },
complete:function(data){
$("#error1").addClass("hidden");
location.reload(); // where I must put this line ?
$("#success").removeClass("hidden");
},
error:function(data){
$("#error").removeClass("hidden");
}
});
}
...
There is no problem everything working correctly. But I want to do this:
if everything OK, first page must reload, and then $("#success").removeClass("hidden");.
P.S: when I remove comment from location.reload(); firstly it shows success message box, and then reload. But I want to do this other way round.
How can I solve this problem?
Thanks.

Related

Why jQuery Code is not working in Magento

The code is working fine but the problem is that when I add this code to Magento it the Javascript doesn't work.
Let me explain a little bit about code. There is a simple form that has only one input field which is intended to enter phone numbers. There is another file called form.php that has all the PHP code. Whenever someone enters a phone number in the input field the PHP saves that number in the CSV file which is created in the backed. I don't want to redirect the form to another page, I just wanted a small message to appear in the same page without page reloading or redirecting.
For that, I added a jQuery code and it was working fine but the code was created to add it on Magento but when I add this code to Magento then the only the Javascript code doesn't work. Does anyone have a solution for this?
$(function() {
$("#myform").on("submit", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
$("#message").hide();
$("#response").html(data);
}
});
});
});
<form id="myform" action="https://www.tawakkalfabric.com/form.php" method="post">
<div class="block-content">
<div class="form-subscribe-header">
<label for="newsletter">Sign Up for Our Newsletter:</label>
</div>
<div class="input-box">
<input type="tel" name="name" placeholder="Sign Up for Our WHATSAPP" />
</div>
<div class="actions">
<button type="submit" class="button"><span><span>Subscribe</span></span></button>
</div>
<div id="message"></div>
<div id="response"></div>
</div>
</form>
The code below is in form.php:
<?php
$email = $_POST['email'];
$name = $_POST['name'];
$data = $name.",".$email;
$file = "sample.csv";
file_put_contents($file, $data . PHP_EOL, FILE_APPEND);
print "<h1 align=center>Thank you for submitting your email address!</h1>";
?>
<html>
<head>
<title>ThankYou Page</title>
</head>
<body>
<h1>GO BACK</h1>
</body>
try following code
<script>
$(document).on("submit", "#myform", function(e) {
e.preventDefault();
$.ajax({
url: $(this).attr("action"),
type: 'POST',
data: $(this).serialize(),
beforeSend: function() {
$("#message").html("sending...");
},
success: function(data) {
$("#message").hide();
$("#response").html(data);
}
});
});
</script>
Magento (similar to WordPress) doesn't automatically allow for the $ alias, so you will need to include the code with the jQuery dependencies and then either create the alias or change the $ to jQuery.
See https://magento.stackexchange.com/questions/97184/how-to-use-jquery-library-in-magento-2

Show error in modal window, when something went wrong

I need some help. I need to show up the error, when something went wrong in my modal window. Right now, is just closing, also when there are error. I tried to find some Ajax and Javascript to solve the problem, but I can’t get it to work well. Can someone help me and thanks for your help?
if($result->num_rows == 0) {
$this->errors[] = "User not fund";
}else{
Modal window
<!-- Modal -->
<div class="modal fade" id="resetPassword" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div style="background-color:#3a3a38;" class="modal-content">
<div class="modal-header">
<h4 style="color:#fff" class="modal-title">Nulstill adgangskode</h4>
</div>
<div class="modal-body">
<form role="form" action="index.php" method="post">
<div class="form-group">
<label class="sr-only"
for="email_forgot">Email</label>
<input type="text" name="email_forgot"
placeholder="email..." class="form-username form-control" id="form-username">
</div>
<input style="margin-left:auto;margin-
right:auto;" data-backdrop="static" data-keyboard="false" class="btn-lg btn-
default btn-block" type="submit" value="send" name="forgot">
</form>
<?php
if (isset($user)) {
if ($user->errors) {
foreach ($user->errors as $error) {
echo '<a style="color:red">'.$error.'</a>';
}
}
if ($user->messages) {
foreach ($user->messages as $message) {
echo '<span style="color:red">'. $message.'</span>';
}
}
}
?>
</div>
</div>
</div>
Submit the form with ajax and display the error with javascript not with php. Now your page reload and you loss the data.
<script
src="https://code.jquery.com/jquery-2.2.4.min.js"
integrity="sha256-BbhdlvQf/xTY9gja0Dq3HiwQF8LaCRTXxZKRutelT44="
crossorigin="anonymous"></script>
$('form').on('submit', function(event){
event.preventDefault();
var formData = $("form").serializeArray();
$.ajax({
url: "index.php",
type: "POST",
data: formData,
dataType: 'json',
success:function(data){
$('body').html('<h1>Thank You</h1>');
},
error:function(){
$('body').html('<h1>Error</h1>');
}
});
});
There are two different options when it comes down to posting your data; you could ajax-validate the data (which means that you'd validate the content in a different file), or you'd ajax-submit the data (which means that you'd validate and use the data in a different file).
I'd suggest ajax-submitting, seeing as that would suit te needs of your form.
<script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
var $form = $('#resetPassword form');
$form.submit(function(event) {
event.preventDefault();
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
success: function ( response ) {
if(response != "") {
alert("Errors: " + response);
} else {
alert("Password reset!");
}
}
});
});
</script>
For it to work you'd have to use the METHOD attribute on the form to point to a processing file, which you'll have to create (for example; ajax-reset-password.php). In there just print all errors, if there are any. If no errors occurred, just don't print anything. The javascript above will show the message "Password reset!".

delete record from database without refreshing

I have an code where it is supposed to delete the data without refreshing. the delete process works but i have to refresh to to remove the data.
heres my code please help me
Ajax:
$(function () {
$(".trash").click(function () {
var del_id = $(this).attr("id");
var info = 'id=' + del_id;
if (confirm("Sure you want to delete this post? This cannot be undone later.")) {
$.ajax({
type: "POST",
url: "delete.php", //URL to the delete php script
data: info,
success: function () {}
});
$(this).parents(".record").animate("fast").animate({
opacity: "hide"
}, "slow");
}
return false;
});
});
Here's my html:
<td style="padding-left: 23px">
<img class="photo" data-toggle="modal" data-target="#gallery<?php echo $photo; ?>" src="<?php echo $r1['photo']; ?>" />
<div class="hotel">
<button class="trash" id="<?php echo $r1['photo_id']; ?>" > <span class="glyphicon glyphicon-remove" aria-hidden="true"></span></button>
</div>
</td>
If I hover the button to the image the .trash button will appear and if I click it the image must be deleted. help me please.
You can give a data image id attr to parent tr,
<tr data-image-id="<?php echo $r1['photo_id']; ?>">
After successful delete process (in your ajax success function) you can run code below.
$("tr[data-image-id="+del_id+"]").remove();
Your code works, maybe do you need show the complete html, or at least the classes ".record" to analyze the "error"
No need to add extra attribute for ID in table row(TR).
$('.glyphicon-remove').on('click',function() {
$(this).closest( 'tr').remove();
return false;
});
Try This:
function delete_value(id)
{
if(confirm('Are you sure you want to delete this?'))
{
// ajax delete data from database
$.ajax({
url : "<?php echo site_url('yoururl/del')?>/"+id,
type: "POST",
success: function(data)
{
$("tr[id="+id+"]").remove();
},
error: function (jqXHR, textStatus, errorThrown)
{
alert('Error deleting data');
}
});
}
}
<button class="btn btn-danger" onclick="delete_value(<?php echo $row->id;?>)"><i class="glyphicon glyphicon-remove"></i></button>
<!--- add tr id --->
<tr id="<?php echo $row->id; ?>">

Ajax not working properly when I tried to call it on same page again

I have a PHP page which has two sections (top and bottom). The top section has a table where I have options to Edit the data.
Once the Edit button is pressed, the content is loaded at the bottom of page and the user can change the data.
Here is part of my PHP page:
<div id="product_entry_<?php echo $id?>" class="product_entry_<?php echo $id?>">
<tr>
<td><font size=2px><?php echo $date?></font></td>
<td><font size=2px><?php echo $ProductName?></font></td>
<td><font size=2px><?php echo $Category.' / '.$SubCategory?></font></td>
<td><font size=2px><?php echo $MRP.' / '.$Price?></font></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="DirectPromoteSubmit(<?php echo $id?>)">Promote</button></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="RePromoteSubmit(<?php echo $id?>)">Edit</button></td>
<td><button type="submit" class="btn btn-primary btn-xs" style="padding:2px 2px;font-size: 9px;line-height: 10px;" onClick="DelPromoteSubmit(<?php echo $id?>)">X</button></td>
</tr>
</div>
<!-- page where data is loaded -->
<div class="box box-warning" id="RePromoteReplace">
....some html content here...
</div>
Here is my Javascript:
function RePromoteSubmit(id){
//alert('got into Edit Promotions');
var dataString = "id="+ id;
alert(dataString);
if(dataString=='')
{
alert('Some Problem Occurred, Please try Again');
}
else
{
//alert('into post');
$.ajax({
type: "POST",
url: "SellerPanel/post_repromote.php",
data: dataString,
cache: false,
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").replaceWith(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
});
}return false;
}
Here is my PHP page which loads the bottom section - post_repromote.php:
<?php
include("../dbconnection.php");
include("session.php");
if(!isset($_SESSION))
{
session_start();
}
$id=$_POST['id'];
$query1=mysqli_query($con,"select promotiondata from sellerpromotions where id=$id");
while($row=mysqli_fetch_array($query1))
{
.....some code here.....
}
?>
<div class="box box-warning">
<div class="box-header">
<h3 class="box-title">Fill Product Details</h3>
</div><!-- /.box-header -->
<div class="box-body">
<!-- <form role="form " name="PromoteForm"> -->
<div>
<!-- text input -->
<table class="table">
....some data here from query..
</table>
<div class="box-header with-border">
<h3 class="box-title">Upload your Product Image</h3>
</div><!-- /.box-header -->
<div class="box-body no-padding">
<div id='preview'>
<?php if ($uploadid){ ?>
<img src=<?php echo "SellerPanel/uploads/".$imagename?> id="<?php echo $uploadid?>" alt="User Image" class='preview' style='width:340px;height:200px;border-color:black'/>
<?php }
?>
</div>
<?php
include ("index_photo.php");
?>
<!-- <span class="users-list-date">Yesterday</span> -->
</div><!-- /.box-body -->
<div class="box-footer">
<button type="submit" class="btn btn-primary" onClick="PromoteSubmit()">Promote</button>
</div>
</div>
</div><!-- /.box-body -->
</div><!-- /.box -->
<?php }
?>
The problem I'am facing:
I'am able to load the data when I press the Edit button first.
When I press it again, I'm not able to load the new data unless I refresh the page and click the Edit button again.
I tried to read the id in JS and printed it, I found that id is being passed correctly.
Any help would be very much appreciated.
Thanks in advance!
JS after using solution:
function RePromoteSubmit(id){
//alert('got into Edit Promotions');
var dataString = "id="+ id;
alert(dataString);
function getRandomInt() {
return Math.floor(Math.random() * Math.pow(10,6));
}
//var url = "SellerPanel/post_repromote.php?"+getRandomInt();
//alert ("url is: "+ url);
if(dataString=='')
{
alert('Some Problem Occurred, Please try Again');
}
else
{
//alert('into post');
$.ajax({
type: "POST",
url: "SellerPanel/post_repromote.php?rnd="+getRandomInt();
data: dataString,
cache: false,
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").replaceWith(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
});
}return false;
}
Try changing your callback to use .html() instead of replaceWith(): (in your original code)
success: function(html){
//$("#tweet").val('');
//$("#preview").hide();
$("#RePromoteReplace").html(html);
alert('Product Successfully Loaded!!! Edit(Optional) & Click Promote Button in bottom section')
}
I also recommend changing your selector to a class instead of an ID, you can do this by just adding an extra class in your HTML:
<div class="box box-warning promoReplace" id="RePromoteReplace">
and then updating the selector in your success callback:
$(".promoReplace").html(html);
Sidenote: For debugging, its usually easier to use console.log() instead of alert() (when using ajax, you usually would have the console open anyway)
Your AJAX response is getting cached by the browser due to some server setting or page header. Easiest way to disable this is to append some randomly generated parameter to your url every time you send a request.
The function getRandomInt will generate a 6 digit random number. If you want to have more/less digits, change the second argument passed to Math.pow.
function getRandomInt() {
return Math.floor(Math.random() * Math.pow(10,6));
}
//then, inside your ajax function, use:
url: "SellerPanel/post_repromote.php?rnd="+getRandomInt(),

inserting an ajax response into div

First time AJAX attempt.....
I am attempting to update a based on a selection made with a button.
I am currently just alerting the ID back, as that is all I can figure out what to do.
Is it possible to put the file my_page.php into the div with class "populated_info"?
Then when I press a different button, the page will function will run again, and populate the div with the new result. I have the my_page.php already built and running based on the ID, just can't get it to render in the correct place.
HTML:
<form name="gen_info">
<div class="body">
<div class="row">
<div class="col-md-2">
<table width="100%" class="border_yes">
<tr>
<td>
Last Name, First Name
</td>
</tr>
<?php
$result = mysqli_query($conn,"SELECT * FROM general_info");
while($row = mysqli_fetch_array($result))
{
$CURRENT_ID = $row['ID'];
$firstName = $row['firstName'];
$lastName = $row['lastName'];
?>
<tr>
<td>
<button type="button" class="btn btn-default custom" onclick="function1('<?php echo $CURRENT_ID;?>')"><?php echo $lastName.', '.$firstName; ?></button>
<!-- button that will run the function -->
</td>
</tr>
<?php
}
?>
</table>
</div>
<div class="col-md-10 populated_info"> <!-- WHERE I WOULD LIKE THE UPDATED INFORMATION -->
</div>
</div>
</div>
</form>
AJAX:
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
alert(resp); //how to get this to put the page back into the right spot?
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
Your approach:
With regards to your button, I'd suggest separating the inline Javascript handler to keep your HTML and Javascript separate. I'll use a custom data attribute to store the ID here:
<button type="button" class="btn btn-default custom mybutton" data-id="<?php echo $CURRENT_ID;?>">
<?php echo $lastName . ', ' . $firstName; ?>
</button>
Then jQuery:
$('.mybutton').click(function() {
var ID = $(this).data('id');
function1(ID);
});
Your AJAX request:
You can shorten that whole function and use $.load() to get the data into your div:
function function1(ID) {
// Get the output of functions/my_page.php, passing ID as parameter, and
// replace the contents of .populated_info with it
$('.populated_info').load('functions/my_page.php', { ID: ID });
}
Doesn't look like you need a callback function here, but if you do you can put it in after the data parameter. A useful application of a callback here might be for your error handler. See here how to implement one.
An an aside, if you're just getting data, you should probably be using the GET HTTP method instead of POST.
if you successfully get the response from the server just replace alert(resp) with $('.populated_info').html(resp);
<script>
function function1(ID) {
$.ajax({
type: "POST",
url: "functions/my_page.php",
data: "ID="+ID,
success: function(resp){
$('.populated_info').html(resp);
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>

Categories