JQuery, HTML5 Uploader - get data response after upload - javascript

How can I get data response after uploading image and insert that response into a tag as data-id attribute (after successful post I am getting id of inserted image ). Where in the function is happening this? The function:
function img_upload(url) {
{
var fileTemplate = "<div id=\"{{id}}\">";
fileTemplate += "<div class=\"preview\"></div>";
fileTemplate += "<div class=\"filename\">{{filename}}</div>";
fileTemplate += "Obriši Sliku";
fileTemplate += "</div>";
function slugify(text) {
text = text.replace(/[^-a-zA-Z0-9,&\s]+/ig, '');
text = text.replace(/-/gi, "_");
text = text.replace(/\s/gi, "-");
return text;
}
$("#dropbox").html5Uploader({
postUrl: url,
onClientLoadStart: function (e, file, data) {
var upload = $("#upload");
if (upload.is(":hidden")) {
upload.show();
}
upload.append(fileTemplate.replace(/{{id}}/g, slugify(file.name)).replace(/{{filename}}/g, file.name));
console.log(data);
},
onClientLoad: function (e, file) {
$("#" + slugify(file.name))
.find(".preview")
.append("<img class=img_upload title=\"" + file.name + "\" src=\"" + e.target.result + "\" alt=\"\">")
.on('click', function () {
img_name = $(this).find('.img_upload').attr('title'),
url = '<?php echo base_url() ?>admin/galerija_naslovna_slika/' + img_name.replace(/\s/g, "_") + '/' + id;
$.post(url);
});
var img_delete = $('.image_delete');
delete_image(img_delete);
},
onServerLoad: function (e, file) {
}
});
}
}

I know this is old, But what I do is pass the id in the postURL.
So something like: /image_upload/212/
You need to use apache's mod_rewrite though to get to your php file. And then you can simply look at the request path to get the ID.
Or the other way to do it is pass the ID as a POST var.
You could have a hidden "input" with the id as the value.
docid = $('#docid').val();
$.ajax({
url: '/upload.php',
type: "POST",
data: {'docid': docid},
success: function(data, status, jqXHR) {
set_status('info', 'Success!');
},
error: function(jqXHR, status, err) {
set_status('danger', 'Error: ' + err + ' - ' + status);
},
complete: function(jqXHR, status) {
}
});

Related

Returning data from asynchronous function through callback comes as undefined

The function gets the data from URL and then passes it to another function where the listing is done dynamically based on users in the list of URL. I tried callback but I am getting the following error service.js:9 Uncaught TypeError: callback is not a function
This is the function in one js file:
function GetData(callback, passdata) {
$.ajax({
type: 'GET',
url: 'https://jsonplaceholder.typicode.com/users',
success: function (response) {
debugger;
console.log(response);
return callback(response, passdata);
}
});
}
This is the function in another js file (wherein I want to list the data from the URL):
$(document).ready(function () {
var getData = GetData();
var $data = $('#dataDisplay');
function listData(response, passdata) {
var data = response;
var passeddata = passdata;
$.each(data, function (i, users) {
$data.append('<li>' + '<span>' + users.name + '</span>' + '<br> <span>' + users.email + '</span>' + ' </li>');
});
//adds li dynamically
$("li").append('<i class="material-icons delete">' + "delete" + '</i>');
$("li").append('<i class="material-icons edit">' + "edit" + '</i>');
}
});
You can use anonymous function in document ready =>
GetData(function(result){
// can do further things here..
console.log(result);
}, passdata);
this should fix your error.
For me this worked
function GetData(callback) {
debugger;
$.ajax({
type: 'GET',
url: ' http://localhost:3000/users',
success: function (response) {
console.log(response);
callback(response);
}
});
}
In another js file call the function back and pass the response parameter for that is where the array of the API was saved.
GetData(function (response) {
debugger;
var data = response;
var $data = $('#dataDisplay');
$.each(data, function (i, users) {
$data.append('<li>' + '<span class="table .table-striped .table-hover">' + users.first_name + '</span>' + ' <span class="table .table-striped .table-hover">' + users.email + '</span>' + ' </li>');
});
//adds li dynamically
$("li").append('<i class="material-icons delete ">' + "delete" + '</i>');
$("li").append('<i class="material-icons edit ">' + "edit" + '</i>');
});
});
How can JavaScript know that listData is the callback function if you don't specify it?
You just declared the listData function, but you aren't using it anywhere. There is not any sort of magic that will do it for you :)
Just change
var getData = GetData();
To
var getData = GetData(listData, 'something');

How can I select multiple checkboxes at once?

I have a html table which is created dynamically. Im adding check box for each row.
$.each(data, function(id, value) {
rows.push('<tr><td><input type="checkbox" autocomplete="off" class="chkbox" name="chkbox" value="'+value.site+':'+value.client+'"></td><td>' + id + '</td><td>' + value.machine + '</td><td>' + value.state + '</td><td>' + value.date_processed + '</td><td><button type="button" onclick="resetSite(\''+ value.site+'\',\''+value.client+'\')">Reset</td></tr>');
});
I want to select multiple rows at once and need to POST the values to my backend service.
Currently my JavaScript function is like;
$(document).on('change','.chkbox',function () {
var sites = [];
var value = $(this).val();
var res = value.split(":");
$.each($("input[class='chkbox']:checked"), function(){
sites.push(res[0]);
});
alert("sites are: " + sites.join(", "));
$.ajax({
type: "POST",
url: "http://localhost:8080/cache/setProcessing?site="+res[0]+"&client="+res[1],
/*data: {
chkbox: value
},*/
error : function(xhr, textStatus, errorThrown) {
alert("Failed. Error : " + errorThrown);
}
});
});
in the above function my alert box shows same site multiple times if I selecet more than one row.
How can I overcome this?
Change
$(document).on('change','.chkbox',function () {
var sites = [];
var value = $(this).val();
var res = value.split(":");
$.each($("input[class='chkbox']:checked"), function(){
sites.push(res[0]);
});
alert("sites are: " + sites.join(", "));
$.ajax({
type: "POST",
url: "http://localhost:8080/cache/setProcessing?site="+res[0]+"&client="+res[1],
/*data: {
chkbox: value
},*/
error : function(xhr, textStatus, errorThrown) {
alert("Failed. Error : " + errorThrown);
}
});
});
cor·re·spond·ing
$(document).on('change','.chkbox',function () {
var sites = [];
$.each($("input[class='chkbox']:checked"), function(){
var value = $(this).val(); // must me be inside the each
var res = value.split(":"); // must me be inside the each
sites.push(res[0]);
});
alert("sites are: " + sites.join(", "));
$.ajax({
type: "POST",
url: "http://localhost:8080/cache/setProcessing?site="+res[0]+"&client="+res[1],
/*data: {
chkbox: value
},*/
error : function(xhr, textStatus, errorThrown) {
alert("Failed. Error : " + errorThrown);
}
});
});
Because in the previous code it only gets the value of the current checkbox you've clicked.
So you must put the value and res inside the each function to know all checkboxes that have been checked and get there corresponding value..

JSON to HTML not rendering into HTML via ID

I am using PHPstorm IDE and i'm trying to render the following JSON and it gets stuck showing only the <ul></ul> without spitting the <li>'s into HTML the each function. Any idea what could be the issue?
thanks.
Script.js:
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
var items = [];
$.each(data, function (key, val) {
items.push('<li id=" ' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
And the JSON:
{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}
My HTML is just an a href that spits out the click ID:
Get JSON
<script>
$(document).ready(function(){
$("button").click(function(){
$.getJSON("demo_ajax_json.js", function(result){
$.each(result, function(i, field){
$("div").append(field + " ");
});
});
});
});
</script>
<button>Get JSON data</button>
By Using this Method You can Easily get Your JSON value In HTML
Try this one :)
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data){
var html = "<ul>";
items = data.map(function(obj){
html += "<li id='" + obj.id + "'>" + obj.mesi + "</li";
});
html += "</ul>";
$('body').append(html);
I would try with some like this
$(function(){
$('#clickme').click(function (){
//fetch json file
$.ajax({
url:'data.json',
dataType: 'json',
success: function(data){
// uncomment line below if data is a single JSON
// data = [data]
var items = [];
// we create a list where we will append the items
var list = document.createElement("ul");
data.forEach(function(item){
// we create a list item
var listItem = document.createElement("li");
// we set the attributes
listItem.setAttribute("id", item.id ); // item.id or the property that you need
// we add text to the item
listItem.textContent = item.mesi;
// We append the list item to the list
list.appendChild(listItem);
});
// we append the list to the body
$("body").html(list);
},
statusCode: {
404: function(){
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
Try like this:
success: function(data){
var items = '';
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
for multiple objects
success: function(datas){
var items = '';
$.each(datas, function (i,data) {
$.each(data, function (key, val) {
items += '<li id=" ' + key + '">' + val + '</li>';
});
});
ul = $('<ul/>').html(items);
$('body').append(ul);
}
output
<ul>
<li id=" id">1</li>
<li id=" mesi">mesima 0</li>
<li id=" done_bool">1</li>
<li id=" id">2</li>
<li id=" mesi">mesima 1</li>
.
.
</ul>
Try like this:
$(function() {
$('#clickme').click(function() {
// fetch json file
$.ajax({
url : 'data.json',
dataType : 'json',
// please confirm request type is GET/POST
type : 'GET',
success : function(data) {
// please check logs in browser console
console.log(data);
var ulHtml = "<ul>";
$.each(data, function(key, obj) {
ulHtml += '<li id="' + obj.id + '">' + obj.mesi + '</li>';
});
ulHtml += "</ul>";
// please check logs in browser console
console.log(ulHtml);
$('body').append(ulHtml);
},
error : function(jqXhr, textStatus, errorThrown) {
console.log(errorThrown);
alert(textStatus);
}
});
});
});
<button id="clickme">Get JSON data</button>
I log json data and created ul html, Please check logs in browser console
I'm not sure how you want to output each item, so I made a simple suggestion, you can easily change the HTML to what you need. Here is working code:
index.html
<!DOCTYPE html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
</head>
<body>
Get JSON
<script>
$(function() {
$('#clickme').click(function() {
//fetch json file
$.ajax({
url: 'data.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, val) {
// the HTML output for each item
var done = (val.done_bool === '1') ? 'true' : 'false';
items.push('<li id=" ' + val.id + '">' + val.mesi + ': ' + done + '</li>');
});
$('<ul/>', {
'class': 'tasks',
html: items.join('')
}).appendTo('body');
},
statusCode: {
404: function() {
alert('there was a problem with the server. try again in a few secs');
}
}
});
});
});
</script>
</body>
</html>
data.json
[{"id":"1","mesi":"mesima 0","done_bool":"1"},{"id":"2","mesi":"mesima 1","done_bool":"0"},{"id":"3","mesi":"mesima 2 ","done_bool":"1"},{"id":"4","mesi":"mesima 3","done_bool":"1"}]
I also created a __jsfiddle__ so you can test it directly. (The AJAX call is simulated with the Mockjax library): https://jsfiddle.net/dh60nn5g/
Good to know:
If you are trying to load the JSON from another domain, you may need to configure CORS (Cross-origin resource sharing):
https://en.wikipedia.org/wiki/Cross-origin_resource_sharing
Isn't this supposed to be a GET request? i think you are missing the method on your Ajax request. You should add
method: 'GET'
to your ajax request. I think this is a big deal in making ajax request.

Codeigniter Jquery Ajax: How to loop returned data as html

Im new to JQuery AJAX thing, this is my script:
$(document).ready(function() {
$("#city").change(function() {
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(block_list) {
// WHAT TO PUT HERE ?
},
});
}
});
If i put console.log(block_list) it returns the right data with JSON type:
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
What is the correct way to loop the returned data? I did this to see what the loop returned:
$.each(block_list, function() {
$.each(this, function(index, val) {
console.log(index + '=' + val);
});
});
But it was totally messed up :(, if the looped data is correct I also want to put the id as a value and block name as a text for my <option> tag how to do that? thank you.
UPDATE
Sorry, I have try both answer and its not working, I try to change my code to this:
$("#city").change(function(){
var city_id = $("#city").val();
$.get("<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id, function(data) {
$.each(data, function(id, val) {
console.log(val.id);
});
});
});
it returns :
**UNDEFINED**
I also try to change it into val[id] or val['id'] still not working, help :(
$.each(block_list, function(id, block){
console.log('<option value="' + block['id'] + '">' + block['block'] + '</option>')
});
The output would be:
<option value="1601">A</option>
<option value="1602">B</option>
try something like:
success: function(data, textStatus, jqXHR) {
if (typeof(data)=='object'){
for (var i = 0; i < data.length; i++) {
console.log(data[i].id + ':' + data[i].id_city);
}
}
}
if ur json output is in this format
[{"id":"1601","id_city":"16","block":"A"},
{"id":"1602","id_city":"16","block":"B"}]
then
var city_id = $("#city").val();
if (city_id != '') {
$.ajax({
type: "POST",
url: "<?php echo base_url() ?>index.php/home/get_block_by_id/" + city_id,
success: function(data) {
$.each(data, function(index)
{
console.log(data[index]['id']);
$('#'+ddname+'')
.append($("<option></option>")
.text(data[index]['id']+"-"+data[index]['block']));
});
},
});
}

how to show the loader dynamically until all the image load in jquery mobile phonegap listview

am having trouble to showing loader untill all the image is load in the listview.the following code is used in my app.it shows the loader untill all the image is load but the problem is , append the last src value to all the image attribute src.please help me.
$.ajax({
url: "http://www.some.com/",
type: 'POST',
data: param,
dataType: "jsonp",
success: function (result) {
$.each(result.results, function (k, v) {
var searchPic = "http://www.some.com" + $.trim(v.eventIcon);
var localarray = new Array();
var c = v.eventText;
strs = c.slice(0, 60);
$('[data-role="listview"]').append('<li> ' + '<img alt="img" class="pic1" src=" ">' + '<h4 >' + v.eventTitle + '</h4>' + '<p>' + strs + '...' + '</p></li>');
$('[data-role="listview"]').listview('refresh');
imgload(searchPic);
});
$('[data-role="listview"]').append('<li id="no-results">There is no record found based on your search criteria, please refine your search.</li>');
}
});
function imgload(tx) {
$('.pic1').load(function () {
$.mobile.loading('hide');
}).attr('src', tx);
}
});

Categories

Resources