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

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)
{
}
});

Related

(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?

loading gif with ajax request

$(".content-short").click(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
success: function(response){
$(".content-full").html(response);
$('.loadingmessage').hide();
}
});
});
//collegeselect.php// is for loading data from database, //.loadingmessage// is for gif
when i am using this for the first time it displays gif,but the gif is not displayed after the 1st click as the data retrieved is already available in content-full from previous ajax request,
how to display it on every click on content short class?
That happens because you are replacing the actual content with loading GIF image with your response.
So, when you click first time it displayed and after the ajax call sucess as per the code you have replaced the content of .content-full and there is no GIF available then.
Solution : To resolve either send the same image tag with response or Move the loader image out side the .content-full.
Add beforeSend : function() before success in your request.
try
$(".content-short").live(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
beforeSend : function()
{
$('.loadingmessage').show();
},
success: function(response){
$(".content-full").html(response);
$('.loadingmessage').hide();
}
});
});
From the comments, I gather that the img is within the .content-full container. The problem is that the img is removed when ajax succeeds since you're doing $(".content-full").html(). One way to fix it is to move the img out of the container. Another way is to store a reference to the img and add it back along with the response via .append() or .prepend() as below.
$(".content-short").click(function() {
var ID = $(this).attr('data-id');
$('.loadingmessage').show();
$.ajax({
type: "post",
url: "collegeselect.php",
data: 'ID=' + ID,
dataType: "text",
success: function(response) {
var $content = $(".content-full");
var $loaderImg = $content.find('.loadingmessage').hide();
$content.html(response).prepend($loaderImg);
}
});
});
Here is a demo mimicking the behaviour thru setTimeout.

Pass Array and String from Javascript to PHP with AJAX

I have the following ajax call.
My addList variable holds a string: list=Sports&list=Cars&list=Outdoor&new_list=123123
I want to grab the addList in my PHP file as
$_POST['list'] is an array with values Sports, Cars, Outdoor
$_POST['new_list'] is a string 123123
But I couldnt convert the POST string into right forms.
I can create arrays/loops in both sides but it didnt feel right.
Whats the convenient way of doing it?
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: "action=post-list&nonce="+ajax_var.nonce+"&post_list=&post_id="+post_id+"&" + addList,
success: function(count){
alert("done");
}
});
Any help will be appreciated. thanks!
try using followig code.
you just neeed to locate your form if and url to pass values to :
var form = new FormData($('#form_id')[0]);
form.append('view_type','addtemplate');
$.ajax({
type: "POST",
url: "savedata.php",
data: form,
cache: false,
contentType: false,
processData: false,
success: function(data){
//alert("---"+data);
alert("Settings has been updated successfully.");
window.location.reload(true);
}
});
this will pass all form element automatically.
Working and tested code.
When you pass variable with the ajax method from jQuery, you can pass array like this :
jQuery
var myArray = newArray();
myArray.push("data1");
myString = "data2";
jQuery.ajax({
type: "post",
url: ajax_var.url,
data: {array:myArray, param2:myString},
^name ^value
success: function(count){
alert("done");
}
});
PHP
echo $_POST['array'][0]; // data1
echo $_POST['param2']; // data2
Change your addList variable to this:
list[]=Sports&list[]=Cars&list[]=Outdoor&new_list=123123
PHP will parse the items named list[] into an array, and you'll find the values as $_POST['list'][0],$_POST['list'][1],$_POST['list'][2]

how do I access a HTML element from javascript using id,the html element belongs to another html document

Continued from the question title:
also the other html document is loaded in the parent using AJAX,like this:
$.ajax({
url: 'calender.aspx',
cache: false,
dataType: "html",
success: function (data) {
$(".mainBar").html(data);
}
});
I need to get a table from calender.aspx which has id 'tableID';
From within your success callback:
$(data).find("#tableID");
In your example, you appear to be inserting the document into your document via the line $(".mainBar").html(data);. That being the case, you can then just get it via $("#tableId") once you've done that:
$(".mainBar").html(data);
var theTable = $("#tableId");
If your goal is not to append everything, but to do something else, you can build up a disconnected DOM tree by doing $(data), and then search it via find:
var theTable = $(data).find("#tableId");
As a side note, you can just use .load. However, you would do this:
var $table;
$.ajax({
url: 'calender.aspx',
cache: false,
dataType: "html",
success: function (data) {
$table = $(data).find('#tableID');
$(".mainBar").empty().append($table);
}
});
Same thing with .load:
var $table;
$('.mainBar').load('calendar.aspx #tableID', function(html) {
$table = $(html).find('#tableID');
});

JQuery/ajax page update help pls

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*/} });

Categories