Including JS file in html page errors - javascript

I have this JavaScript code inside an html and PHP page. But I've been told that it will works only if I had an internet connection, so the solution was to make a .JS file and include this file inside the page like that:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script language="javascript" type="text/javascript" src="/clinic form/appoint/dropscript.js">
</script>
Now I got an error while testing the page offline.
The JS file is taken from this link:
multiple java script in one page error
And the final code is:
$(document).ready(function(){
$("#Date").change(function(){
var seldate =$(this).val();
display_data(seldate);
});
// This is the function...
function display_data(seldate) {
$("#scheduleDate").html(seldate);
var dataString = 'seldate='+ seldate;
$.ajax({
type: "POST",
url: "getdata.php",
data: dataString,
cache: false,
success: function(data) {
$("#Schedule").html(data);
}
});
}
// Now here is the real code for retaining your Date...
/*<?php
if (!empty($_GET['date'])) {
?>
display_data('<?php echo $_GET["date"]; ?>')
<?php
}
?>*/
document.getElementById('Date').value = '<?php echo #$_GET["date"]; ?>';
});
$(document).ready(function(){
$("#Name").change(function(){
var selname =$(this).val();
display_name(selname);
});
// This is the function...
function display_name(selname) {
$("#scheduleName").html(selname);
var dataString = 'selname='+ selname;
$.ajax({
type: "POST",
url: "getdatabyname.php",
data: dataString,
cache: false,
success: function(data) {
$("#Schedule").html(data);
}
});
}
});// JavaScript Document
P.S. I am totally new to JS and I am experimenting.

Go to https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js, hit CTRL+S, move saved file to your project's directory and then include it as you did with dropscript.js.
Also do the same with the font if you need it. Include it into your CSS file using #font-face. More information: https://developer.mozilla.org/en-US/docs/Web/CSS/#font-face

Related

$.ajax not uploading files using data: object array method

Ive searched on Stack overflow all over the place and could not find a solution or a post that is close to my problem.
So if this has been posted before I do apologies.
I am posting some information using a different method rather than posting a form which I will explain after I show you the code :)
Jquery:
$("#submit-add-cpos").on('click',function(){
var checkHowManyInstallments = $('#installment-ammount').val();
var checkCpoNumber = $('#addcponumber').val();
var checkCpoTotalPrice = $('#addcpoprice').val();
var checkCpoContactName = $('#addcpocontactname').val();
var form_data = new FormData();
form_data.append("type", 'addcpo');
form_data.append("quoteid", '<?php echo $_GET['id']; ?>');
form_data.append("installmentamount", checkHowManyInstallments);
form_data.append("cponumber", checkCpoNumber);
form_data.append("costcode", '<?php echo $quotecostcode; ?>');
form_data.append("cpocontactname", checkCpoContactName);
form_data.append("cpotitle", '<?php echo $quotetitle; ?>');
var checkDynamicValues = '';
var checkDynamicValue1 = '';
var checkDynamicValue2 = '';
var checkmakename1 = '';
var checkmakename2 = '';
if(checkHowManyInstallments != 'undefined' && checkHowManyInstallments != '' && checkHowManyInstallments != 0){
for(var makingi = 1; makingi <= checkHowManyInstallments; makingi++){
checkDynamicValue1 = $('#cpo-adddate-' + makingi).val();
checkDynamicValue2 = $('#cpo-addprice-' + makingi).val();
form_data.append('cposadddate' + makingi, checkDynamicValue1);
form_data.append('cposaddvalue' + makingi, checkDynamicValue2);
}
}
$.ajax({
url: '/Applications/Controllers/Quotes/ajax-add-sin.php',
dataType: 'script',
cache: false,
contentType: false,
processData: false,
data: form_data, // Setting the data attribute of ajax with file_data
type: 'post',
success: function(data) {
$('body').html(data);
}
});
});
So from this script I get all the fields from within the form, including some dynamic ones.
The reason why I am doing it like this instead of the easier way of:
$("#formname").on('submit',function(){
$.ajax({
url: "xxxxxxxxxx/xxxxx/xxxx/xxxx.php",
type: "POST",
data: new FormData(this),
contentType: false,
cache: false,
processData:false,
success: function(data){
}
});
});
Is because for some reason it will not find the posted information no matter what I tried, so the only way I could do it is to find each id and get the value from it.
Now the issue is, uploading a file, you can not simply upload a file this way because nothing is posted.
How would I go about uploading a file if not posting a form?
Thanks
The reason why it was not posting the file is simply because I did not give it a file to post...
18 hours straight of work has not agreed with me here.
Basically I need to add the following code
var checkCpoFiles = $("#addcpofile").prop("files")[0];
form_data.append("cpofile", checkCpoFiles);
Now all works
:)
Please go through this page Ajax Upload image
Here's sample code, it might help
<html>
<head>
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'></script>
</head>
<body>
<form enctype="multipart/form-data" action="uploadfile.php" method="POST" id="imageUploadForm">
<input type="file" name="upload" />
<input type="submit"/>
</form>
</body>
<script>
$(document).ready(function (e) {
$('#imageUploadForm').on('submit',(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type:'POST',
url: $(this).attr('action'),
data:formData,
cache:false,
contentType: false,
processData: false,
success:function(data){
console.log("success");
console.log(data);
},
error: function(data){
console.log("error");
console.log(data);
}
});
}));
});
</script>
uploadfile.php
<?php
if(move_uploaded_file($_FILES['upload']['tmp_name'],$_FILES['upload']['name'])) {
echo "File uploaded successfully";
} else {
echo "Unable to upload the file";
}
?>
Hope it helps! All the best!

post binary code not working from Jquery ajax

I made this code to make image upload function but the variable is not getting posted by ajax please help me !!
Jquery()
<script type="text/JavaScript">
$(document).ready(function() {
$("#btn").click(function() {
$.get("i.png", function(response) {
var img = response;
});
$.ajax({
type: "POST",
url: 'lol.php',
data: {r: img},
success: function(data){
$("#ol").html(data)
}
});
return false;
});
});
</script>
PHP Code
<?php
$conn = mysqli_connect("localhost","root","","image");
$r = $_POST['r'];
echo $r;
?>
If you only want to make an image upload (and not exactly match "binary upload")
I suggest you to use the proper functional and native input type file.
In a html form, put an :
<input type="file" id="upload">
<img src="blank.png" title="upload-preview">
and in you javascript:
this will load the preview thumbnail selected
fileInput.addEventListener("change", function(event)
{
var file = $("#upload")[0].files[0];
$(".upload-preview").attr('src', window.URL.createObjectURL(file));
});
and when you click the button, that will send the image
with a "multipart/form-data" Content-Type
$("#btn").on("click", function()
{
var inputs = new FormData();
inputs.append("upload", $("#upload")[0].files[0]);
$.ajax
({
url:"your.php",
type:"POST",
data: inputs,
cache: false, // don't cache the image
processData: false, // Don't process the files
contentType: false,
success: function(response)
{
// next instructions
}
});
});

pass js variable to php using ajax on the same page

this is my html code:
<form id="form" action="javascript:void(0)">
<input type="submit" id="submit-reg" value="Register" class="submit button" onclick="showtemplate('anniversary')" style='font-family: georgia;font-size: 23px;font-weight: normal;color:white;margin-top:-3px;text-decoration: none;background-color: rgba(0, 0, 0, 0.53);'>
</form>
this is my javascript code:
function showtemplate(temp)
{
$.ajax({
type: "POST",
url: 'ajax.php',
data: "section="+temp ,
success: function(data)
{
alert(data);
}
});
}
this is my ajax.php file:
<?php
$ajax=$_POST['section'];
echo $ajax;
?>
The above html and javascript code is included in a file named slider.php. In my index file i have included this slider.php file and slider.php is inside slider folder. So basically index.php and slider.php are not inside the same folder.
Javascript code alerts the data properly. But in my php code (ajax.php file) the value of $_POST['section'] is empty. What is the problem with my code. I tried googling everything and tried a few codes but it still doesn't work. Please help me out
Try this instead:
$.ajax({
type: "POST",
url: 'ajax.php',
data: { 'section': temp},
success: function(data)
{
alert(data);
}
});
It is quite possible that your server does not understand the string you have constructed ( "section="+temp ). When using ajax I prefer sending objects since for an object to be valid it requires a certain format.
EDIT1:
Try this and let me know if it doesn't work either:
$.post('ajax.php', {'section': temp}, function(data}{
alert(data);
});
Add jquery plugin(jQuery library) ,then only ajax call works
for eg
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
check your input data , whether it contain '&,/' charators,then use encodeURIComponent()
for Ajax Call Eg:
var gym_name = encodeURIComponent($("#gym_name").val());
$.ajax({
type: "POST",
url: "abc.php",
data:string_array,
success: function(msg) {
console.log(msg);
}
});
In abc.php
<?php
$id = $_POST['gym_name'];
echo "The id is ".id;
?>
Give a try to the following (although I cannot work out why #Grimbode's answer is not working):
$("#submit-reg").on( "click", function() {
$.ajax({
type: "POST",
url: 'ajax.php',
data: {'section': 'anniversary'},
success: function(data)
{
alert(data);
}
});
});
Note: I don't know what your underlying code is doing. However, I would suggest not using HTML element properties to handle events for numerous reasons, but separate the JS/event handling appropriately (separate js file(s) (recommended) or inside <script> tags). Read more...

ajax and json object encode and decode into and from php script

i have created a simple html file with a fixed json object. I want to take the object to the php file text.php, encode it, decode it, print it in the php file, and then print it back in the html file.
html file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
</head>
<body>
<script>
var key=45;
var value=65;
var rated = {"key" : key , "value" : value};
var rated_encoded = JSON.stringify(rated);
$.ajax({
type: "POST",
url: "text.php",
dataType:"json",
data: {
"rated" : rated_encoded
},
//success: function(data) {
//document.write(data);
//}
});
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("text.php");
});
});
</script>
<div id="div1"><h6>Result</h6></div>
<button>Get External Content</button>
</body>
</html>
text.php code:
<?php
if(isset($_POST["rated"])){
$rated_json = $_POST["rated"];
$JSONArray = json_decode($rated_json, true);
if($JSONArray !== null){
$key = $JSONArray["key"];
$value = $JSONArray["value"];
}
echo json_encode($rated_json);
}
?>
the
echo json_encode($rated_json);
in the last line of text.php is not working. I don't know if we can't print encoded stuff or something. In place of that line, even if i type echo "hello";, it's not printing in the php file. If there is any way i can print the $JSONArray variable in text.php, that would be great. It would be better if i can encode the json object in the html file itself, send to the php script, decode it there and then send back and print in the html file. Sorry if this question is not worded properly or is very basic. Also, please go slow and explain the code.
You need add contentType: "application/json; charset=UTF-8",
$.ajax({
type: "POST",
url: "text.php",
dataType:"json",
contentType: "application/json; charset=UTF-8",
data: {
"rated" : rated_encoded
},
//success: function(data) {
//document.write(data);
//}
});
the dataType option is just for parsing the received data.
If still not working, add this: processData: false

Deleting a file with ajax javascript and php

I am creating a page where you can upload files and delete them.
My upload is working fine and my download also.
But i cant get my delete working, i want to have the delete using AJAX and a possible confirm box but when i click my button now it doesnt do anything.
The formatoverzicht.php and ajax.php are in the main folder and the files that need to be deleted are in a uploads folder in side the main folder.
Here is my code.
Formatoverzicht.php
<script src="/website/libraries/jquery.js"></script>
<script type="text/javascript">
$('.delete-btn').click(function(filename) {
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { filename: filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>
The Button:
<button data-file="<?php echo $file ?>" class="delete-btn">Delete</button>
Ajax.php:
<?php
if (isset($_POST['filename'])) {
if (unlink(htmlentities( $_POST['filename']))) {
echo "success";
}
}
?>
I am trying to get this fixed for a couple of days now but it still doesnt work.
EDIT:
I am not using this code:
<script src="/website/libraries/jquery.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$('.delete-btn').on('click',function() {
filename=$(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { 'filename': filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
})
});
</script>
and i now get: event.returnValue is deprecated. Please use the standard event.preventDefault() instead. as an error. But the code still doesnt delete or do anything.
It is because filename is totally undefined. You should use something like this:
<script type="text/javascript">
$('.delete-btn').click(function() {
var filename = $(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { 'filename' : filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>
Shouldn't
$('.delete-btn').click(function(filename)
be:
$('.delete-btn').click(function(file) ?
Or retrieve the filename inside the anonymous function like:
$(this).attr('data-file'); ?
<script type="text/javascript">
$('.delete-btn').on('click',function() {
filename=$(this).attr('data-file');
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { filename: filename },
success: function(data) {
if(data == 'success') {
$this = $(this).closest('tr');
$this.remove();
}
}
});
});
</script>
try doing it on('click'), also your filename is not passed to function.
Try this,
HTML:
<button data-file="<?php echo base64_encode($file); ?>" class="delete-btn">Delete</button>
ajax.php
<?php
if (isset($_POST['filename'])) {
$file = base64_decode($_POST['filename']);
if(is_file($file)){
if (unlink($file)) {
echo "success";
}
}else{
echo "there is no file found (". $file.")";
}
}
?>
Your button click is not handled because the javascript is not triggered. You need to wrap your javascript in jQuery 'ready()' statement, like so:
$( document ).ready(function() {
// your stuff
});
Then you should set your filename variable, as suggested by the others, like so:
filename=$(this).attr('data-file');
instead of passing it directly to the function...
Also, check that the filename that is send to ajax.php matches the original filename. The path should also match off course, since deleting is a filesystem action. Either use the full system path when deleting (or a relative path) or make sure that ajax.php is inside the same directory as the file you want to delete

Categories

Resources