JQuery/ajax page update help pls - javascript

Hi Am new to Jquery/ajax and need help with the final (I think) piece of code.
I have a draggable item (JQuery ui.draggable) that when placed in a drop zone updates a mysql table - that works, with this:
function addlist(param)
{
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');}
});
}
but what I cannot get it to do is "reload" another page/same page to display the updated results.
In simple terms I want to
Drag & drop
Update the database
Show loading gif
Display list from DB table with the updated post (i.e. from the drag & drop)

The are many ways of doing it. What I would probably do is have the PHP script output the content that needs to be displayed. This could be done either through JSON (which is basically data encoded in JavaScript syntax) or through raw HTML.
If you were to use raw HTML:
function addlist(param)
{
$.ajax(
{
type: 'POST',
url: 'ajax/addtocart.php',
data: 'img=' + encodeURIComponent(param),
dataType: 'html',
beforeSend: function()
{
$('#ajax-loader').css('visibility','visible');
},
success: function(data, status)
{
// Process the returned HTML and append it to some part of the page.
var elements = $(data);
$('#some-element').append(elements);
},
error: function()
{
// Handle errors here.
},
complete: function()
{
// Hide the loading GIF.
}
});
}
If using JSON, the process would essentially be the same, except you'd have to construct the new HTML elements yourself in the JavaScript (and the output from the PHP script would have to be encoded using json_encode, obviously). Your success callback might then look like this:
function(data, status)
{
// Get some properties from the JSON structure and build a list item.
var item = $('<li />');
$('<div id="div-1" />').text(data.foo).appendTo(item);
$('<div id="div-2" />').text(data.bar).appendTo(item);
// Append the item to some other element that already exists.
$('#some-element').append(item);
}

I don't know PHP but what you want is addtocart.php to give back some kind of response (echo?)
that you will take care of.
$.ajax({
type: "POST",
url: "ajax/addtocart.php",
data: 'img='+encodeURIComponent(param),
dataType: 'json',
beforeSend: function(x){$('#ajax-loader').css('visibility','visible');
success: function(response){ /* use the response to update your html*/} });

Related

Pull different data strings from JSON via Ajax

My client has a jobs board whose API data I'm pulling via Ajax. I can parse the "jobs" data but cannot seem to pull any thing else. For instance, this works to pull the names of job listings to a select box:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
$.each(json.jobs, function(i, value) {
$('#myselect').append($('<option>').text(value.title).attr('value', value.title));
});
}
});
But when I change "json.jobs" to anything else like "json.offices" or "json.locations" nothing is pulled. How do I go about accurately targeting these data strings to cull together for a complete careers page? Appreciate any guidance whatsoever thanks.
This is the JSON if you need to take a look:
https://api.greenhouse.io/v1/boards/roivantsciences/jobs/
try pull location.name for all jobs $.each(json.jobs, function(i, value) { $('#myselect').append($('<option>').text(value.location.name).att‌​r('value', value.location.name)); });
Ive done a small test:
$.ajax({
url:'https://api.greenhouse.io/v1/boards/roivantsciences/jobs/',
type:'GET',
data: 'q=' + "",
dataType: 'json',
success: function( json ) {
console.log(json)
}
});
What I got back from console is that your json object only has 'jobs' as the top attribute in it.
You have to go through it like this to get locations:
$.each(json.jobs, function(i, value) {
console.log(value.location);
});
then you have the location object inside this you got the attribute 'name'
so u can get the names with value.location.name

(this).parent().find not working for getting response in ajax call

$(".content-short").click(function() {
$(".content-full").empty();
var contentid=$(this).parent().find(".content-full").attr('data-id');
var content=$(this).parent().find(".content-full");
alert(contentid);
var collegename = $(this).attr('data-id');
$.ajax({
type: "post",
url: "contenthome.php",
data: 'collegename=' + collegename,
dataType: "text",
success: function(response) {
$content.html(response);
}
});
});
here the alert displays the specific data-id but
content=$(this).parent().find(".content-full");
this didn't displays data in content-full div with that specific data-id
anything wrong in the code or something else?
the query displays data if i use(."content-full"); instead of
$(this).parent().find(".content-full");
Inside the ajax callback you are using $content, but you declare your variable as content. May that be the problem?
Your question is not clear. What are you trying to achieve?

Image does not update when appending newly inserted row using jquery ajax

I want to insert data using ajax and show that newly inserted data in a div, but the record (i.e. image and name ) does not get updated it.
I don't want to reload page, the newly entered record should be shown without page reload, but it shows only the initial name and image.
I can't understand whats the problem. Please help. Following is the code i am using static data which is stored in a variable as an example:
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
d = new Date();
var img_name='amit.png'+'?'+d.getTime();
var s_name='Ashish';
$('#main').prepend('<img alt="client" id="p_img"><h1>'+s_name+'</h1>');
$('#p_img').attr("src", "image/Amit.png");
},
error: function (error)
{
}
});
Shouldn't the src attribute use the response/variable/generated file name?
Like this:
$('#p_img').attr("src", '/image/' + img_name);
Instead of this:
$('#p_img').attr("src", "image/Amit.png");
It can be two reasons :
the image you are prepending to the DOM is not yet in the DOM when you are trying to add the src
or the src is not existing (should be an absolute or relative path)
Try to prepend the image with the src
$('#main').prepend('<img alt="client" src="ABSOLUTE_OR_RELATIVE_PATH/image/Amit.png"><h1>Amit</h1>');
Also there is no need to create a variable s_name which you only use once.
you can done it easily by returing List of data and populating the div with ajax success result.
jQuery.ajax({
type: "POST",
url: 'add.php',
data: data,
mimeType:"multipart/form-data",
contentType: false,
cache: false,
processData:false,
dataType: 'json',
success: function (data) {
// in data you are getting your result ...
// now for ease split json format data and store in list
// m not sure about your formate so m assuming at first index it
//should be image URL so..
var res = data.split(",");
var imgSrc = res[0];
$('#main').prepend('<img alt="client" id="p_img"/>');
$('#p_img').attr("src", imgSrc);
},
error: function (error)
{
}
});

Reading a file into a string in jQuery/JS

The title is quite self-explanatory: I need to read a HTML file through jQuery and store its contents into a string variable.
I tried using .load and $.get, but they wouldn't do what I needed.
This is the code I've tried so far, based on the comments below, but they didn't populate my template variable at all:
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template);
AND:
var template = "";
var fileUrl = "includes/twig/image_box.twig";
jQuery.get(fileUrl).then(function(text, status, xhr){
var html = String(text);
template.concat(html);
// console.log(html); // WORKS!
});
console.log(template); // Does not work
It's weird why this isn't working. Weird for me at least. This is how I'd populate a variable in PHP so I've carried the same logic to JS. Maybe there is an alternative way?
P.S:V I've also tried all alternative ways, like concatenating with += and assigning inside the callback function to template with =, but nothing worked.
Thanks to the ones who are trying to help me!
Maybe you should try a AJAX request with $.ajax()
Check the jQuery API here
$.ajax({
url: 'yourHTMLfile.html',
type: 'get',
async: false,
success: function(html) {
console.log(html); // here you'll store the html in a string if you want
}
});
DEMO
EDIT: Added a demo!
I reread your question and I noticed you're calling the console log right above the ajax request but you forgot the ajax is asynchronous that means the page will do a request and only will set the template value when the response return with success(if it returns). So the console.log(template) don't appears because it may be not loaded yet.
var template = "";
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
success: function(html) {
var twig = String(html);
template.concat(twig);
console.log(template); // the change!
}
});
or
$.ajax({
url: 'includes/twig/image_box.twig',
type: 'get',
async: false,
success: function(html) {
var twig = String(html);
template.concat(twig);
}
});
console.log(template); // the change!
You can try this:
//as you see I have used this very page's url to test and you should replace it
var fileUrl = "/questions/20400076/reading-a-file-into-a-string-in-jquery-js";
jQuery.get(fileUrl).then(function(text, status, xhr){
//text argument is what you want
});
and if it won't work try if your browser can open the file. if it could you'd better try ajax method in jQuery if not you might have some problems regarding permissions or somethings like that in you application server.

HTTP error on adding large data using jquery ajax

I have created a good html/javascript program in displaying ajax in my jqgrid. But just recently, I noticed that when I try to save large or many data to save to my table line, it will return http:error.
I really don't understand whats wrong when I can successfully saved small numbers of lines. Someone told me that it was my html/javascript that has a problem since when I try to trace it with delphi(the one I used to create my webservice), it doesn't go into my code (when saving many lines), and will go into my code if only less than 10 line data that i will save (there's no error in tracing). Here's a data that I am sending to my webservice/html request:
{
"SessionID":"66KuzRH1w1sWCM188q4k8BTJb5ijG81v",
"operation":"add",
"transaction_date":"7/27/2011",
"supplier_id":"10000000108",
"wood_specie_id":"1",
"lines":[
{"plank_number":"1","thickness":"4","width":"6","length_t":"8","quantity":"1","board_foot":"16.00","wood_classification_id":"1","price":"15"},
{"plank_number":"2","thickness":"45","width":"6","length_t":"8","quantity":"1","board_foot":"180.00","wood_classification_id":"1","price":"15"},
.
.
.
.
{"plank_number":"22","thickness":"3","width":"6","length_t":"8","quantity":"1","board_foot":"12.00","wood_classification_id":"1","price":"15"},
{"plank_number":"23","thickness":"4","width":"6","length_t":"7","quantity":"1","board_foot":"14.00","wood_classification_id":"1","price":"15"}
],
"scaled_by":"JAYSON","tallied_by":"TALLIED BY","checked_by":"CKECKED BY","total_bdft":"582.84","final":""
}
here's the code in adding my line data:
function tallyAddData(){
var datas = {
"SessionID": $.cookie("SessionID"),
"operation": "add",
//"transaction_num":$('#tallyNo').val(),
"transaction_date":$('#tallyDate').val(),
"supplier_id":$('#supplierInput').attr("name"),
"wood_specie_id":$('#woodSpecie').attr("name"),
"lines":plank_data,
"scaled_by":$('#tallyScaled').val().toUpperCase(),
"tallied_by":$('#tallyTallied').val().toUpperCase(),
"checked_by":$('#tallyChecked').val().toUpperCase(),
"total_bdft":$('#tallyTotal').val(),
"final":"",
};
alert(JSON.stringify(datas));
$.ajax({
type: 'GET',
url: 'processjson.php?' + $.param({path:'update/tallyHdr',json:JSON.stringify(datas)}),
dataType: primeSettings.ajaxDataType,
success: function(data) {
if ('error' in data)
{
showMessage('ERROR: ' + data["error"]["msg"]);
}
else{
$('#tblTallyHdr').trigger('reloadGrid');
}
}
});
}
your are using the Query string to pass the data - the Query string size is limited (http://en.wikipedia.org/wiki/Query_string)
I recommend on passing the data as post:
$.ajax({
type: 'POST',
url: url,
data: data,
success: success,
dataType: dataType
});
you can also read about Jquery post (http://api.jquery.com/jQuery.post/)

Categories