How to execute a javascript function that is in ajax call - javascript

There should be a simple solution this this issue but I am not being able to figure it out!!
So I am getting data/templates via ajax. And there are some function in the ajax data. When I try to call the function it throws and error. Example in jsfiddle with regular vs ajax function calls. http://jsfiddle.net/rexonms/b05uxko6/
<!-- HTML -->
<div id="regularData">
<h2>Regular Data</h2>
<p onclick="mouseEvent()">Click Me</p>
<script>
function mouseEvent(){
alert('Yep clicked');
}
</script>
</div>
<hr>
<div id="ajaxData"></div>
<!-- Javascript -->
var request = new XMLHttpRequest(); // do we need this?
request.open("POST", "https://kvdevl06.sohalo.com/apps/kobie/php/widget/dispatcher_tpl.php");
request.onreadystatechange = function(){
if(request.readyState === 4){
alert('Ajax data is: ' + request.response);
document.getElementById("ajaxData").innerHTML = request.response;
}
}
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
request.send("action=getTest&partner_user_id=1&template_id:test");

You may check the following question:
Executing <script> elements inserted with .innerHTML
In short, you may iterate the script tags and eval them.

Related

Pressing the ajax button again after the first time gives a strange error

Basically when I press the button the first time ajax loads perfectly but when I press that same ajax button again it gives me this error
(index):17 Uncaught DOMException: Failed to execute 'send' on 'XMLHttpRequest': The object's state must be OPENED.
at sendAJAX (http://etc.../:17:5)
at HTMLButtonElement.onclick (http://etc.../:29:40)
I have found articles about this but they are confusing to a point where I don't know how to integrate those solutions to my script, to get it to work with my script so I need a code example solution based on my exact script not based on some one else's script so I can
better understand this based on my script. I mainly want to know how can I keep calling the same ajax request regardless how many times I press that same button with out errors.
Code example
index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link href='//fonts.googleapis.com/css?family=Varela+Round' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="css/main.css">
<title>AJAX with JavaScript</title>
<script>
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'sidebar.html');
function sendAJAX() {
xhr.send();
}
</script>
</head>
<body>
<div class="grid-container centered">
<div class="grid-100">
<div class="contained">
<div class="grid-100">
<div class="heading">
<h1>Bring on the AJAX</h1>
<button id="load" onclick="sendAJAX()">Bring it!</button>
</div>
<ul id="ajax">
</ul>
</div>
</div>
</div>
</div>
</body>
</html>
sidebar.html
<section>
<h2>Welcome to the wonderful world of AJAX</h2>
<p>This content provided to you dynamically by the XMLHTTP Request Object</p>
</section>
You create your xhr element only once, so if sendAJAX is called a second time, then send is called on an XMLHttpRequest that was already send.
After send is called the state of the xhr obeject is not opened anymore and because of that you get the error message.
You can solve the problem by creating new XMLHttpRequest for each sendAJAX call.
function sendAJAX() {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
xhr.open('GET', 'sidebar.html');
xhr.send();
}
Or by only moving open into the sendAJAX:
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
document.getElementById('ajax').innerHTML = xhr.responseText;
}
};
function sendAJAX() {
xhr.open('GET', 'sidebar.html');
xhr.send();
}
XMLHttpRequest.open()
Note: Calling open for an already active request (one for which open() has already been called) is the equivalent of calling abort().

XHTTP request from REST API

I have this API
[HttpGet("data")]
public dynamic GetData(){
return context.DataTable.ToList();
}
I tried calling it on my Javascript using this snippet;
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true);
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
var resp = xhttp.responseText;
}
However, it only returns empty XMLHttpRequest.
I think what's wrong there is the URL. How I may able to call the API to my Javascript?
Since u have not cheked the response of ur answer, i susspect there is something wrong in ur backend. But, here is a sample of functional solution:
<!DOCTYPE html>
<html>
<body>
<h2>Using the XMLHttpRequest Object</h2>
<div id="demo">
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</div>
<script>
function loadXMLDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
console.log("Status is: "+this.status);
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "xmlhttp_info.txt", true);
xhttp.send();
}
</script>
</body>
</html>
You van find more info here. But in the line
xhttp.open("GET", "api/myclass/data", true);
The second parameter is the address of a file in ur server. r u sure u have wrotten the correct format? what is the extension of ur data file.
I guess, both backend and front end should be reconsidered. To do it:
Try to send a reuqest using postman to backend
in frontend check the status of response using my answer
To make sure make it async = false with
xhttp.open("GET", "api/myclass/data", false);
Therefore, there wouldn't be a delay as #Alex Kudryashev pointed
Solution:
You need to first find the result of line
console.log("Status is: "+this.status);
in ur browser's console.
If u get the responseText as empty it may come because u have sent an empty string from backend,(we are not sure because u have not tested ur backend with postman) but it is crucial to know the status of response.
The request may take time to receive the response so you have to wait. Something like this.
function getData(){
var xhttp = XMLHttpRequest();
xhttp.open("GET", "api/myclass/data", true); //the request is asynchronous
xhttp.onreadystatechange = function(){
if(this.readyState == 4 && this.state == 200){ //**this** is xhttp
//data are received and ready to use
var resp = this.responseText;
//do whatever you want with resp but never try to **return** it from the function
}
}
xhttp.setRequestHeader("Content-type","application/json");
xhttp.send();
//var resp = xhttp.responseText; //too early ;(
}

Post form data to php without page refresh

I am trying to post form data, an array to php file without page refresh. I am using ajax which doesn't seem to be working. Below is form syntax and ajax. Can somebody please help me? Thanks.
<form name="postcontent" id="postcontent">
function[]; //just for an example of data
<button type="button" id="submitform" onclick="posttophp" >Send</button>
<script>
function posttophp() {
var xhttp = new XMLHttpRequest();
xhttp1.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("submitform").innerHTML = this.responseText;
}
};
xhttp.open("POST", "options.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("
function_Options1[]=function[]")
}
</script>
In php, I store function_Options1[] in another variable and use further.
Two ideas to try:
Maybe the script should be placed before calling the function, but not sure about this.
Try onclick="posttophp();"

Do script from another file

im today stared learning some ajax technology and im done that when im pressing the button im getting text from another file with functions but they dont working.
My main file
<html>
<head>
<script>
function showHint(str) {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET", "request/testa.php?q=" + str, true);
xmlhttp.send();
}
</script>
</head>
<body>
<button id="inp" style="background-color: #0000FF; color: #ffffff" onclick="showHint(this.value)">
Just do it!
</button>
<p><span id="txtHint"></span></p>
</html>
and in file which send me text (request/testa.php) is
test 2
<script>
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
</script>
and tekst working fine, i got text "test 2" and script but that not works.
Writing javascript code into your page using innerHTML will not execute the script.
The easiest way around this is to use jQuery's load, which will execute the scripts for you.
You have to change something in testa.php. Put everything in a function or just remove the script tag.
function MyScript(){
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
}
or
document.getElementById("inp").value="You did it!";
document.getElementById("inp").style.backgroundColor="ffffff";
After that you can replace the innerHTML in your showHint function for the eval function.
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
for
eval(xmlhttp.responseText);
but have in mind that the eval function opens the door for bugs or hacks.

Alternative to call php in java script?

I want to call php in a java script
I have read that this is forbidden:
document.getElementById('id1').innerHTML="<?php include my.php?>";
if I can't do this How can I load a php page content to a div with id1 when clicking an li:
<ul>
<li onclick="javascriptFunction()">
<li>
<li>
</ul>
<div id="id1"></div>
There are two ways of achieving the goal.
It isn't so much that what you are trying to do is forbidden as much as it is simply impossible.
Option 1
Use an ajax call to your PHP code. In the callback of the ajax call, fill in the innerHTML.
Option 2
Use a template.
<script type="text/html" id="template-id1">
<?php include my.php?>
</script>
<li onclick="setDiv()">
<script>
function setDiv() {
document.getElementById('id1').innerHTML =
document.getElementById("template-id1").innerHTML;
}
</script>
You could use AJAX (http://en.wikipedia.org/wiki/Ajax).
With a usage of library like jQuery (http://api.jquery.com/jquery.ajax/) you will have code like this:
$.ajax('my.php')
.done(function(response) {
$('#id1').html(response);
})
Of course it's doable without any libraries like jQuery, but just requires a bit more code.
I don't know why that'd be forbidden. It's called bootstrapping.
But if you must:
my.php
echo 'whatever';
And then in a <script> tag, use $.ajax to call my.php and fill the appropriate element with the response.
ready function:
function javascriptFunction () {
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
document.getElementById("id1").innerHTML = xhr.responseText;
}
}
xhr.open('GET', 'my.php', true);
xhr.send();
}
You need to use ajax, if you don't want to use library try this:
var request = (window.XMLHttpRequest) ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
request.onreadystatechange=function() {
if (request.readyState == 4 && request.status == 200) {
document.getElementById("id1").innerHTML=request.responseText;
}
};
request.open("GET","my.php",true);
request.send();
Or you could hide the div, then when you click on the link then make it visible.
<div id='id1' style='display:none;'>
your content
</div>
function javascriptFunction() {
document.getElementById('id1').style.display = 'block';
}

Categories

Resources