Remove multiple records serverside with ajax and jquery - javascript

I'm trying to delete multiple tables with a same class name, my js code snippet works once and it doesn't loop to the next table unless the page is refreshed again.
when I comment my ajax call and just run it plain jquery it works fine. , I think there's an issue with my ajax call somewhere....
This jsfiddle url http://jsfiddle.net/ehsansajjad465/ExnkV/ has the snippet without the ajax....how do I make sure the ajax call works properly rather refreshing my page every time?
$(".closeprod").live("click",function(e){
e.preventDefault();
elem = $(this).parents('.tbl');
//get serial number
prodsn = $(".tbl").find(".prodsn:eq(0)");
sn = $(prodsn[0]).html().substr(5);
tpl = "anything";
url = "delprod.asp?email=<%=email%>&sn=" + sn + "&t=" + tpl + "&nf=notfeatured";
//remove product from xml file
$.get(url, function(data,status){
if (data == "OK") {
//remove product from template
elem.remove();
}else{
alert("opps something is wrong")
}
});
});

I figured it out this line prodsn = $(".tbl").find(".prodsn:eq(0)"); should be prodsn = elem.find(".prodsn:eq(0)"); and it worked like this

Related

Assigning javascript variable to java variable

I know I can't use javascript variable inside java code so can anyone explain me what I can do instead?
function init(srcc) {
<%if (session.getAttribute("status") != null && session.getAttribute("status").equals("member")) {%>
alert(srcc + " ");
<%application.setAttribute(session.getAttribute("currentuser"), srcc);%>
<%}%>
in this line:
<%application.setAttribute(session.getAttribute("currentuser"), srcc);%>
I can't read the srcc variable as it's assigned in javascript, this function called when I press a button in jquery, code:
var $lightbox = $("<div class='lightbox'></div>");
var $img = $("<img>");
var $caption = $("<p class='caption'></p>");
var $btn = $("<div align='center'> <INPUT TYPE='BUTTON' VALUE='Add to cart'></div>");
$lightbox.append($img).append($caption).append($btn);
$('body').append($lightbox);
$('.gallery li').click(function(e) {
e.preventDefault();
var src = $(this).children('img').attr("src");
var cap = $(this).children('img').attr("alt");
$btn.off('click').on('click', function(da) {
$(document).ready(function() {
init(src);
});
});
$img.attr('src', src);
$caption.text(cap);
$lightbox.fadeIn('fast');
$lightbox.click(function() {
$lightbox.fadeOut('fast');
});
});
I use it in an "add to cart" button, I want the server to keep data of whom added it to the cart and what he added. (srcc equals what he added and session.getAttribute("currentuser") is whom added).
Thanks guys.
You can send that JavaScript variable to Java using an AJAX request
You would have to have a serverside route set up to handle this request coming in and process the sent data.
Since I already see jQuery being used in your code, I'll use this AJAX function in my example code. You can send an HTTP request without your browser reloading the page in this way:
$.get("/urlOfCartHandler/?parameterName=" + javaScriptVariableContainingDataYouWantToSend, function(data) {
//Request was a success
}).fail(function() {
//Request failed
});

yiiGridView pagination is not working after first ajax call

I have one page there are four gridviews in one page. When i click on any pagination page button (ex : 1,2,3,4,5,6) It takes me to that page without any problem [via ajax]. And replaces new html with old html. But now when i click on pagination button it just redirects to the url. It do not get loaded via ajax. Whole page gets refreshed.
It works when on click of one page button.If i initialize through console. Like when i put this and press enter in console then It will work for next page call. And for again i have to initialize via console to make it work for next page button press.
$('#answer-grid').yiiGridView({'ajaxUpdate':['answer-grid'],'ajaxVar':'ajax','pagerClass':'pager','loadingClass':'grid-view-loading','filterClass':'filters','tableClass':'table table-responsive','selectableRows':1,'pageVar':'saved_card_id_page'});
I try to add script in ajax loaded copntent but it did not worked. Not event Alert got excuted.
<script type='application/javascript'>
alert("This is also not getting executed. When it comes from ajax content.")
</script>
I know may be they strips down the all content except the gridview div. But the same thing works in other project.
I use afterAjaxUpdate parameter did this.
'afterAjaxUpdate'=>"function(id, data){
var newHtml = $('<div></div>');
newHtml.append(data);
var scriptExecute = newHtml.find('#scriptExecute');
$('body').append(scriptExecute);
}",
so now my script is getting executed as i append this to body. This was the scripts i append to the body as i can only do this way It is not proper way but it works..
<?php
$true = Yii::app()->request->isAjaxRequest;
if($true)
{
?>
<script type="application/javascript" id="scriptExecute" >
//alert("Execute this");
jQuery('#share-grid').yiiGridView({'ajaxUpdate':['share-grid'],'ajaxVar':'ajax','pagerClass':'pager','loadingClass':'grid-view-loading','filterClass':'filters','tableClass':'table table-responsive','selectableRows':1,'pageVar':'CardShare_page','afterAjaxUpdate':function(id, data){
var newHtml = $('<div></div>');
newHtml.append(data);
var scriptExecute = newHtml.find('#scriptExecute');
$('body').append(scriptExecute);
}});
jQuery('#rate-grid').yiiGridView({'ajaxUpdate':['rate-grid'],'ajaxVar':'ajax','pagerClass':'pager','loadingClass':'grid-view-loading','filterClass':'filters','tableClass':'table table-responsive','selectableRows':1,'pageVar':'RatingLike_page','afterAjaxUpdate':function(id, data){
var newHtml = $('<div></div>');
newHtml.append(data);
var scriptExecute = newHtml.find('#scriptExecute');
$('body').append(scriptExecute);
}});
jQuery('#saved-card-grid').yiiGridView({'ajaxUpdate':['saved-card-grid'],'ajaxVar':'ajax','pagerClass':'pager','loadingClass':'grid-view-loading','filterClass':'filters','tableClass':'table table-responsive','selectableRows':1,'pageVar':'SavedCard_page','afterAjaxUpdate':function(id, data){
var newHtml = $('<div></div>');
newHtml.append(data);
var scriptExecute = newHtml.find('#scriptExecute');
$('body').append(scriptExecute);
}});
jQuery('#answer-grid').yiiGridView({'ajaxUpdate':['answer-grid'],'ajaxVar':'ajax','pagerClass':'pager','loadingClass':'grid-view-loading','filterClass':'filters','tableClass':'table table-responsive','selectableRows':1,'pageVar':'saved_card_id_page','afterAjaxUpdate':function(id, data){
var newHtml = $('<div></div>');
newHtml.append(data);
var scriptExecute = newHtml.find('#scriptExecute');
$('body').append(scriptExecute);
}});
</script>

Passing a JavaScript value to PHP on completion of quiz

I have a web page that allows users to complete quizzes. These quizzes use JavaScript to populate original questions each time it is run.
Disclaimer: JS Noob alert.
After the questions are completed, the user is given a final score via this function:
function CheckFinished(){
var FB = '';
var AllDone = true;
for (var QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] < 0){
AllDone = false;
}
}
}
if (AllDone == true){
//Report final score and submit if necessary
NewScore();
CalculateOverallScore();
CalculateGrade();
FB = YourScoreIs + ' ' + RealScore + '%. (' + Grade + ')';
if (ShowCorrectFirstTime == true){
var CFT = 0;
for (QNum=0; QNum<State.length; QNum++){
if (State[QNum] != null){
if (State[QNum][0] >= 1){
CFT++;
}
}
}
FB += '<br />' + CorrectFirstTime + ' ' + CFT + '/' + QsToShow;
}
All the Javascript here is pre-coded so I am trying my best to hack it. I am however struggling to work out how to pass the variable RealScore to a MySql database via PHP.
There are similar questions here on stackoverflow but none seem to help me.
By the looks of it AJAX seems to hold the answer, but how do I implement this into my JS code?
RealScore is only given a value after the quiz is complete, so my question is how do I go about posting this value to php, and beyond to update a field for a particular user in my database on completion of the quiz?
Thank you in advance for any help, and if you require any more info just let me know!
Storing data using AJAX (without JQuery)
What you are trying to do can pose a series of security vulnerabilities, it is important that you research ways to control and catch these if you care about your web application's security. These security flaws are outside the scope of this tutorial.
Requirements:
You will need your MySQL database table to have the fields "username" and "score"
What we are doing is writing two scripts, one in PHP and one in JavaScript (JS). The JS script will define a function that you can use to call the PHP script dynamically, and then react according to it's response.
The PHP script simply attempts to insert data into the database via $_POST.
To send the data to the database via AJAX, you need to call the Ajax() function, and the following is the usage of the funciton:
// JavaScript variable declarations
myUsername = "ReeceComo123";
myScriptLocation = "scripts/ajax.php";
myOutputLocation = getElementById("htmlObject");
// Call the function
Ajax(myOutputLocation, myScriptLocation, myUsername, RealScore);
So, without further ado...
JavaScript file:
/**
* outputLocation - any HTML object that can hold innerHTML (span, div, p)
* PHPScript - the URL of the PHP Ajax script
* username & score - the respective variables
*/
function Ajax(outputLocation, PHPScript, username, score) {
// Define AJAX Request
var ajaxReq = new XMLHttpRequest();
// Define how AJAX handles the response
ajaxReq.onreadystatechange=function(){
if (ajaxReq.readyState==4 && xml.status==200) {
// Send the response to the object outputLocation
document.getElementById(outputLocation).innerHTML = ajaxReq.responseText;
}
};
// Send Data to PHP script
ajaxReq.open("POST",PHPScript,true);
ajaxReq.setRequestHeader("Content-type","application/x-www-form-urlencoded");
ajaxReq.send("username="username);
ajaxReq.send("score="score);
}
PHP file (you will need to fill in the MYSQL login data):
<?php
// MYSQL login data
DEFINE(MYSQL_host, 'localhost');
DEFINE(MYSQL_db, 'myDatabase');
DEFINE(MYSQL_user, 'mySQLuser');
DEFINE(MYSQL_pass, 'password123');
// If data in ajax request exists
if(isset($_POST["username"]) && isset($_POST["score"])) {
// Set data
$myUsername = $_POST["username"];
$myScore = intval($_POST["score"]);
} else
// Or else kill the script
die('Invalid AJAX request.');
// Set up the MySQL connection
$con = mysqli_connect(MYSQL_host,MYSQL_user,MYSQL_pass,MYSQL_db);
// Kill the page if no connection could be made
if (!$con) die('Could not connect: ' . mysqli_error($con));
// Prepare the SQL Query
$sql_query="INSERT INTO ".TABLE_NAME." (username, score)";
$sql_query.="VALUES ($myUsername, $myScore);";
// Run the Query
if(mysqli_query($con,$sql))
echo "Score Saved!"; // Return 0 if true
else
echo "Error Saving Score!"; // Return 1 if false
mysqli_close($con);
?>
I use these function for ajax without JQuery its just a javascript function doesnt work in IE6 or below. call this function with the right parameters and it should work.
//div = the div id where feedback will be displayed via echo.
//url = the location of your php script
//score = your score.
function Ajax(div, URL, score){
var xml = new XMLHttpRequest(); //sets xmlrequest
xml.onreadystatechange=function(){
if (xml.readyState==4 && xml.status==200){
document.getElementById(div).innerHTML=xml.responseText;//sets div
}
};
xml.open("POST",URL,true); //sets php url
xml.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xml.send("score="score); //sends data via post
}
//Your PHP-script needs this.
$score = $_POST["score"]; //obtains score from POST.
//save your score here
echo "score saved"; //this will be displayed in the div set for feedback.
so call the javascript function with the right inputs, a div id, the url to your php script and the score. Then it will send the data to the back end, and you can send back some feedback to the user via echo.
Call simple a Script with the parameter score.
"savescore.php?score=" + RealScore
in PHP Side you save it
$score = isset ($_GET['score']) ? (int)$_GET['score'] : 0;
$db->Query('INSERT INTO ... ' . $score . ' ...');
You could call the URL via Ajax or hidden Iframe.
Example for Ajax
var request = $.ajax({
url: "/savescore.php?score=" + RealScore,
type: "GET"
});
request.done(function(msg) {
alert("Save successfull");
});
request.fail(function(jqXHR, textStatus) {
alert("Error on Saving");
});

AJAX parse + Yahoo YQL returning no results?

I'm working on a script that gets all the <table> elements from an external website by going through Yahoo's YQL. This has worked fine recently, but it stopped working as of today. I'm not entirely sure why, all websites used to work with this code:
<script type="text/javascript">
$(document).ready(function () {
var container = $('#target');
function doAjax(url) {
if (url.match('^http')) {
$.getJSON("http://query.yahooapis.com/v1/public/yql?"
+ "q=select%20*%20from%20html%20where%20url%3D%22"
+ encodeURIComponent(url)
+ "%22&format=xml'&callback=?",
function (data) {
if (data.results[0]) {
var fullResponse = $(filterData(data.results[0])),
justTable = fullResponse.find("body");
container.append(justTable);
} else {
var errormsg = '<p>Error: could not load the page.</p>';
container.html(errormsg);
}
});
} else {
$('#target').load(url);
}
}
function filterData(data) {
data = data.replace(/<?\/body[^>]*>/g, '');
data = data.replace(/[\r|\n]+/g, '');
data = data.replace(/<--[\S\s]*?-->/g, '');
data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g, '');
data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g, '');
data = data.replace(/<script.*\/>/, '');
data = data.replace(/<img[^>]*>/g, '');
return data;
}
doAjax('http://www.google.com');
});
</script>
I changed the url to google and changed it to find the <body> tag instead of <table> tags to better show its not working. I looked at the URL that it's requesting and it's not showing any content. Not sure what the problem is though.
Have you checked if the "external website" you have crawled has structural changes?
When it has worked before and now not anymore, then my tip is that the site structure has changed.
It looks like the problem was that YQL was down? I just tested it again and it worked out fine. I wish they would tell us in the future if an outage occurred.

Internet Explorer jQuery getJSON not working

im making a small script which gets some data from a database through php using jquery's getJSON method.
the code as shown below:
$(document).ready(function(){
var id = userid;
$('#a-div').after('<div id="data"></div><input type="button" id="getdata" value="Get Data">');
$('#getdata').click(function(){
$.getJSON('http://mysite.com/data.php?id=' + id, function(data) {
var notfound = data['notfound'];
var user = data['user'];
if(notfound == '1'){
$('#data').html("Not found");
}
else{
$('#data').html("Found , user is "+ user);
}
});//end of getJSON
});//end of click
}); //end of document ready
My php script returns JSON data something like this :
If the data is found in database-
{"notfound":"0","user":"john"}
If the data is NOT found in database-
{"notfound":"1","user":"none"}
This works perfectly on Firefox , Google Chrome and Safari , just dosent work in Internet Explorers(7,8,9)
can anyone help me out.
P/S i have tried a few techniques in other posts similar to this one , is not working.
Like changing the the META content-type
Thanks.
Try putting the button inside of the <body> like so:
$("body").append( /* markup for div and btn here */ );
...instead of using after().
Maybe internet explorer is taking long time to add the html, try with live
$('#getdata').live('click', function(){
you are using very ugly code, after body incorrect to write any HTML content, for that you must add in body any div and append your cod to it, and then this code will work in IEs
$(document).ready(function () {
$('#anydiv').html('<div id="data"></div><input type="button" id="getdata" value="Get Data">');
$('#getdata').click(function () {
alert("asd");
$.getJSON('/HowItWork/Index?id=' + 23, function (data) {
var notfound = data['notfound'];
var user = data['user'];
if (notfound == '1') {
$('#data').html("Not found");
}
else {
$('#data').html("Found , user is " + user);
}
}); //end of getJSON
}); //end of click
}); //end of document ready
This works for me- jQuery.support.cors = true;
Find more discussion http://jquery.10927.n7.nabble.com/jQuery-getJSON-response-not-working-with-IE-works-perfectly-in-firefox-safari-td81254.html

Categories