Re-Run a Ajax script? - javascript

If I have a script like below that's ran to load a table with data injected into it from an external PHP file on to the page.
<script>
$(document).ready(function(){
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
success : function(text)
{
response = text;
}
});
alert(response);
});
</script>
I have another script down below where a user can add records to the database.
<script id="sosurce" language="javascript" type="text/javascript">
$("#newitemadd").click(function(){
$('#New').modal('show');
$("#insertResults").click(function(){
var getname = $('#getname').val();
var getquant = $('#getquant').val();
var getprice = $('#getprice').val();
var getdesc = $('#getdesc').val();
$.ajax({
url: 'api2.php',
data: "name="+getname+"&quantity="+getquant+"&price="+getprice+"&description="+getdesc,
success: function(data)
{ $('#New').modal('hide');
$("#success").html(data);
$('#success').slideDown().delay(3000).slideUp().reload
},
error: function() {
$("#failure").alert('show');
}
});
});
});
</script>
It works fully as intended but, how can I get the first script to Re-Run so the table that's inserted onto the page is refreshed to show the new results that were just added?

you can do like this .
<script>
var renderTable = function() {
var response = '';
$.ajax({ type: "GET",
url: "Records.php",
success : function(text)
{
response = text;
}
});
alert(response);
}
// Call function onload
jQuery(function($){
renderTable();
$(".refreshBtn").click(function(){
renderTable();
})
});
</script>

Move first code into an function like
<script>
$(document).ready(LoadData);
function LoadData() {
var response = '';
$.ajax({
type: "GET",
url: "Records.php",
success : function(text) {
response = text;
}
});
alert(response);
};
</script>
And call this function from other function, example does it on success
<script id="sosurce" language="javascript" type="text/javascript">
$("#newitemadd").click(function() {
$('#New').modal('show');
$("#insertResults").click(function() {
var getname = $('#getname').val(),
getquant = $('#getquant').val(),
getprice = $('#getprice').val(),
getdesc = $('#getdesc').val();
$.ajax({
url: 'api2.php',
data:
"name="+getname+"&quantity="+getquant+"&price="+getprice+"&description="+getdesc,
success: function(data) {
$('#New').modal('hide');
$("#success").html(data);
$('#success').slideDown().delay(3000).slideUp().reload
// Call load data again to refresh the table
LoadData();
},
error: function() {
$("#failure").alert('show');
}
});
});
});
</script>

Related

Display one item of my choice rather than the whole list items in ajax upon success

I've got an AJAX code, that does POST reqeusts and displays results upon success. The displayed results are in JSON format and from a different website. The result displays all of the list items, but now I want to display only one item of my choice at the same time, instead of displaying all the items. I've been trying to use the each() and slice() functions, but I think I'm not using them correctly or I don't have any idea of how to deal with the problem. Please help, I'm new to AJAX and JQuery.
This is the code I have:
jQuery.ajax({
async:false,
url : "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type : "post",
dataType : "jsonp",
jsonp: "jsoncallback",
success : function(jsonData){
if (jsonData.product_display!=='') {
/**The code below will display all the items under a div="product_dispay"*/
jQuery('#product_display').append(jsonData.product_display);
//I want a code that will display one item of my choice at this section.
}else{
alert(jsonData.error);
}
},
error:function(){
alert('fail');
}
});
You can access the contents of the #product_display element with jQuery. The API returns HTML data so you can render it in the page, then using jQuery find the data within the HTML and do whatever you want with it.
I have added this code into your original code.
(function($){
var data = [];
var creatik = null;
$('#product_display .business_list').each(function(){
var price = $(this).find('p a span.price').text();
var bld = $(this).find('p a span.bld').text();
var img = $(this).find('.image_area a img').prop('src');
//How to check each logo
if("Creatick" === bld){
creatik = $(this).clone();
}
data.push({
price: price,
bld: bld,
img: img
});
});
//You can use this data as you please
console.log(data);
//you can replace the contents of the #product_display container with the one logo that you want
$('#product_display .business_detail').html(creatik);
//
})(jQuery);
This is the final code.
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></script>
<script type="text/javascript">
function getbrandsbyuser(user) {
var postData = {user: user};
jQuery.ajax({
async: false,
url: "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type: "post",
dataType: "jsonp",
jsonp: "jsoncallback",
success: function (jsonData) {
console.log(jsonData);
if (jsonData.product_display !== '') {
jQuery('#product_display').append(jsonData.product_display);
(function($){
var data = [];
var creatik = null;
$('#product_display .business_list').each(function(){
var price = $(this).find('p a span.price').text();
var bld = $(this).find('p a span.bld').text();
var img = $(this).find('.image_area a img').prop('src');
//How to check each logo
if("Creatick" === bld){
creatik = $(this).clone();
}
data.push({
price: price,
bld: bld,
img: img
});
});
//You can use this data as you please
console.log(data);
//you can replace the contents of the #product_display container with the one logo that you want
$('#product_display .business_detail').html(creatik);
//
})(jQuery);
} else {
alert(jsonData.error);
}
},
error: function () {
alert('fail');
}
});
}
jQuery(".image_area").each(function ()
{
jQuery(this).hover(
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_" + id).stop(true, true).fadeIn('slow', function () {
jQuery(this).children(".published_content_" + id).css("display", "block");
jQuery(this).children(".published_content_" + id).stop(true, true).animate({"opacity": 1}, 400);
});
},
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_" + id).stop(true, true).fadeOut('slow', function () {
jQuery(this).children(".published_content_" + id).css("display", "none");
jQuery(this).children(".published_content_" + id).stop(true, true).animate({"opacity": 0}, 400);
});
}
);
});
</script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function () {
getbrandsbyuser("Sarfraz300");
});
</script>
</head>
<body>
<div id="product_display"></div>
</body>
</html>
I hope it helps.
This is the code:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script></script>
<script type="text/javascript">
function getbrandsbyuser(user) {
var postData = {
user: user
};
jQuery.ajax({
async:false,
url : "http://brandroot.com/index.php?option=com_brands&controller=brands&task=getbrandsbyuser",
data: postData,
type : "post",
dataType : "jsonp",
jsonp: "jsoncallback",
success : function(jsonData){
if (jsonData.product_display!=='') {
jQuery('#product_display').append(jsonData.product_display);
}else{
alert(jsonData.error);
}
},
error:function(){
alert('fail');
}
});
}
jQuery(".image_area").each(function ()
{
jQuery(this).hover(
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_"+id).stop(true, true).fadeIn('slow', function(){
jQuery(this).children(".published_content_"+id).css("display","block");
jQuery(this).children(".published_content_"+id).stop(true, true).animate({"opacity": 1}, 400);
});
},
function () {
id = jQuery(this).attr("rel");
jQuery(this).children(".published_content_"+id).stop(true, true).fadeOut('slow', function(){
jQuery(this).children(".published_content_"+id).css("display","none");
jQuery(this).children(".published_content_"+id).stop(true, true).animate({"opacity": 0}, 400);
});
}
);
});
</script>
<script type="text/javascript">
jQuery.noConflict();
jQuery(document).ready(function(){
getbrandsbyuser("Sarfraz300");
});
</script>
</head>
<body>
<div id="product_display"></div>
The result displayed upon success is in html format.
jsonData.product_display[i]
has not worked.

Youtube Search js function

While i was searching at stackoverflow, i found the code below :
$(document).ready(function () {
$("#show").click(function () {
getYoutube($("#Search").val());
});
});
function getYoutube(title) {
$.ajax({
type: "GET",
url: yt_url = 'http://gdata.youtube.com/feeds/api/videos?q=' + title + '&format=5&max-results=1&v=2&alt=jsonc',
dataType: "jsonp",
success: function (response) {
if (response.data.items) {
$.each(response.data.items, function (i, data) {
var video_id = data.id;
var video_title = data.title;
var video_viewCount = data.viewCount;
$("#result").html(video_id);
});
} else {
$("#result").html('false');
}
}
});
}
How can i edit the code to keep only the function?
I want to be able to use it like that : getYoutube(my_keywords);
Also, how can i save the function output to variable? something like :
var_name = getYoutube(my_keywords);
would be ok?
Thnx! ;)
yes, you can use it as without $(document).ready. No, function does not return anything
To "return" value from Ajax:
$.ajax({
...
success: function(dataFromServer) {
processServerOutput(dataFromServer);
}
});
function processServerOutput(someString) {
alert(someString);
}

Suppressing and adding parameters for ajax call

I am trying to make an ajax call for two separate click events. The difference is for the second click event the variable testOne should not be part of the call and instead there would be a new variable. How should I approach this?
var varOne = '';
var varTwo = '';
var varThree = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: {
testOne: varOne,
testTwo: varOne
}
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
varOne = 'xyz123';
varTwo = '123hbz';
testAjax();
});
$('.clickTwo').click(function(){
//varOne = 'xyz123'; // I dont need this for this click
varTwo = '123hbz';
varThree = 'kjsddfag'; // this gets added
testAjax();
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
Make some like this
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data= {
varOne: 'xyz123',
varTwo: '123hbz',
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data= {
varThree : 'kjsddfag',
varTwo: '123hbz',
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
You can also do the same in other way with minimum line of code, you can call the ajax on click event and pass the data based on the element triggered the click event.
like this:
$('.ajax').click(function(e){
if($(this).hasClass('clickOne')){
var data= { varOne: 'xyz123'; varTwo: '123hbz'; }
}else{
var data= { varThree : 'kjsddfag'; varTwo: '123hbz'; }
}
$.ajax({
type: "POST",
dataType: 'json',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
e.preventDefault();
});
<div class="ajax clickOne"></div>
<div class="ajax clickTwo"></div>
In this way you can put as many conditions for different data variable.
You should be doing it like this:
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data
}).done(function(data) {
$('.result').html(data);
});
}
$('.clickOne').click(function(){
var data {
varOne = 'xyz123',
varTwo = '123hbz'
}
testAjax(data);
});
$('.clickTwo').click(function(){
var data = {
varTwo = '123hbz',
varThree = 'kjsddfag'
}
testAjax(data);
});
<div class="clickOne"></div>
<div class="clickTwo"></div>
This way you absolute control over which variables are added to which ajax call. You should not use global variables unless you really need them to be global, which doesn't seem to be the case.
You can pass whatever JavaScript object to the data parameter of the ajax method.
I just wanted to add something. I often hide value inside the value attribute of the button tags to produce something like this.
I haven't been able to test this of course but I thought it was worth mentioning.
jquery:
var fields = '';
function testAjax(){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: fields
}).done(function(data) {
$('.result').html(data);
});
}
$('#btn').click(function(){
var varCount = 0;
var vars = $(this).val().split('|');
$.each( vars, function( key, value ) {
varCount++;
fields = fields + 'var' + varCount + '=' + value + '&';
});
fields = fields.slice(0,-1);
$(this).val('123hbz|kjsddfag');
testAjax();
});
html:
<button id="btn" value="xyz123|123hbz"></button>
A more optimized and cleaner version -
var varTwo='junk1'
var varOne='junk2'
var varThree='junk3'
function testAjax(data){
$.ajax({
type: "POST",
dataType: 'html',
url: "http://someblabla.php",
data: data,
}).done(function(data) {
$('.result').html(data);
});
}
$('.ajaxClick').click(function(){
var data={};
if(this.classList.contains('clickOne')){
data.varOne=varOne;
data.varTwo=varTwo;
}else{
data.varThree=varThree;
data.varTwo=varTwo;
}
testAjax(data);
});
<div class="ajaxClick clickOne"></div>
<div class="ajaxClick clickTwo"></div>

How to pass extra parameter in jquery post request from outside click event?

Hi i have jquery request like below ,
$('#filterForm').submit(function(e){
e.preventDefault();
var dataString = $('#filterForm').serialize();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn')
{
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
}
else
{
document.getElementById("2011").className='yearOn';
}
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});
and my Form is like ,
<form method="post" name="filterForm" id="filterForm">
<!-- some input elements -->
</form>
Well, I am triggering jquery submit on submit event of a form ,(it's working fine)
I want pass one extra parameter inside form which is not in above form content but it's outside in page
it's like below
[Check this image link for code preview][1]
So how can i trigger above event , on click of , element with class yearOn ( check above html snippet ) and class yearOff , with additional parameter of year set to either 2011 or 2010
$(document).ready(function () {
$('#filterForm').submit(function (e) {
e.preventDefault();
var dataString = $('#filterForm').serialize();
if ($("#2011").hasClass('yearOn')) {
dataString += '&year=2011';
$("#2011").removeClass('yearOn').addClass('yearOff');
}
else {
$("#2011").removeClass('yearOff').addClass('yearOn');
}
$.ajax({
url: "/myServlet",
type: "POST",
data: dataString,
success: function (data) {
/*var a = data;
alert(data);*/
}
});
});
});
1.) If you are using jQuery already, you can use the $.post() function provided by jquery. It will make your life easier in most cases.
2.) I have always had a successful post with extra parameters this way:
Build you extra parameters here
commands={
year:'2011'
};
Combine it with your form serialize
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
Perform your post here
$.post("myServlet",data,
function(data) {
/*var a = data;
alert(data);*/
}
);
OR use $.ajax if you really love it
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
In the end, here is the full code the way you are doing it now
$('#filterForm').submit(function(e){
e.preventDefault();
var class2011 = document.getElementById("2011").className;
//var validate = validateFilter();
alert(dataString);
if(class2011=='yearOn') {
dataString+='&year=2011';
document.getElementById("2011").className='yearOff';
} else {
document.getElementById("2011").className='yearOn';
}
commands={
year:'2011'
};
var dataString=$.param(commands)+'&'+$("#filterForm").serialize();
alert (dataString);
$.ajax({
type: "POST",
url: "myServlet",
data: dataString,
success: function(data) {
/*var a = data;
alert(data);*/
}
});

Data variable in jquery ajax function

I'm trying to use the code below, but it's not working:
UPDATED WORKING:
$(document).ready(function() {
$('.infor').click(function () {
var datasend = $(this).html();
$.ajax({
type: 'POST',
url: 'http://domain.com/page.php',
data: 'im_id='+datasend',
success: function(data){
$('#test_holder').html(data);
}
});
});
});
As you can see I used $datasend as the var to send but it doesn't return the value of it, only its name.
I would change
$datasend = $(this).html;
to
var datasend = $(this).html();
Next I would change
data: 'im_id=$datasend',
to
data: 'im_id='+datasend,

Categories