JQuery: Cannot Access php file using Relative Path - php

Really struggling to get a relative path to work for an Ajax request.
From like.js I'm trying to get to likeunlike.php
Error message:
jquery-3.3.1.js:9600 POST http://localhost:8000/serverside/likeunlike.php 404 (Not Found)
File structure:
JQuery:
$(document).ready(function(){
// like and unlike click
$(".content").on("click",".like",function(){
var id = $(this).attr("id"); // Getting Button id
var split_id = id.split("_");
var postid = split_id[1];
var userid = split_id[2];
// AJAX Request
$.ajax({
url: '../serverside/likeunlike.php',
type: 'post',
data: {postid:postid,userid:userid},
dataType: 'json',
success: function(data){
var likes = data['likes'];
var type = data['type'];
$("#likes_" + postid + "_" + userid).text(likes);
if(type == 1){
$("#like_" + postid + "_" + userid).css("color","lightseagreen");
}
if(type == 0){
$("#like_" + postid + "_" + userid).css("color","#ffa449");
}
}
});
});
});
Have provided the index file as requested by one of the answers. Hope it helps.
Index.php:
<?php
include "detail/config.php";
?>
<html>
<head>
<title>Talk</title>
<link href="style/style.css" type="text/css" rel="stylesheet" />
<script src="jquery/jquery-3.3.1.js" type="text/javascript"></script>
<script src="search/script/like.js" type="text/javascript"></script>
<script src="search/check/check.js" type="text/javascript"></script>
</head>
<script>
$(function() {
$('form').on("submit", function(e) {
e.preventDefault();
$('#error').text(""); // reset
var name = $.trim($("#search").val());
if (name.match(/[^a-zA-Z0-9 ]/g)) {
$('#error').text('Please enter letters and spaces only');
return false;
}
if (name === '') {
$('#error').text('Please enter some text');
return false;
}
if (name.length > 0 && name.length < 3) {
$('#error').text('Please enter more letters');
return false;
}
$.ajax({
url: 'search/search.php',
method: 'POST',
data: {
msg: name
},
dataType: 'json',
success: function(response) {
$(".content").html("")
$(".total").html("")
if(response){
var total = response.length;
$('.total') .append(total + " Results");
}
$.each(response, function() {
$.each($(this), function(i, item) {
var mycss = (item.Type == 1) ? ' style="color: #ffa449;"' : '';
$('.content').append('<div class="post"><div class="post-text"> ' + item.MessageText + ' </div><div class="post-action"><input type="button" value="Like" id="like_' + item.ID + '_' + item.UserID + '" class="like" ' + mycss + ' /><span id="likes_' + item.ID + '_' + item.UserID + '">' + item.cntLikes + '</span></div></div>');
});
});
}
});
});
});
</script>
<body>
<form action="index.php" method="post" id="myForm" autocomplete="on"><pre>
<input name="msg" id="search" type="text" autofocus value= "<?php if(isset($_POST['msg'])) {
echo htmlentities ($_POST['msg']); }?>"></input> <span id="error"></span>
<input type="submit" style="border:0; padding:0; font-size:0">
</pre></form>
<div class="total">
</div>
<div class="content">
</div>
</body>
</html>

jquery / js has no information about his location.
this should be work.
var base_url = window.location.origin;
// like and unlike click
$(".content").on("click",".like",function(){
var id = $(this).attr("id"); // Getting Button id
var split_id = id.split("_");
var postid = split_id[1];
var userid = split_id[2];
// AJAX Request
$.ajax({
url: base_url + '/search/serverside/likeunlike.php',
type: 'post',
data: {postid:postid,userid:userid},
dataType: 'json',
success: function(data){
var likes = data['likes'];
var type = data['type'];
$("#likes_" + postid + "_" + userid).text(likes);
if(type == 1){
$("#like_" + postid + "_" + userid).css("color","lightseagreen");
}
if(type == 0){
$("#like_" + postid + "_" + userid).css("color","#ffa449");
}
}
});
});
});

I have resolved the situation by:
Making my directory structure simpler as well as the file names. It was over-engineered. I have my root folder now and then just one level below that for folders.
The Ajax url path, which I was struggling with was amended to 'serverside/like.php', which picked up the php file but nothing happened.
Reviewing the like.php code I had an include("../con/config.php") without a ';'. I added this and it's now working fine.
Thank you for everyone's help. Much appreciated as always.
New folder structure:

Related

How to automatically send a discount coupon when it exists in the url?

I have created a discount coupon system, everything is working perfectly.
From the following form I send the information by ajax
<div class="form-group relative">
<div class="response">
<div class="success"></div>
<div class="warning"></div>
</div>
<form id="coupon" class="mt-2em" method="post" autocomplete="off" enctype="multipart/form-data">
<div class="form-group flex justify-between">
<div class="promo">
<input type="text" name="couponCode" maxlength="15" placeholder="Enter the coupon">
</div>
<div class="btn-promo">
<input id="submit_coupon" type="submit" name="ajaxData" value="Apply" formnovalidate>
</div>
</div>
</form>
</div>
And, this is my ajax code
$(function() {
var frm = $('#coupon');
frm.submit(function(e){
e.preventDefault();
var formData = frm.serialize();
formData += '&' + $('#submit_coupon').attr('name') + '=' + $('#submit_coupon').attr('value');
var url = "coupon.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
if(res.status){
$(".checkout").load(" .checkout").fadeIn();
$(frm)[0].reset();
$(frm).hide();
} else {
if (typeof (res.message) === 'object') {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#coupon'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
} else {
$('.warning').fadeIn();
$('.warning').html(res.message).delay(8000).fadeOut(8000);
}
}
})
.fail(function( jqXHR, textStatus ) {
console.log(jqXHR.responseText);
console.log("Request failed: " + textStatus );
})
});
});
How do I mention this all right, but with the same ajax code, how can I send the coupon code automatically when the coupon is being shared by the URL?
That is, if I have the following in the url: example.com/?codecoupon=EADEAA So I want to automatically send that information to Ajax only if there are those parameters in the URL.
In your HTML:
<input type="text" name="couponCode" maxlength="15" placeholder="Enter the coupon" value="<?= isset($_GET['codecoupon']) ? $_GET['codecoupon'] : '' ?>">
(In order to avoid XSS injections you want to wrap it with htmlspecialchars)
In your JS you should make the sending code a function, then call it:
On submit
On load: only if the input is not empty.
The script will look something like this:
$(function() {
var frm = $('#coupon');
frm.submit(function(e){
e.preventDefault();
sendCoupon(frm);
});
if ($("input[name='couponCode']").val() !== "") {
sendCoupon(frm);
}
function sendCoupon(frm) {
var formData = frm.serialize();
formData += '&' + $('#submit_coupon').attr('name') + '=' + $('#submit_coupon').attr('value');
var url = "coupon.php";
$.ajax({
type: frm.attr('method'),
url: url,
data: formData,
})
.done(function(data) {
let res = JSON.parse(data);
if(res.status){
$(".checkout").load(" .checkout").fadeIn();
$(frm)[0].reset();
$(frm).hide();
} else {
if (typeof (res.message) === 'object') {
for (let name in res.message) {
$('.error').remove();
let msg = '<span class="error">' + res.message[name] + '</span>';
$(msg).insertAfter($('[name=' + name + ']', '#coupon'));
$('.error').fadeIn().delay(5000).fadeOut(5000);
}
} else {
$('.warning').fadeIn();
$('.warning').html(res.message).delay(8000).fadeOut(8000);
}
}
})
.fail(function( jqXHR, textStatus ) {
console.log(jqXHR.responseText);
console.log("Request failed: " + textStatus );
});
}
});

how to pass data to php using ajax?

I want to display a message according to the className passed to server using AJAX . I'm new ajax , I have no idea about that..
myhtml code :
<div class="header">
<h2>Configuration</h2>
<p> Enable: </p> <i class="fas fa-toggle-off " id="enable-btn"></i>
<span id="demo">Dashboard Enabled</span>
</div>
myJS code :
function enableButtonClicked() {
$(document).ready(function () {
$('#enable-btn').click(function () {
$( ".dashboard, #demo" ).toggle();
$(this).toggleClass("fa-toggle-off fa-toggle-on");
});
});
}
ajax code :
function displayMessageAccordingToButtonState() {
var x = document.getElementById('enable-btn').className;
if( x == 'fas fa-toggle-off'){
var msg = "Button Disabled"
$('.header').load('request.php',{"displayMsg":msg});
}
else {
var msg = "Button Enabled"
$('.header').load('request.php',{"displayMsg":msg});
}
}
php code :
<?php
if( $_REQUEST["displayMsg"] ){
$msg = $_REQUEST['displayMsg'];
echo "".$msg ;
}
?>
this is working demo
just copy and try
i have added extra span and ajax file content is copy to that content
<html>
<head>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
</head>
<body>
<div class="header">
<h2>Configuration</h2>
<p> Enable: </p> <i class="fas fa-toggle-off " id="enable-btn"></i>
<span id="demo">Dashboard Enabled</span>
</div>
<span id="demo2"></span>
</body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> </script>
<script>
$(document).ready(function () {
$('#enable-btn').click(function () {
$( ".dashboard, #demo" ).toggle();
$(this).toggleClass("fa-toggle-off fa-toggle-on");
});
});
$('#enable-btn').click(function () {
var x = document.getElementById('enable-btn').className;
if( x == 'fas fa-toggle-off'){
var msg = "Button Disabled"
$('#demo2').load('request.php',{"displayMsg":msg},function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
console.log("External content loaded successfully!"+responseTxt);
if(statusTxt == "error")
console.log("Error: " + xhr.status + ": " + xhr.statusText);
});
}
else {
var msg = "Button Enabled"
$('#demo2').load('request.php',{"displayMsg":msg},function(responseTxt, statusTxt, xhr){
if(statusTxt == "success")
console.log("External content loaded successfully!"+responseTxt);
if(statusTxt == "error")
console.log("Error: " + xhr.status + ": " + xhr.statusText);
});
}
});
</script>
</html>
this is my php file
if( $_REQUEST["displayMsg"] ){
$msg = $_REQUEST['displayMsg'];
echo "".$msg ;
}
in JS
var request = $.ajax({
async: false,
url: 'Php.file', / your php file path
type: "POST",
data: "Value1=your value";
datatype: 'html',
});
request.done(function(data) {
//data you will handle from php file
});
in PHP receive
$data = $_POST['data'];
//you can check like this
if(empty($data))
{
echo("none received");
}
else{
echo 'passed parameter '+$data;
//in here you will receive as data in js file
you will receive in data in js as 'passed parameter+ your value'
}
First of all is to create an HTML file with jQuery included.
Let's say you have a hidden input field.
<input type="hidden" id="mydata" value="sampledata">
You can now get the data from the hidden field using the script $("#mydata").val();
You can now write the ajax code as follows
$.ajax({
type: 'post',
url: '/path/to/ajax.php',
data: {
postvariable: $("#mydata").val()
},
success: function() {
alert('success');
}
});
In your ajax.php file, you can now receive the value as $_POST['postvariable']
You can now declare
$myphpvar = $_POST['postvariable'];
Where
echo $myphpvar; //will print 'sampledata' without quotes
To summarize, it is simply like submitting a form with the having the method post. Except when using ajax it does not require the page to reload.
You may read more about this in my tutorial:
https://www.davidangulo.xyz/website-development/how-to-pass-value-from-javascript-to-php/

I can not click again remove or add button

I want to create an Add and Remove from ordered lists button for my site.
But I can not click again when I click add button or remove button.
<script>
$(document).ready(function () {
$('.order-lists div #add').click(function(e) {
$('.order-lists div').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.cookie(ids, name);
$.cookie(name, mov_size);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).append('<a class="btn btn-danger" id="remove" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Remove </a>');
});
}
e.preventDefault();
});
$('.order-lists div #remove').click(function(e) {
$('.order-lists div').removeClass('remove');
var $parent = $(this).parent();
if (!$parent.hasClass('remove')) {
$parent.addClass('remove');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.removeCookie(ids, null);
$.removeCookie(name, null);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).removeClass('remove');
$("#" + ids).append('<a class="btn btn-danger" id="add" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Add Order List </a>');
});
}
e.preventDefault();
});
});
</script>
use on function for dynamically added elements.
$(document).ready(function () {
$('.order-lists').on('click', '#add' , function(e) {
$('.order-lists div').removeClass('active');
var $parent = $(this).parent();
if (!$parent.hasClass('active')) {
$parent.addClass('active');
var DataId = $(this).attr('value');
var requested = { 'id': DataId }
$.ajax({
type: 'POST',
url: 'config/process/order-lists.php',
data: requested,
dataType: 'json',
encode: true
}).done(function (data) {
console.log(data);
ids = data['mov_id'];
name = data['mov_name'];
mov_size = data['mov_size'];
$.cookie(ids, name);
$.cookie(name, mov_size);
$("#" + ids + ' ' + 'a').remove();
$("#" + ids).append('<a class="btn btn-danger" id="remove" href="javascript:void(0);" value="' + ids + '"> <i class="glyphicon glyphicon-shopping-cart"></i> Remove </a>');
});
}
e.preventDefault();
});
});
same for remove.

AJAX not working within form and instantly sending me to PHP script? PHP/AJAX

I've currently got a feature on my web application where you can add your skills by clicking the "Add a Skill" button, very simple and worked up until I tried to add something else into the mix. The error is the fact that when I click the "Add a Skill" button it acts as if that were the submit button and try's to execute the php script skills/add
I'm currently trying to make it so that my application constantly checks whether the text which the user is typing exists within the database which is represented with a green tick or red cross if it doesn't exist.
What I'm asking is can anyone see why this is not working as it should be?
VIEW
<form method="post" action="skills/add" id="container">
<script>
$.fn.addSlide = function () {
return this.each(function () {
var $this = $(this),
$num = $('.slide').length++,
$name = $('<input type="text" class="inputField" id="autoskill-' + $num + '" name="skill-' + $num + '" placeholder="What\'s your skill?"></div><img id="tick" src="/images/tick.png" width="16" height="16"/><img id="cross" src="/images/cross.png" width="16" height="16"/>');
$slide = $('<br><div class="slide" id="slider-' + $num + '"></div><br>'),
$amt = $('<input name="amount-' + $num + '" id="amount-' + $num + '" class="inputField" readonly placeholder="Slide to select this skill level..."/><br>');
$this.append($name).append($amt).append($slide);
console.log($('#autoskill'));
$slide.slider({
value: 0,
min: 0,
max: 5,
step: 1,
slide: function (event, ui) {
$amt.val(ui.value);
}
});
});
}
$('body').on('click', '.addNew', function(event) {
event.preventDefault();
$('#newFields').addSlide();
});
var count = 0;
$(document).ready(function(){
$('.inputField').keyup(skill_check);
function skill_check(){
var skill = $('.inputField').val();
if(skill == "" || skill.length < 4){
$('.inputField').css('border', '3px #CCC solid');
$('#tick').hide();
}else{
jQuery.ajax({
type: "POST",
url: "skills/auto",
data: 'name='+ skill,
cache: false,
success: function(response){
if(response == 1){
$('.inputField').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}else{
$('.inputField').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
$('.addNew').click( function(event){
event.preventDefault();
$('#length').html(count);
count++;
});
$('.submitButton').click( function(event){
$('#container').append('<input type="hidden" name="count" value="' + count + '">');
});
});
</script>
<button class="addNew submitButton"> Add a Skill </button><br>
<div id="newFields"></div>
<input type="submit" class="submitButton" value="Save Skills">
</form>
Thanks for your help in advance.
You should use absolute path to your php script..
jQuery.ajax({
type: "POST",
url: "full-path-to-your-script",
If you are sending the form via AJAX you don't want this:
<input type="submit" class="submitButton" value="Save Skills">
You want this:
<input type="button" class="submitButton" value="Save Skills" onClick="SomeAJAXFunction()">
You can add return false to one of your functions.
<input type="button" class="submitButton" value="Save Skills" onClick="return FunctionWithReturnFalse()">
As you pointed out in your comment above, you have a JS error on the page. If you were to indent your code correctly, you would discover that it is probably due to a missing } to close the else after your ajax call:
<script>
$.fn.addSlide = function () {
return this.each(function () {
var $this = $(this),
$num = $('.slide').length++,
$name = $('<input type="text" class="inputField" id="autoskill-' + $num + '" name="skill-' + $num + '" placeholder="What\'s your skill?"></div><img id="tick" src="/images/tick.png" width="16" height="16"/><img id="cross" src="/images/cross.png" width="16" height="16"/>');
$slide = $('<br><div class="slide" id="slider-' + $num + '"></div><br>'),
$amt = $('<input name="amount-' + $num + '" id="amount-' + $num + '" class="inputField" readonly placeholder="Slide to select this skill level..."/><br>');
$this.append($name).append($amt).append($slide);
console.log($('#autoskill'));
$slide.slider({
value: 0,
min: 0,
max: 5,
step: 1,
slide: function (event, ui) {
$amt.val(ui.value);
}
});
});
}
$('body').on('click', '.addNew', function(event) {
event.preventDefault();
$('#newFields').addSlide();
});
var count = 0;
$(document).ready(function(){
$('.inputField').keyup(skill_check);
function skill_check(){
var skill = $('.inputField').val();
if(skill == "" || skill.length < 4){
$('.inputField').css('border', '3px #CCC solid');
$('#tick').hide();
} else {
jQuery.ajax({
type: "POST",
url: "skills/auto",
data: 'name='+ skill,
cache: false,
success: function(response){
if(response == 1){
$('.inputField').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
}else{
$('.inputField').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
// MISSING } HERE
}
$('.addNew').click( function(event){
event.preventDefault();
$('#length').html(count);
count++;
});
$('.submitButton').click( function(event){
$('#container').append('<input type="hidden" name="count" value="' + count + '">');
});
});
</script>

jquery auto complete does not work on every field

I use codeigniter. And I have three field with the class .eghamat. I don't know why autocomplete doesn't work in the two first fields (INSERT VALUE HERE 1, INSERT VALUE HERE 2) but works in the third(INSERT VALUE HERE 3).
The problem might come from one of the following:
The php code
the $.each loop
the ajax call
Does someone see what's wrong?
html:
<div class="bg_units bu0">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 1">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
<div class="bg_units bu1">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 2">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
<div class="bg_units bu2">
<div class="auto_box">
<b class="search_hotel">
<div class="mediumCell">
<input type="text" name="hotel_auto" class="eghamat" placeholder="INSERT VALUE HERE 3">
</div>
<ul class="list_autobox_hotel">
</ul>
</b>
</div>
</div>
php:
function auto_complete() {
$hotel_search = $this ->input-> post('hotel_auto');
$query = $this->db->query("SELECT * FROM hotel_submits WHERE name LIKE '%$hotel_search%' ORDER BY name asc");
if($query->num_rows()==0){
return '0';
}else{
$data = array();
foreach ($query->result() as $row)
{
$units = json_decode($row->units);
$data[] = array('name' => $row->name, 'units' =>$units );
}
}
echo json_encode($data);
}
jQuery:
$('.auto_complete_eghamat').live('keyup',function () {
var $this = $(this),
$div = $this.closest('div.bg_units'),
bu_num = '.' + $div.attr('class').split(" ")[1];
var dataObj = $(this).closest('form').serialize();
$.ajax({
type: "POST",
dataType: 'json',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
//alert(dataObj);
var id_name = $(bu_num+' .list_autobox_hotel').attr('id');
$(bu_num+' .list_autobox_hotel').show().html('');
if (data == 0) {
$(bu_num+' .search_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p id="' + value.name + '">' + value.name + '</p>').appendTo(bu_num+' .list_autobox_hotel');
});
$('body').click(function () {
$(".list_autobox_hotel p").hide().remove();
$('.auto_complete').val('');
$('.list_autobox_hotel').show().html('');
$('.list_autobox_hotel').css('display', 'none');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
could you please rename id="tour" and id="hotel" cz html cannot have same ids multiple times
id="tour"
and also
id="hotel"
appears 3 times in the code so please look into it.
could you please try it out. and let me know.your admin.js should be like this
$(document).ready(function () {
$('.list_autobox_hotel p').click(function() {
$(this).parent().parent().find('.eghamat').val($(this).text());
});
$(document).click(function() {
if($('.list_autobox_hotel').is(':visible')){
$('.list_autobox_hotel').hide();
}
return true;
});
////////////////////////////////////////////////////////////////
$('#loadingDiv').hide() // hide it initially
.ajaxStart(function () {
$(this).show();
}).ajaxStop(function () {
$(this).hide();
});
///////auto_complete///////////////////////////////////////////////
$('.eghamat').live('keyup', function () {
var $this = $(this),
$div = $this.closest('div.bg_units'),
bu_num = '.' + $div.attr('class').split(" ")[1];
var dataObj = $(this).closest('form').serialize();
//alert(dataObj);
$.ajax({
type: "POST",
dataType: 'json',
//url: 'binboy.gigfa.com/admin/…',
url: 'auto_complete',
data: dataObj,
cache: false,
success: function (data) {
//alert(bu_num);
var id_name = $(bu_num + ' .list_autobox_hotel').attr('id');
$(bu_num + ' .list_autobox_hotel').show().html('');
if (data == 0) {
$(bu_num + ' .list_autobox_hotel').show().html('<p><b>there is no</b></p>');
} else {
$.each(data, function (index, value) {
$('<p >' + value.name + '</p>').appendTo(bu_num + ' .list_autobox_hotel');
});
}
},
"error": function (x, y, z) {
// callback to run if an error occurs
alert("An error has occured:\n" + x + "\n" + y + "\n" + z);
}
});
});
});
Here is a simple code
$('.eghamat').click(function(){
var id =$(this).attr('id');
//Here you have the id select with it and put your code in it
});

Categories