calling jquery AJAX dynamically - javascript

The following code is not working for me and I don't know why...
this is my js code:
var getEventsFunctionScript = document.createElement('script');
getEventsFunctionScript.setAttribute('type', 'text/javascript');
getEventsFunctionScript.innerHTML = "function getEvents(){$.ajax({url:'myPHP_file.php',type:'post',data:{'ajaxData':'1'},success:function(response){alert('AJAX executed!!');}});}";
w.document.body.appendChild(getEventsFunctionScript);
this us my php code:
if (isset($_POST['ajaxData'])) {
exit;
}
My problem is that this is not working, Ajax is never executed (I never see the alert)
could someone give any idea about why this is not working?
thank you very much

You need to call your function afterwards:
getEventsFunctionScript.innerHTML = "function getEvents() {
$.ajax({
url: 'myPHP_file.php',
type: 'post',
data: {
'ajaxData': '1'
},
success: function (response) {
alert('AJAX executed!!');
}
});
}
getEvents();";

Related

unable to set result from ajax success to div html in mvc

I have the below code, I'm calling an action and getting a partialviewresult in ajax success.
But I'm unable to set the html to the div-Graph, but I'm getting undefined in alert; alert( $('#div-Graph').html()); The entire html is disappearing...
Any idea on this?
$(document).ready(function () {
$('#ChartTypes').change(function () {
var selectedID = $(this).val();
$.ajax({
url: '/charts/GetChart/4',
type: 'GET',
success: function (result) {
debugger ;
$('#div-Graph').html(result.toString());
alert( $('#div-Graph').html());
}
});
});
});
Kindly let me know if you need any more code parts. Tried a lot for a solution :(
Thanks
Ragesh
You can directly append it to the class/id like this. You can't display the whole div inside the alert box.
success: function (result) {
alert(result);
var res = JSON.stringify(result);
$('#div-Graph').append(res);
}

Ajax post request doesn't work (simple)

I am struggling to make a simple ajax request. I have no idea why it doesn't work.
<script>
function checkdata() {
var reqdata = "aha";
alert(reqdata);
$.ajax({
type: "POST",
url: "https://example.com/cs/test.php",
data: reqdata,
cache: false,
success: function(returnedata) {
alert(returnedata);
}
}); //end of ajax
return true;
}
</script>
<input type="button" value="CheckData" onclick="checkdata();">
The file https://example.com/cs/test.php has one: echo "done"; which works properly. When I navigate to the page with the browser I see just "Done"
What is the problem here? Thanks.
Don't forget to include https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js
your code will not work without this
here is something that worked ,, change your function declaration to match this
checkdata = function () {
var reqdata = "aha";
....

Return and print value passed through php script from javascript object using jquery ajax

i have the following code:
Javascript object:
var getDBresults = (function () {
function getResult(url,TableName ,callback){
$.ajax({
url: url,
type: 'POST',
data: {
'table':TableName,
},
dataType: 'json',
success: function(data){
callback(data);
console.log(data)
},
error: function(){}
});
}
return {
getAllVideoes: function(){
getResult("getAllResults.php", "videoer", function(data){
return data;
});
}
}
})();
simple php script:
<?php
$tableName = $_REQUEST['table'];
echo $tableName;
?>
My js command for fetching(seperate script ofc):
var obj = getDBresults;
var data = obj.getAllVideoes();
console.log(data)
My issue is with the callback function. It wont output anything and it doesn't seem to be running at all.. Had this issue for quite som time now and i just cant figure it out.. Is there anything i'v been missing? All help is apriciated! Sorry for my spelling btw.
you ajax is expecting
`dataType: 'json',`
json output from your php script
you are returning html/plaintext data
`echo $tableName;`
try json_encode
echo json_encode(array($tableName));
result is not in JSON format, so when jQuery fails to parse it,
You can catch the error with ajax's error: callback function

Adding javascripts functions dynamically in mvc3

I'm creating a dynamic-form infrastructure. This infrastructure will get a certain XML which will include all of the form data, from the order in the page to validators.
The dynamic page may also contain fields which will require some sort of validation. The validation is not only trivial (such as "numeric"\"alphanumeric"), it might be something more complicated.
That's why I want to pass in my XML the validators javascripts.
When developing on traditional Web Application, it's simple to plant this code in the page header. But I don't know how to do so when using MVC3, since it's not a normal client-server application.
It's important to explain - in my controller, I pass this dynamic-form class the xml file, it does all it should, and in the end, I plant the result in ViewBag.table.
Anyone know how can I can plant the javascript code from the controller to view header?
EDIT:
I tried thw following:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function (result) {
var myscript = document.createElement('script');
myscript.setAttribute('type', 'text/javascript');
myscript.innerHTML = '$( document ).ready( function ( e ){' + result + '});';
document.getElementsByTagName('head').item(0).appendChild(myscript);
}
});
and also:
$(document).ready(function () {
$.ajax({
url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function (result) {
var myscript = document.createElement('script');
myscript.setAttribute('type', 'text/javascript');
myscript.innerHTML = "function test() {alert('aa');}";
document.getElementsByTagName('head').item(0).appendChild(myscript);
}
});
or change the:
myscript.innerHTML = "function test() {alert('aa');}";
to:
myscript.innerHTML += "function test() {alert('aa');}";
so it will be added to the existing "$documnet.ready" function.
None of it worked.
I kept getting "Unknown error"
Thank you all.
Hope it helps..
$(document).ready(function () {
$.ajax(
{ url: '#Url.Action("SetJScript", "MyPages")',
type: 'POST',
success: function(result)
{ var myscript = document.createElement('script');
myscript.setAttribute('type','text/javascript');
myscript.innerHTML = 'function test() {alert("aa");}';
document.getElementsByTagName('head').item(0).appendChild(myscript);
} //end of success
});
});

Calling a function from if block in success

Hello fellow programmers. I am newbie to jquery ajax.
How do i call function checkreturn() from if block or is it possible to access msg outside the success if yes then please let me know how. I need it because only if condition proves true i have to enable the subsequent textbox. Here is my code.Thanks in advance for your time and reply.Rajesh.
<script type="text/javascript" >
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e){
var uname= $("#<%=Username.ClientID%>").val();
var sq=$("#<%=SecQuest.ClientID%>");
var sqtn = $("#<%=SecQuest.ClientID%> option:selected").text();
var sans=$("#txtAns");
var msgbox = $("#Dstatus");
$.ajax({
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
}
else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
});
}
</script>
You have a typo in your checkreturn function. You want to use removeAttribute, instead of removeAtrribute (double t,not double r).
Also, you can use jQuery functions:
function checkreturn(){
$('#txtAns').prop('disabled',false);
}
, instead of native DOM functions (document.getElementById, setAttribute):
not sure what why the normal way is not working but you could try forcing what the browser is supposed to do,
function checkreturn(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Becomes
window.checkreturn = function(){
document.getElementById("txtAns").removeAtrribute("disabled");
}
Then try calling via window.checkreturn(); or checkreturn(); you can also so try this the other way arround so you can leave your function and try calling window.checkreturn();
If none of these are working it would say your function is not entering the window(Global) scope for your page use Firebug or Inspector and try to all checkreturn(); see what exception you get back,
if you get a not found your not showing us some thing in your code maybe a closure or some thing
I'll look into it further but try setting async for the ajax call to false:
function checkreturn() {
document.getElementById("txtAns").removeAtrribute("disabled");
}
function cQtn(e) {
var uname= $("#<%=Username.ClientID%>").val(),
sq=$("#<%=SecQuest.ClientID%>"),
sqtn = $("#<%=SecQuest.ClientID%> option:selected").text(),
sans=$("#txtAns"),
msgbox = $("#Dstatus");
$.ajax( {
async: false,
type: "POST",
url: "forgotpassword.aspx/CheckValidSQtn",
data: "{'uname':'"+uname+"','args':'"+sqtn+"'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(msg) {
if (msg.d == 'Available') {
sq.removeClass("notavailablecss");
sq.addClass("availablecss");
msgbox.html('<img src="proj_mages/a.png"> <font color="Green"> Valid </font>');
//how do i call from here??
} else {
sq.removeClass("availablecss");
sq.addClass("notavailablecss");
msgbox.html(msg.d);
}
}
} );
}
Now, when the ajax call is made, the rest of the script will wait til it completes instead of how everything continues when async is true.

Categories