I have setup my CI in a sub directory under my apache /localhost/ci_app/
Now I have some JS file under /localhost/ci_app/assets/js/code.js
Inside code.js I load a script dynamically
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = "/assets/js/another_script.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'my_other_script'));
In CI config I have $config['base_url'] = '/ci_app/'; but everytime I load the page I get the script calling http://localhost/assets/js/another_script.js.
I need the script to be pointing to http://localhost/ci_app/assets/js/another_script.js
you could do it in two ways,
your js script could call this function and it will give you the base url you want
(function(d, s, id){
var js, fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) {return;}
js = d.createElement(s); js.id = id;
js.src = getBaseUrl() + "/assets/js/another_script.js";
fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'my_other_script'));
function getBaseUrl() {
var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
return base_url;
}
and you could change your base_url in config like this
$config['base_url'] = 'http://localhost/ci_app/';
and it could work.
You could add <base href="<?php echo base_url(); ?>"> inside the <head> of your page. This resolves all relative paths to your $config['base_url'] setting.
Related
i am create simple image uploading system with help of stack over flow thanks with jsp with ajax.
image uploaded successfully.but after upload the image i want get the alert message what i wrote inside the ajax success function but it didn't work.after uploaded the image i got [{"success":"success"}] only
what i tried so far i attached below.
index.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-giJF6kkoqNQ00vy+HMDP7azOuL0xtbfIcaT9wjKHr8RbDVddVHyTfAAsrekwKmP1" crossorigin="anonymous">
</head>
<body>
<form id="upload-form" class="upload-box" action="upl.jsp" method="post" enctype="multipart/form-data">
<input type="file" id="file" name="file" />
<input type="submit" id="upload-button" value="upload" />
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Dropify/0.2.2/js/dropify.min.js"></script>
<script>
$(function() {
$('#upload-form').ajaxForm({
success: function(msg) {
alert("File has been uploaded successfully");
},
error: function(msg) {
$("#upload-error").text("Couldn't upload file");
}
});
});
</script>
</body>
</html>
upl.jsp
<%#page import="org.json.simple.JSONObject"%>
<%#page import="org.json.simple.JSONArray"%>
<%# page import="java.io.*,java.sql.*,java.util.zip.*" %>
<%
JSONArray list = new JSONArray();
JSONObject obj = new JSONObject();
String saveFile="";
String contentType = request.getContentType();
if((contentType != null)&&(contentType.indexOf("multipart/form-data") >= 0)){
DataInputStream in = new DataInputStream(request.getInputStream());
int formDataLength = request.getContentLength();
byte dataBytes[] = new byte[formDataLength];
int byteRead = 0;
int totalBytesRead = 0;
while(totalBytesRead < formDataLength){
byteRead = in.read(dataBytes, totalBytesRead,formDataLength);
totalBytesRead += byteRead;
}
String file = new String(dataBytes);
saveFile = file.substring(file.indexOf("filename=\"") + 10);
saveFile = saveFile.substring(0, saveFile.indexOf("\n"));
saveFile = saveFile.substring(saveFile.lastIndexOf("\\") + 1,saveFile.indexOf("\""));
int lastIndex = contentType.lastIndexOf("=");
String boundary = contentType.substring(lastIndex + 1,contentType.length());
int pos;
pos = file.indexOf("filename=\"");
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
pos = file.indexOf("\n", pos) + 1;
int boundaryLocation = file.indexOf(boundary, pos) - 4;
int startPos = ((file.substring(0, pos)).getBytes()).length;
int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
File ff = new File("F:/123/"+saveFile);
FileOutputStream fileOut = new FileOutputStream(ff);
fileOut.write(dataBytes, startPos, (endPos - startPos));
fileOut.flush();
fileOut.close();
obj.put("success", "success");
list.add(obj);
out.println(list.toJSONString());
out.flush();
%>
<%
Connection connection = null;
PreparedStatement psmnt = null;
try{
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection("jdbc:mysql://localhost/ems","root","");
psmnt = connection.prepareStatement("insert into employee(photo) values(?)");
psmnt.setString(1, saveFile);
int s = psmnt.executeUpdate();
}
catch(Exception e){
e.printStackTrace();
}
}
%>
what we have to do inside the upl.jsp page inorder to redirect to ajax success function.
I'm collecting data from a form and sending to a controller
$('form').submit(function(e){
e.preventDefault();
var supplier = $('select[name="supplier"]').val();
var reqdate = $('input[name="reqdate"]').val();
var priority = $('input[name="priority"]:checked').val();
if( supplier !='' && reqdate !=''){
var Material_ID = [];
var Material_Name = [];
var Mat_Quantity =[];
var Unit_Price =[];
var Cost =[];
$('.matid').each(function(){
Material_ID.push($(this).text());
});
$('.matname').each(function(){
Material_Name.push($(this).text());
});
$('.unitprice').each(function(){
Unit_Price.push($(this).text());
});
$('.matqty').each(function(){
Mat_Quantity.push($(this).text());
});
$('.matcost').each(function(){
Cost.push($(this).text());
});
var _token = $('input[name="_token"]').val();
$.ajax({
url:"{{ route('purchase.sessionstore') }}",
method:"POST",
data:{supplier:supplier,reqdate:reqdate,priority:priority,Material_ID:Material_ID,Material_Name:Material_Name,Unit_Price:Unit_Price,Mat_Quantity:Mat_Quantity,Cost:Cost,_token:_token},
success:function(data){
alert(data);
}
});
}
in the controller, I'm trying to put all variables into a Session
public function storeSessionData(Request $request){
if($request){
$supplier = $request->get('supplier');
$duedate = $request->get('reqdate');
$priority = $request->get('priority');
$token = $request->get('_token');
$materialid = $request->get('Material_ID');
$materialname = $request->get('Material_Name');
$matqty = $request->get('Mat_Quantity');
$unitprice = $request->get('Unit_Price');
$cost = $request->get('Cost');
$cart[] = array($supplier, $duedate,$materialid,$priority,$materialname,$matqty,$unitprice,$cost);
Session::set('cart', $cart);
return $cart;
}
}
I want to open a view with session data to show ordered items (just like a page to confirm cart)
What I want to do - collect data from a dynamic form and display them with a second view, on that view I will save them to database
how can I do it, please explain
<body>
<form id="form1" modelAttribute="uploadForm" enctype="multipart/form-data">
<label for="sampleText">Please enter a text </label>
<input id="sampleText" name="sampleText" type="text" /> <br/>
,
<label for="sampleFile">Please select a file</label>
<input id="sampleFile" name="files[0]" type="file" style="border: solid 1px black" /> <br/>
<label for="sampleFile1">Please select a file</label>
<input id="sampleFile1" name="files[1]" type="file" style="border: solid 1px black" /> <br/>
<input id="uploadBtn" type="button" value="Ajax Submit" onClick="Checkfiles();"></input>
</form>
<script type="text/javascript">
function Checkfiles()
{
var fup = document.getElementById('sampleFile');
var fileName = fup.value;
var ext = fileName.substring(fileName.lastIndexOf('.') + 1);
if(ext == "gif" || ext == "GIF" || ext == "JPEG" || ext == "jpeg" || ext == "jpg" || ext == "JPG" || ext == "doc" || ext == "txt")
{
performAjaxSubmit();
}
else
{
alert("Upload Gif or Jpg images only");
fup.focus();
return false;
}
}
function performAjaxSubmit() {
var sampleText = document.getElementById("sampleText").value;
var sampleFile = document.getElementById("sampleFile").files[0];
var sampleFile1= document.getElementById("sampleFile1").files[1];
var formdata = new FormData();
formdata.append("files[0]", sampleFile);
formdata.append("files[1]", sampleFile1);
var xhr = new XMLHttpRequest();
xhr.open("POST","save.html", true);
xhr.send(formdata);
xhr.send(formdata);
}
</script>
in the controller side
#RequestMapping( value = "/save", method = RequestMethod.POST )
public String save( #ModelAttribute( "uploadForm" ) FileUploadForm uploadForm,
BindingResult result,
Model map ) throws IllegalStateException, IOException
{
List<MultipartFile> files = uploadForm.getFiles();
List<String> fileNames = new ArrayList<String>();
if( null != files && files.size() > 0 )
{
for( MultipartFile multipartFile : files )
{
if( multipartFile.getSize() > 0 )
{
}
InputStream inputStream = null;
inputStream = multipartFile.getInputStream();
if( multipartFile.getSize() > 10000 )
{
System.out.println( "File Size exceeded:::" + multipartFile.getSize() );
}
String fileName = multipartFile.getOriginalFilename();
fileNames.add( fileName );
System.out.println( fileName );
//Handle file content - multipartFile.getInputStream()
File dest = new File( "C:/Aslam/files/" + fileName );
multipartFile.transferTo( dest );
}
}
System.out.println( "save.html is called" );
map.addAttribute( "files",
fileNames );
return "file_upload_success";
}
The requirement is to use ajax with spring without submitting the form, but the problem in the above code is that files[1] is not saved,
I am not sure whats happening - either xhr is not passing the files[1] to the controller or controller is not reading the files[1]
Please somebody help me i am new to ajax
The following code worked for me using Apache file upload ..
In Javascript
var fd = new FormData();
fd.append('file',packageFile);
fd.append('file',xmlFile);
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() { });
xhr.send(fd);
In Spring contoller
public String save(HttpServletRequest request, HttpServletResponse httpServletResponse) {
boolean isMultipart;
String response = null;
String myFileName = null;
String filename = null;
isMultipart = ServletFileUpload.isMultipartContent(request);
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload upload = new ServletFileUpload(factory);
try {
List fileItems = upload.parseRequest(request);
Iterator i = fileItems.iterator();
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
InputStream in = fi.getInputStream();
filename = UPLOAD_FILE_DIR + sessionId + "/" + fi.getName();
if (filename.endsWith(".zip")) {
myFileName = fi.getName();
} else if(filename.endsWith(".xml")) {
myFileName = fi.getName();
}
File fd = new File(UPLOAD_FILE_DIR + sessionId + "/" + myFileName);
final File parent_directory = fd.getParentFile();
FileOutputStream fos = new FileOutputStream(fd);
byte[] buffer = new byte[4096];
int length;while ((length = in.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
fos.close();
}
}
EDIT: The following is the Javascript code to get the selected files and adding them to FormData
packageFile = $.find(".fileselector")[0].files[0];
xmlFile = $.find(".fileselector")[1].files[0];
var fd = new FormData();
fd.append('file',packageFile);
fd.append('file',xmlFile);
Following is my XMLHttpRequest
var xhr = new XMLHttpRequest();
xhr.open("POST", url, true);
xhr.onreadystatechange = function() { });
xhr.send(fd);
Below is the HTML tags for uploading files
<input id="upf_local_fileinput1" type="file" name="myFile" path="fileData" class="fileselector">
<input id="upf_local_fileinput2" type="file" name="myFile" path="fileData" class="fileselector">
Try the below code if you still have problem because I remember that in some version of Spring the above code didn't worked.
MultipartHttpServletRequest multi = (MultipartHttpServletRequest) request;
Map fileMap = multi.getFileMap();
Iterator fileIt = fileMap.keySet().iterator();
while (fileIt.hasNext()) {
String fileKey = (String) fileIt.next();
MultipartFile file = (MultipartFile) fileMap.get(fileKey);
if (file != null) {
bufReader = new BufferedReader(new InputStreamReader(file.getInputStream()));
} else {
System.out.println("Invalid file");
}
String str;
File file = new File(imeiFilePath);
FileWriter fw = new FileWriter(file);
BufferedWriter bw = new BufferedWriter(fw);
while ((str = bufReader.readLine()) != null) {
if (bw != null) {
bw.write(str);
bw.newLine();
}
}
if (bw != null) {
bw.flush();
bw.close();
}
}
Ajax
<script type="text/javascript">
var stopTime =0;
var scoreCheck = function ()
{
$.ajax({
url: 'http://127.0.0.1/ProgVsProg/main/checkScoreRoundOne',
success:function(output){
if(output !='Instruction'){
console.log(output);
clearTimeout(scoreCheck);
}
else
console.log(output);
stopTime = setTimeout(scoreCheck, 1000);
}
});
}
stopTime = setTimeout(scoreCheck,1000);
</script>
Controller
public function checkScoreRoundOne(){
$id = $this->session->userdata('userID');
$battleID = $this->lawmodel->getBattle($id);
foreach($battleID as $row){
$Rscore = $row->requestedScore;
$Cscore = $row->challengerScore;
if($Cscore == '1'){
$rID = $this->lawmodel->getID($row->challengerID);
foreach($rID as $row){
echo $row->username."Got the correct answer";
}
}
else if($Rscore == '1'){
$cID =$this->lawmodel->getID($row->requestedID);
foreach($cID as $row){
echo $row->username."Got the correct answer";
}
}
else
echo "Instruction";
}
}
Im confused in the code above
In ajax, why when the output !='Instruction' it will display "Instruction" and when the output == 'Instruction' it will display $row->username got the correct answer.
And how can i stop the setTimeout when the Cscore == 1 or Rscore ==1?
I think cleartimeout will not just stop the setTimeout..
Plss help...Im new in ajax..
Im using codeigniter
About the clearTimeout:
clearTimeout(stopTime);
Im trying to build something like images bookmarklet site like Pinterest, but somehow some of the website doesnt grab any image. Some are works just fine. Also as additional information, I use jquery wookmark as the grid templates.
Here are the codes im currently use... I dont know if its right or simply i used the wrong method to retrieve the images. Cheers guys in advance for any comment or help... really appreciated.
-- html
<ul id="tiles"></ul>
<div id="loader">
<div id="loaderCircle" style="display:none"></div>
</div>
-- javascript
<script type="text/javascript">
function loadData() {
isLoading = true;
var link_pin ='http://www.somewebsite.com';
$('#loaderCircle').show();
$.ajax({
url: '<?php echo(base_url('index.php/home/pin_ajax'))?>',
dataType: 'json',
data: {link_pin:link_pin},
success: onLoadData
});
};
function onLoadData(data) {
isLoading = false;
$('#loaderCircle').hide();
var html = '';
var i=0, length=data.length, returns_data;
for(; i<length; i++) {
var link_foto = data[i];
var newImg = new Image();
newImg.src = link_foto;
var height = newImg.height;
var width = newImg.width;
var image_click="image_clicks('"+link_foto+"')";
if (width >="200" && height >="200"){
html += '<li onclick="'+image_click+'" id="image_'+i+'">';
html += '<a>';
html += '<div class="back_tristlist">';
html += '<span class="hover-icon icon-text">🔍</span>';
html += '<img src="'+link_foto+'">';
html += '</div>';
html += '</a>';
html += '<div class="space_image"></div>';
html += '</li>';
}
}
$('#tiles').append(html);
handler = $('#tiles li');
handler.wookmark(options);
};
</script>
-- php
public function pin_ajax(){
extract($_GET);
$page = file_get_contents($link_pin);
error_reporting(0);
$doc = new DOMDocument();
#$doc->loadHTML($page);
$images = $doc->getElementsByTagName('img');
echo($images);
$_datas[]="";
foreach($images as $image){
$raw_img_url = $image->getAttribute('src');
$img_final_link = $raw_img_url;
$img_url = explode('http://www.', $raw_img_url);
$img_check = $img_url[1];
if($img_check==''){
$img_url = explode('http://', $raw_img_url);
$img_check = $img_url[1];
if($img_check!=''){ $img_check_error=1; }
if($img_check==''){ $img_check_error=2; }
}
$_datas[] = ($img_check);
}
$output = json_encode($_datas);
echo($output);
}