How to call href function with ajax - javascript

I'm new here, i'm working with ajax and notify.js on my website.
Where there are a slight problem, which is i can't call my function using href with ajax and the notify.js won't pop up and delete the file
Let me show you my code
Views:
<tbody>
<?php foreach ($rows as $row) { ?>
<tr>
<td><?php echo $row ->description ?></td>
<td><?php echo $row->updated_at ?></td>
<td>Edit</td>
<td><a id="aDeleteOrderType" onclick="type_delete()" href="#.<?php echo $row->id ?>">Delete</a></td>
</tr>
<?php } ?>
Admin Footer
<script>
$("#aDeleteOrderType").click(function(e){
e.preventDefault();
$.ajax({
url: '<?php echo base_url().'admin/type_delete' ?>',
type: 'post',
data: {
},
success: function(msg)
{
if (msg == 'valid')
{
$.notify('Data Has Been Deleted', 'error')
}
}
});
});
Controller
public function type_delete($id)
{
$is_logged_in1 = $this->session->userdata('is_logged_in');
$type = $this->session->userdata('type');
if(!isset($is_logged_in1) || $is_logged_in1 != true)
{
$data['error'] = '';
$this->load->view('login-1', $data);
}
else
{
$this->load->model('listtipeorder_model');
$this->listtipeorder_model->delete_list_type($id);
echo 'valid';
}
}
Help me guys please:(
P.S sorry for my bad english though.

HTML:
Notice data-id, and attribute we will get soon.
<td><a id="aDeleteOrderType" href="#" data-id="<?php echo $row->id ?>">Delete</a></td>
JS:
Since you aren't using get or post to get the $id var in your php function and instead are passing it as a url param you have to do the same via jquery.
<script>
$(document).ready(function () {
$("#aDeleteOrderType").click(function (e) {
var id = $(this).attr('data-id');
e.preventDefault();
$.ajax({
url: '<?php echo base_url() . '/admin/type_delete/'; ?>' + id,
type: 'POST',
success: function (msg) {
if (msg == 'valid') {
// success would be better suited than 'error'
// might confuse some
$.notify('Item deleted', 'success');
} else {
$.notify('Error occurred', 'error');
}
}
});
});
});
</script>
PHP:
There isn't anything wrong with your PHP, but it can be improved.
function type_delete($id = null) {
$is_logged_in1 = $this->session->userdata('is_logged_in');
//$type = $this->session->userdata('type');
// isset not required with userdata as will return null if no data
if ($is_logged_in1 != true || is_null($id)) {
echo 'error';
// don't load a view
//$data['error'] = '';
//$this->load->view('login-1', $data);
} else {
$this->load->model('listtipeorder_model');
$this->listtipeorder_model->delete_list_type($id);
echo 'valid';
}
exit;
}

Related

How can i get the same ajax result using WP REST API instead of admin-ajax?

I have been told that admin-ajax is outdated now and it's better to use REST API instead but I was wondering how can I get the same result of this code which generates a button with a link based on some variables and custom fields using REST API?
also, someone told me that this code is not secure because I'm using HTML response instead of data in ajax but I'm wondering how to use data for this code?
I apologize but i'm still very new to coding
<?php
add_action( 'woocommerce_before_add_to_cart_button', 'simple_amz_link_ajax', 10);
function simple_amz_link_ajax() {
?>
<script>
jQuery(document).ready(function(){
jQuery.ajax({
url: "<?php echo admin_url('admin-ajax.php'); ?>",
type: 'POST',
data: {
action: 'getmyfunctionform1',
postId: <?php echo get_post()->ID; ?>
},
dataType: 'html',
success: function(response) {
jQuery("#buy_amz_btn_wrap").html(response);
}
});
});
</script>
<!-- end Ajax call to getmyfunctionform1 smc 11-22-2013 -->
<div id="buy_amz_btn_wrap"> Loading ... </div>
<?php
}
// Amazon Simple Button Function
add_action('wp_ajax_getmyfunctionform1', 'myfunctionform1');
add_action('wp_ajax_nopriv_getmyfunctionform1', 'myfunctionform1');
function myfunctionform1() {
$postId = filter_input( INPUT_POST, 'postId', FILTER_SANITIZE_NUMBER_INT );
$country_code = $_SERVER ["HTTP_CF_IPCOUNTRY"];
$de_asin = get_post_meta( $postId, "wccaf_de_asin", true );
$uk_asin = get_post_meta( $postId, "wccaf_uk_asin", true );
$not_avilable_country = '<div id="amz_not_avilable" class="amz_not_avilable">This product is not avilable in your country yet</div>';
//////////////////////////////////////////////
if ($country_code=="DE" or $country_code=="DE") {
$amazon_domain = 'https://www.amazon.de';
$associate_id = 'bonstato-21';
$asin = $de_asin;
}
else if ($country_code=="GB" && $uk_asin!=="") {
$amazon_domain = 'https://www.amazon.co.uk';
$associate_id = 'bonmedico-21';
$asin = $uk_asin;
}
///////////////////
global $post;
$product = wc_get_product( $postId );
$type = $product->get_type();
if( $type == 'simple' && $asin!="" ){
// Amazon Link For Mobile
?>
<script>
function amzGo(){
window.location='<?php echo $amazon_domain ?>/dp/<?php echo $asin ?>/?tag=<?php echo $associate_id ?>';
}
</script>
<?php
?>
<div class="buy_amz_btn_wrap" >
<button type="button" id="buy_amz_btn" class="buy_amz_btn" onclick="amzGo();"><i class="fa fa-amazon fa-amz"></i><?php echo $amz_btn_title ?></button>
</div>
<?php
}
else if( $type == 'simple' && $asin=="" ){
echo $not_avilable_country;
}
die();
}
?>

How to debug my Ajax/jQuery app?

I am trying some things regarding Ajax, Jquery and PHP.
My JavaScript code (the pop.php is located correctly)
<script type="text/javascript">
$('.nameclick').click(function()) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id=$(this).data("formid")}
success: function(result){
alert(result);
} else {
alert("test");
}
});
});
</script>
Part of my html/php code in the same page (this code works fine to print out the table I am looking for):
<table class="data-table">
<thead>
<tr>
<th>Servicenummer</th>
<th>Kund</th>
<th>Uppgift</th>
<th>Status</th>
<th>Inlämnad</th>
</tr>
</thead>
<tbody>
<?php
$no = 1;
$total = 0;
while ($row = mysqli_fetch_array($query))
{
echo '<tr>
<td><div id="clickMe">'.$row['service'].'</div></td>
<td>'.$row['name'].'</td>
<td>'.$row['Drakt1'].'<br>'.$row['Drakt2'].'<br>'.$row['Drakt3'].'<br>'.$row['Drakt4'].'<br>'.$row['Drakt5'].'<br>'.$row['Drakt6'].'<br>'.$row['reg1'].'<br>'.$row['flaska1'].'<br>'.$row['dator1'].'</td>
<td>'.$row['Service_Status'].'</td>
<td>'.$row['date'].'</td>
</tr>';
$no++;
}?>
</tbody>
</table>
And my pop.php:
<?php
require 'connection.php';
$conn = Connect();
$name = $conn->real_escape_string($_POST['name']);
$email = $conn->real_escape_string($_POST['email']);
$telephone = $conn->real_escape_string($_POST['telephone']);
$sql = 'SELECT name, email, telephone FROM Service_Form WHERE id = "10"';
$query = mysqli_query($conn, $sql);
if (!$query) {
die ('SQL Error: ' . mysqli_error($conn));
}
?>
<?php
while ($row = mysqli_fetch_array($query))
{
echo $row['name'];
echo $row['email'];
echo $row['telephone'];
}
?>
At the moment when I click my link in my normal page I don't get anything, no alerts at all, but my pop.php prints out the values correctly, I hope... I know I have to change my id="10" to something but i am not certain to what, could it be formid?
What am I doing wrong here?
What I want:
a table with the values below from a table in the database
when I click the name in the table it should show an alert (or something similar) that shows the name, email and telephone number (these are stored as well in the database table but not on the website table).
your ajax function is having some errors
so use this
<script type="text/javascript">
$('.nameclick').click(function(ev) {
ev.preventDefault();
var id = $(this).data("formid");
$.ajax({
type: "POST",
url: "pop.php",
data: {
"id":id
},
success: function(result){
alert(result);
},
error:function (error) {
alert(error);
}
});
});
</script>
I am editing your jquery part please try
<script type="text/javascript">
$('.nameclick').click(function(ev)) {
ev.preventDefault();
$.ajax({
typ: "POST"
url: "/pop.php"
data: {id:$(this).attr("data-formid")}
success: function(result){
if(result){
alert(result);
} else {
alert("test");
}
}
});
});
</script>

'Unexpected token ;' when trying to pass PHP variable in jQuery AJAX request

So im trying to run a PHP script that sets a deleted field in the database to poplulate if you drag a certain text element to the droppable area.
At the moment i have this droppable area:
<div class="dropbin" id="dropbin" >
<span class="fa fa-trash-o noSelect hover-cursor" style="font-size: 20pt; line-height: 225px;"> </span>
</div>
and this draggable text:
<div id='dragme' data-toggle='modal' data-target='#editNoteNameModal' class='display-inline'>" . $data['NoteName'] . "</div>
The area im having an issue with is this:
$("#dropbin").droppable
({
accept: '#dragme',
hoverClass: "drag-enter",
drop: function(event)
{
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
var deletedby = <? if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>
var data = {noteid1: noteid, deletedby1: deletedby};
if (confirm('Delete the note?')==true)
{
$('#dragme').hide();
debugger
$.ajax({
type: 'POST',
url: 'deleteNote.php',
datatype: 'json',
data: data,
success: function(result)
{
alert("Success");
}
});
window.location = "http://discovertheplanet.net/general_notes.php";
}
else
{
window.location = "http://discovertheplanet.net/general_notes.php";
}
}
});
EDIT: The line i get the error on is:
var noteid = <?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>;
Im currently getting an "Unexpected token ;" and its stopping the droppable from working.
Just a side note, if i run it without the variables it hits everything apart from:
url: 'deleteNote.php',
Also inside deleteNote.php is this incase it helps:
<?php
include "connectionDetails.php";
?>
<?php
if (isset($_POST['noteid1'], $_POST['deletedby1']))
{
$noteid2 = $_POST['noteid1'];
$deletedby2 = $_POST['deletedby1'];
// echo "Hello...". $noteid;
$stmt = "UPDATE Notes SET Deleted = GETDATE() WHERE NoteID = (?)";
$params = array($noteid2);
$stmt = sqlsrv_query($conn, $stmt, $params);
if ($stmt === false)
{
die( print_r(sqlsrv_errors(), true));
}
}
else
{
echo "No Data";
}
?>
(I deliberatley don't have deletedby in the database just yet, ignore that)
Could anyone possibly help me to get this to work?
Try to add quotes in these lines and add php after <? in second line:
var noteid = "<?php if(isset($_POST['noteid'])){ echo $_POST['noteid'];} ?>";
var deletedby = "<?php if(isset($_SESSION['username'])){ echo $_SESSION['username'];} ?>";
OR
var noteid = "<?=isset($_POST['noteid']) ? $_POST['noteid'] : "" ?>";
var deletedby = "<?=isset($_SESSION['username']) ? $_SESSION['username'] : "" ?>";

How to add php form validation with ajax error handling

How can I add validation and php error handling with ajax. Now the success message come correctly but how can I implement error message on it? I might need to add some php validation please help.
Here is my JS.
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function () {
$(".msg-ok").css("display", "block");
$(".msg-ok-text").html("Profile Updated Successfully!!");
},
error: function() {
//Error Message
}
});
});
PHP
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "<p>Succcessfully Updated</p>";
} else {
echo "Erorr while updating record : ". $connect->error;
}
$connect->close();
}
?>
ajax identifies errors based of status code, your php code will always return status code 200 which is success, even when you get error in php code unless its 500 or 404. So ajax will treat response as success.
if you want to handle php error, make following changes in your code
<?php
require_once 'db_connect.php';
if($_POST) {
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$index_no = $_POST['index_no'];
$contact = $_POST['contact'];
$id = $_POST['id'];
$sql = "UPDATE members SET fname = '$fname', lname = '$lname', index_no = '$index_no', contact = '$contact' WHERE id = {$id}";
if($connect->query($sql) === TRUE) {
echo "true";
} else {
echo "false";
}
$connect->close();
}
?>
$('#edit_user_form').bind('click', function (event) {
event.preventDefault();// using this page stop being refreshing
$.ajax({
data: $(this).serialize(),
type: $(this).attr('method'),
url: $(this).attr('action'),
success: function (res) {
if(res == 'true') {
//success code
} else if(res == 'false') {
//error code
}
},
error: function() {
//Error Message
}
});
});

Error in Ajax submit

I am new to Yii and ajax I want to read some inputs for a model from view and save it by using ajax. I used the following code inside form
<input type="button" name="save" value="save" onclick="saveFile()" id="profile-update" class="btn button-main" live="false">
and saveFile() is
function saveFile()
{
var data;
data = new FormData();
data.append('file', $('#UserProfile_profile_picture')[0].files[0]);
data.append('UserProfile', $('#profile-update-form').serialize());
$.ajax({
url: '<?php echo CHtml::normalizeUrl(array('user/profileupdate?rand=' . time())); ?>',
type:"POST",
data: data,
processData: false,
contentType: false,
success: function (data) {
$("#AjaxLoader1").hide();
if(data.status=="success"){
$("#formResult1").html("Profile settings changed successfully.");
$("#profile-update-form")[0].reset();
}
else{
$.each(data, function(key, val) {
$("#profile-update-form #"+key+"_em_").text(val);
$("#profile-update-form #"+key+"_em_").show();
});
}
},
beforeSend: function(){
$("#AjaxLoader1").show();
}
}
)
return false;
}
and the code in controller is
$profile = UserProfile::model()->findByAttributes(array('user_id' => Yii::app()->user->id));
if (!$profile) {
$profile = new UserProfile;
$profile->create_time = time();
$profile->update_time = time();
}
if (isset($_POST['UserProfile'])) {
$profile->attributes = $_POST['UserProfile'];
$profile->profile_picture=$_FILES['file']['name'];
$images = CUploadedFile::getInstance($profile,'profile_picture');
// print_r($_POST);
// print_r($profile->phone);
// print_r($images);
// exit();
if (isset($images))
{
if(!is_dir(Yii::getPathOfAlias('webroot').'/images/profilepic/'. 'quy'))
{
mkdir(Yii::getPathOfAlias('webroot').'/images/profilepic/'. $profile->profile_picture);
// the default implementation makes it under 777 permission, which you could possibly change recursively before deployment, but here�s less of a headache in case you don�t
}
foreach ($images as $image => $pic)
{
echo $pic->name;if ($pic->saveAs(Yii::getPathOfAlias('webroot').'/images/profilepic/'.$pic->name))
{
$profile->profile_picture = $pic->name;
}
}
}
$profile->user_id = Yii::app()->user->id;
$profile->update_time = time();
$valid = $profile->validate();
$error = CActiveForm::validate(array($profile));
if ($error == '[]') {
$profile->save(false);
echo CJSON::encode(array('status' => 'success'));
Yii::app()->end();
} else {
$error = CActiveForm::validate(array($profile));
if ($error != '[]')
echo $error;
Yii::app()->end();
exit();
}
}
But here only the profile_picture is saving to the database all other fields are not changing. and the profile picture is not copying into the folder($images is blank) Please somebody help me to solve this problem. Thanks in advance
The code $profile->attributes = $_POST['UserProfile']; doesnt worked so i send it seperately by data.append('UserProfile[about_me]', $('#UserProfile_about_me').val());
data.append('UserProfile[city]', $('#inputCity').val());
data.append('UserProfile[phone]', $('#inputPhone').val()); and in controller i used $profile->profile_picture=$_FILES['file']['name'];
$profile->about_me = $_POST['UserProfile']['about_me'];
$profile->city = $_POST['UserProfile']['city'];
$profile->phone = $_POST['UserProfile']['phone']; I know this is not the correct way but may be helpful for someone who is hurry.

Categories

Resources