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
Related
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
I'm working on joomla environment. I would like to run small php script by click on button event from JQuery reason I would like to use JQuery is I cannot modified existing component. Current component adding some values on Database from webpage. I would like to do same thing but from back-end with out notify any thing from another PHP file. I was trying something as code but it's not working.
Is there any other way.?
What is wrong in code.?
<script type="text/javascript">
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
$.post("/automate/UpdateMySql.php");
});
}
</script>
You were missing a dot and bracket(with semi-colon) at the end. As per the comments if you want to just Update Date And Time. You can post any random variable to UpdateMySql.php and then Create Date And Time there.
<script type="text/javascript">
var clicked = 0;
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
clicked = 1;
jQuery.post("/automate/UpdateMySql.php" , { click : clicked });
});
});
</script>
In UpdateMySql.php write.
$clicked = $_POST['click'];
if(isset($clicked) && !empty($clicked)) {
$today = date("Y-m-d H:i:s");
$query = "UPDATE table_name date_time=".$today." WHERE anything = 'anything'";
if($query) {
return 'Updated';
} else {
return 'Something Went Wrong';
}
}
Please use:
$(document).ready(function() {
$('#submitButton').click(function(e) {
$.ajax({ type:'POST',
url:'/automate/UpdateMySql.php'
data:{name:'demo',id:"1"},
sucess:function(xhr) {
alert('table updated');
}
});
});
});
if some one need complete answer in future.
<script type="text/javascript">
var clicked = 0;
jQuery(document).ready(function(){
jQuery('#submitButton').click(function(){
clicked = 1;
jQuery.post("/automate/UpdateMySql.php" , { click : clicked });
});
});
</script>
Following are two code blocks, each one is responsible for AJAX call to a PHP file onclick of respective hyperlink:
<script language="javascript" type="text/javascript">
$(".fixed").click(function(e) {
var action_url1 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$(".fixed").colorbox({inline:true, width:666});
$("#fixedPop_url").click(function(event) {
event.preventDefault();
$.get(action_url1, function(data) {
alert("Question status updated successfully");
$("#fix_"+qid).hide();
$("#notfix_"+qid).show();
});
});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
$(".notfixed").click(function(e) {
var action_url2 = $(this).attr('delhref');
var qid = $(this).data('q_id');
$(".notfixed").colorbox({inline:true, width:666});
$("#notfixedPop_url").click(function(event) {
event.preventDefault();
$.get(action_url2, function(data) {
alert("Question status updated successfully");
$("#notfix_"+qid).hide();
$("#fix_"+qid).show();
});
});
$(".c-btn").bind('click', function(){
$.colorbox.close();
});
});
</script>
Now the PHP code snippet from a file is written below to which the AJAX request is made. Actually, the PHP file name to which the AJAX request is going and the parameters passed required are contained in variables action_url1 and action_url1. These are working fine. Until now there is no issue for me. Also the PHP code is working fine.
<?php
$objQuestionIssue = new QuestionIssue;
$op = $_GET['op'];
switch( $op ) {
case "fixed":
$que_issue_data = $objQuestionIssue->UpdateQuestionIssueStatus($question_id, $op);
die();
break;
case "notfixed":
$que_issue_data = $objQuestionIssue->UpdateQuestionIssueStatus($question_id, $op);
die();
break;
}
?>
But the issue I'm facing is getting the alert success message multiple times. It is expected to show the alert message only once but in current scenario it's showing multiple times. Can anyone hep me in correcting this issue please?
You have nested click handlers -
Every time you click on .fixed you are binding a new click handler on #fixedPop_url. And that is why your .get is executing multiple times
you can use .off() to fix this -
$("#fixedPop_url").off('click').on('click',function(event) {
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.
I have a link: Hello.
When someone clicks the link I'd like to check via JavaScript if the page the href-attribute points to exists or not. If the page exists the browser redirects to that page ("www.example.com" in this example) but if the page doesn't exist the browser should redirect to another URL.
It depends on whether the page exists on the same domain or not. If you're trying to determine if a page on an external domain exists, it won't work – browser security prevents cross-domain calls (the same-origin policy).
If it is on the same domain however, you can use jQuery like Buh Buh suggested. Although I'd recommend doing a HEAD-request instead of the GET-request the default $.ajax() method does – the $.ajax() method will download the entire page. Doing a HEAD request will only return the headers and indicate whether the page exists (response codes 200 - 299) or not (response codes 400 - 499). Example:
$.ajax({
type: 'HEAD',
url: 'http://yoursite.com/page.html',
success: function() {
// page exists
},
error: function() {
// page does not exist
}
});
See also: http://api.jquery.com/jQuery.ajax/
A pretty good work around is to proxy. If you don't have access to a server side you can use YQL. Visit: http://developer.yahoo.com/yql/console/
From there you can do something like: select * from htmlstring where url="http://google.com". You can use the "REST query" they have on that page as a starting point for your code.
Here's some code that would accept a full URL and use YQL to detect if that page exists:
function isURLReal(fullyQualifiedURL) {
var URL = encodeURIComponent(fullyQualifiedURL),
dfd = $.Deferred(),
checkURLPromise = $.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20htmlstring%20where%20url%3D%22' + URL + '%22&format=json');
checkURLPromise
.done(function(response) {
// results should be null if the page 404s or the domain doesn't work
if (response.query.results) {
dfd.resolve(true);
} else {
dfd.reject(false);
}
})
.fail(function() {
dfd.reject('failed');
});
return dfd.promise();
}
// usage
isURLReal('http://google.com')
.done(function(result) {
// yes, or request succeded
})
.fail(function(result) {
// no, or request failed
});
Update August 2nd, 2017
It looks like Yahoo deprecated "select * from html", although "select * from htmlstring" does work.
Based on the documentation for XMLHttpRequest:
function returnStatus(req, status) {
//console.log(req);
if(status == 200) {
console.log("The url is available");
// send an event
}
else {
console.log("The url returned status code " + status);
// send a different event
}
}
function fetchStatus(address) {
var client = new XMLHttpRequest();
client.onreadystatechange = function() {
// in case of network errors this might not give reliable results
if(this.readyState == 4)
returnStatus(this, this.status);
}
client.open("HEAD", address);
client.send();
}
fetchStatus("/");
This will however only work for URLs within the same domain as the current URL. Do you want to be able to ping external services? If so, you could create a simple script on the server which does your job for you, and use javascript to call it.
If it is in the same domain, you can make a head request with the xmlhttprequest object [ajax] and check the status code.
If it is in another domain, make an xmlhttprequest to the server and have it make the call to see if it is up.
why not just create a custom 404 handler on the web server? this is probably the more "good-bear" way to do this.
$.ajax({
url: "http://something/whatever.docx",
method: "HEAD",
statusCode: {
404: function () {
alert('not found');
},
200: function() {
alert("foundfile exists");
}
}
});
If you are happy to use jQuery you could do something like this.
When the page loads make an ajax call for each link. Then just replace the href of all the links which fail.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script type="text/javascript">
<!--
$.fn.checkPageExists = function(defaultUrl){
$.each(this, function(){
var $link = $(this);
$.ajax({
url: $link.attr("href"),
error: function(){
$link.attr("href", defaultUrl);
}
});
});
};
$(document).ready(function(){
$("a").checkPageExists("default.html");
});
//-->
</script>
You won't be able to use an ajax call to ping the website because of same-origin policy.
The best way to do it is to use an image and if you know the website you are calling has a favicon or some sort of icon to grab, you can just use an html image tag and use the onerror event.
Example:
function pingImgOnWebsite(url) {
var img = document.createElement('img');
img.style.visibility = 'hidden';
img.style.position = 'fixed';
img.src = url;
img.onerror = continueBtn; // What to do on error function
document.body.appendChild(img);
}
Another way to do this is is with PHP.
You could add
<?php
if (file_exists('/index.php'))
{
$url = '/index.php';
} else {
$url = '/notindex.php';
}
?>
And then
<a href="<?php echo $url; ?>Link</a>