From my previous question(Create json using JavaScriptSerializer), In .ashx file I am printing the json object using:
context.Response.ContentType = "application/json";
context.Response.Write(json);
I am calling this .ashx file from default.aspx which has some javascript function inside its <head> tag.
My question is :
How will I be able to call the javascript function from .ashx file after context.Response.Write(json);?
UPDATE:
My ultimate goal is to achieve Server Side Processing for DataTable.In that i want to bind the rows with context menu using javascript function.
For that I am using following code to call .ashx file:
$('#example').dataTable({
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': '/data.ashx'
});
Are you using ajax requests? In that case, you can use the success method that is available in javascript, as in the following example from w3schools:
function showHint(str)
{
var xmlhttp;
if (str.length==0)
{
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
// You can call your custom method here...
document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","gethint.asp?q="+str,true);
xmlhttp.send();
}
Or if you are using jquery:
$.ajax({
url: "test.html",
context: document.body
}).done(function() {
// You can call your custom method here...
$(this).addClass("done");
});
UPDATE
Check out: http://datatables.net/usage/callbacks The method you can use is: fnInitComplete
e.g.
$('#example').dataTable({
'bProcessing': true,
'bServerSide': true,
'sAjaxSource': '/data.ashx',
'fnInitComplete' : function() {
alert('Your menu population code here!');
}
});
You could use
eval
to evaluate the response as javascript on client-side. But I doubt you really need or want this, it might not be a very elegant solution. So what you want to archieve?
Related
please help bring an array of data. spring is here:
{"news": [{"img": "http://static2.smi2.net/img/160x120/2212764.jpeg", "title": "Усиление слуха в 2 - 3 раза! Уникальная разработка", "url": "http://news.smi2.ru/newdata/news?ad=681120&bl=81060&ct=adpreview&st=16&in=lJUrBQDHL4CgZAoA", "id": "681120"}]}
I do the following:
var massive = JSON.parse('http://news.smi2.ru/data/js/81060.js');
console.log(massive.news.id);
console.log(massive.news.img);
console.log(massive.news.title);
console.log(massive.news.url);
The result is the following error message:
Uncaught SyntaxError: Unexpected token h
use only the native js
You try to parse an url and not a json. You can pass the respone you get and parse it using JSON.parse:
var massive = JSON.parse('{"news": [{"img": "http://static1.smi2.net/img/160x120/2269036.jpeg", "title": "Украинские власти и Саакашвили прокомментировали убийство Немцова", "url": "http://news.smi2.ru/newdata/news?ad=696406&bl=81060&ct=adpreview&st=16&in=uU6IBQAiL4BWoAoA", "id": "696406"}]}');
console.log(massive.news[0].id);//outputs 696406
To clear it up you can make an request to the url you want for example using an ajax call:
$.ajax({
url: "http://news.smi2.ru/data/js/81060.js",
dataType : "json"
}).done(function(res) {
console.log(res.news[0].id);//outputs 696463
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You cannot parse Json from url .If you need data from URI do send an ajax call for that :-
//Simple javascript example.
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
var massive = JSON.parse(xmlhttp.responseText);
console.log(massive.news[0].id);
console.log(massive.news[0].img);
console.log(massive.news[0].title);
console.log(massive.news[0].url);
}
}
xmlhttp.open("GET","http://news.smi2.ru/data/js/81060.js",true);
xmlhttp.send();
So I'm trying to build a pretty simple website, to learn basic webdesign. It's just a random quote generator - you click on a button and it prints some famous quote. Anyway, I try to use ajax to get the quote, so I use this function:
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
but no matter what I type into RandomQuote.php, even if it's something like :
<?php
echo 'Hello, world';
?>
nothing shows up in the quote "div', it just becomes blank. I really have no idea what's the problem here. Thanks for the help!
Well, I'm not sure about much, but are you calling your function? You put your ajax inside loadXMLDoc() , so you probably have to call it. Another way is to put your ajax into an addEventListener so when a user clicks on something, it'll execute. If that's not the problem, try making sure your element in your html page with the id of "quote" is spelled correctly. Sometimes the latter scenario is always the problem for me.
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
console.log( "Load was performed." );
});
Don't forget to include jQuery.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
This is my ajax function, try to use it:
/**
* #function ajax Send ajax-request with post
* #param {string} xmlpage Target url
* #param {string} data Post parameters (like param1=val1¶m2=val2...)
* #param {Function} callback
* #return {null}
*/
function ajax(xmlpage, data, callback)
{
var xmlh = null;
if(window.XMLHttpRequest)
xmlh = new XMLHttpRequest();
else
try
{
xmlh = new ActiveXObject("Msxml2.XMLHTTP");
}
catch(ex)
{
xmlh = new ActiveXObject("Microsoft.XMLHTTP");
}
if(xmlh)
{
xmlh.open("post", xmlpage, true);
xmlh.onreadystatechange = function(x)
{
if(xmlh.readyState==4 && typeof callback !== 'undefined')
callback(xmlh.responseText);
}
xmlh.setRequestHeader("Accept-Language","ru, en");
xmlh.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlh.send(data);
}
}
Following test files using your code from the question. It is working perfectly. Either you are missing something or its a browser issue. I tested on Mozilla. To be sure of browser independent code use jQuery for Ajax call
test.html
<html>
<script>
function loadXMLDoc()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("quote").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","RandomQuote.php",true)
xmlhttp.send();
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
RandomQuote.php
<?php
echo 'hi';
Update: jQuery version
<html>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
function loadXMLDoc()
{
$.get( "RandomQuote.php", function( data ) {
$( "#quote" ).html( data );
});
}
</script>
<div id="quote"></div>
<input type="button" value="Click Me" onclick="loadXMLDoc()"/>
</html>
This is my javascript that holds the function to save the file.
function saveMap()
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
map = document.getElementById("sectorTableMap").innerHTML;
data = '<table id="sectorTableMap">';
data += map;
data += '</table>';
document.getElementById("sectorTableMap").innerHTML = data;
//alert("done");
//alert(data);
if(fileName=="lastSave - RENAME") {
return alert("Please set a file name under [CONFIG]");
}
else {
//alert(data);
//alert(user);
//alert(fileName);
xmlhttp.open("POST","http://pardustools.comuf.com/saveMap.php?t="+Math.random(),true);
xmlhttp.send('map='+data+'&user='+user+'&fileName='+fileName);
//alert(data);
//alert(user);
//alert(fileName);
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
//return alert("File has successfully been saved!");
return alert(xmlhttp.responseText);
}
}
}
This is my files that is posted too.
<?php
$user = strtolower($_POST['user']);
$map = $_POST['map'];
$fileName = "savedMaps/".$user."/".$_POST['fileName'].".html";
file_put_contents($fileName,$map);
echo $fileName."<br />".$map;
?>
This is the output I receive on the php file.
savedMaps//.html
It should be more like this
savedMaps/randomName/fileName.html
EDIT:
To set for the user.
user = "<?php $cookie = $_COOKIE['mapperlogauth']; echo strtolower($cookie['user']);?>";
To set for the data...
It is under the saveMap() function and starts with map.
You are using PHP's $_POST get, you're not posting any variables, you should use $_GET in your situation, or change your xmlhttp send to post properly. edit you are also missing the content type header to do a successful post
edit You should also be aware that there is a limit on how much you can send through using the technique you're using. (which is a get, not a post, even though you specify it)
I'd also recommend looking into jQuery for cross-browser compatibility and ease of use.
edit
Here's some code that will allow you to pick it up via POST:
xmlhttp.open("POST","ajax_test.asp",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("fname=Henry&lname=Ford");
Have you tried to use :
xmlhttp.send('map=dummy&user='+user+'&fileName='+fileName);
I doubt it may be caused by the encoding.
I am using below code on my main page ,where other pages are loaded using ajax with the help of TWO RADIO BUTTONS
<script>
function loadXMLDoc(str)
{
var xmlhttp;
if (window.XMLHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}
else
{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function()
{
if (xmlhttp.readyState==4 && xmlhttp.status==200)
{
document.getElementById("myDiv").innerHTML=xmlhttp.responseText;
}
}
if(str=="Candidate")
{
xmlhttp.open("GET","creg.php",true);
}
else if(str=="Employer")
{
xmlhttp.open("GET","Empyr.php",true);
}
xmlhttp.send();
}
</script>
below script is written for FORM VALIDATION (written at end of main page),this script works only when main page loaded first time ,but when forms are getting loaded second time using ajax than this script is not working
<script>
$.validate({
form : '#cand, #employerRegister'
})
;
</script>
As i know script is getting read at the time of page load ,but now Where should I write this script so that it works when I load forms using ajax,where i am going wrong?
Are you using validation engine? I will not prefere doing ajax call with pure javascript it looks messy.
jQuery(document).ready(function($) {
$('#registration').validate({
rules:{
email: {
email: true
},
password : {
minlength : 6
},
repassword : {
minlength : 6,
equalTo : "#password"
}
},
submitHandler: function(form) {
// do other things for a valid form
var post = {};
form_data = $(form).serialize();
//console.log(form_data);
//console.log(book_form);
if(post)
{
$.post(site_url+'/members/register',form_data,
function(response){
var res1 = $.parseJSON(response);
console.log(res1);
if(res1.success == true )
{
$('.success_message').html('You are successfully registered ').show();
window.location.href = site_url+'/pages/registerstep';
clear_form(form);
}
else
{
$('.error_message').html(res1.success).show();
//clear_form(form);
}
}
);
}
}
});
});
Use something like this. This will work. Reason why your code is not working after first load is because your validation is not triggering while form submit
You need to run the code again to bind the event handler, after the new element is inserted into the DOM. It is better to use cross platform javascript framework like jQuery, Prototypejs etc
You need to call the bellow javascript again from ajax response
<script>
$.validate({
form : '#cand, #employerRegister'
})
;
</script>
Check here
Hi i tried to call a rest webservice from ajax get request.
Following is the code i tried for that.
function callRestService(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
$.ajax({
xmlhttp.open("GET","http://mywebservice/test/",false);
xmlhttp.send();
alert(xmlhttp.responseText);
});
}
And following error am getting while running this code/
missing : after property id
[Break On This Error]
xmlhttp.open("GET","http://mywebservice/test..
/AjaxC...ervice/ (line 30, col 13)
In the first case i tried something like following
$.ajax({
type: "GET",
url: "http://mywebservice/test/",
cache: false,
success: function(data){
alert(data);
//var obj = eval(data);
},
error: function (msg, url, line) {
alert('error trapped in error: function(msg, url, line)');
alert('msg = ' + msg + ', url = ' + url + ', line = ' + line);
}
});
and in the above case control comes into the error block, but i didn't get what's the reason for that .and that's why i tried the first case.
Is there any problem with this code..??Can anyone help in this.?
Your code is all wrong.
Assuming that$.ajax is jQuery ajax call, then Your code should look like this:
function CallRestService() {
$.ajax({url:'http://mywebservice/test'}).done(function(data) {
alert(data);
})
);
}
You don't need to create xml http request if you're using jquery ajax call.
See this: http://api.jquery.com/jQuery.ajax
for reference.
If you don't want to use jQuery:
function callRestService(){
var xmlhttp;
if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else{// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET","http://mywebservice/test/",false);
xmlhttp.send();
if (xmlhttp.status == "200") {
alert(xmlhttp.responseText);
}
}
Reference here: Using XMLHttpRequest
If you are using cross domain calls, see here:
jQuery AJAX cross domain