Laravel 4 javascript ajax request - javascript

I performed and Ajax request when a button is being clicked, to make a get request and update a div,but my page doesn't seem to update at all.but using the debugging tools i realised that:
it gives error: Cannot set property 'innerHTML' of null
But when i save my xmlhttp.responseText to a variable and i alert it alert this:
<div>
This is a new Ajax Message !! Thanks
</div>
which is the content of msg.blage.php that am requesting for.Though am new to using ajax and laravel.
Below here is the code:
register.blade.php
<button id="btn" onclick="makerequest('{{route('msg')}}','succesMessage')">Update!!</button>
<div id="successMessage"></div>
msg.blade.php
<div>
This is a new Ajax Message !! Thanks
</div>
script.js
function makerequest(serverPage, objID) {
var obj = document.getElementById(objID);
xmlhttp.open("GET", serverPage);
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var data = xmlhttp.responseText;
alert(data);
obj.innerHTML=data;
}
}
xmlhttp.send(null);
}
routes.js
Route::get('/msg',['as' => 'msg', 'uses' => 'HomeController#msg']);
HomeContoller.php
public function msg()
{
return View::make('msg');
}
The error shows on line "sortable.js:14";
and that i think is the second each()

<button id="btn" onclick="makerequest('{{route('msg')}}','succesMessage')">Update!!</button>
<div id="successMessage"></div>
You have a typo in the first line, succesMessage instead of successMessage. It's trying and failing to find an element with the ID succesMessage as a result.

Related

Maintaining authentication using API and xhr

I'm getting to grips with using an API to display the data on a page refresh. SO the first part is to authenticate using form based authentication. So I have this:
<html>
<head>
<script type="text/javascript">
function CallWebAPI()
{
var request = new XMLHttpRequest(), data = 'username=admin&password=admin';
request.open('POST', 'https://localIP:8443/api/users/_login', true)
request.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")
request.setRequestHeader("Accept", "application/xml")
request.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(request.responseText);
//}
}
request.send(data);
}
</script>
</head>
<body>
<div>
<div id="response">
</div>
<input type="button" class="btn btn-primary" value="Call Web API" onclick="javascript:CallWebAPI();" />
</body>
</html>
So from the above, in the console browser I return a proper authentication message as thus:
SUCCESS
So I want to run another function to retrieve data now I'm logged in but it seems to reset back to 'unauthorised. All I did was create another function exactly the same except it was a GET rather than POST and added another button to test it. But it just kept returning 401: unauthorised. Am I doing it in the incorrect order or something?
I insert a second function like this:
function getChannelStats()
{
var stats = new XMLHttpRequest();
stats.open('GET', 'https://localIP:8443/api/channels/statistics?channelId=f237ae66-6c5b-4ffa-9396-0721eb575184', true)
stats.setRequestHeader("Accept", "application/xml")
stats.onreadystatechange = function()
{
// D some business logics here if you receive return
//if(request.readyState === 4 && request.status === 200) {
console.log(stats.responseText);
//}
}
stats.send();
}
request.send(data);
}
And add another button that class that function to get the responseText. I'm expecting an xml message with various numbers in it. But when I try to run it, it asks for me to authenticate - like it's not retaining it?

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();"

How to trigger a variable/method in python from a html file with javascript

I want to have a hyperlink on a html page run a variable that is defined in my python file. The variable is going to clear my database. Here is the code I am trying to use.
Python
#app.route('/log')
def log():
cleardb = db.session.delete()
return render_template('log.html', cleardb=cleardb)
Html
<a onclick="myFunction()">Clear database</a>
Javascript
<script>
function myFunction()
</script>
I don't know what javascript I need to run the variable. I want to make the cleardb get triggered so that it will delete the database.
Thanks
You need to make an ajax request with javascript to /log, it would look something like this:
function myFunction() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
if (xmlhttp.status == 200) {
//Do Success functionality here
}
else if (xmlhttp.status == 400) {
//Handle 400 errors here
}
else {
//All other errors go here
}
}
};
xmlhttp.open("GET", "/log", true);
xmlhttp.send();
}

Retrieve a variable from server using alert

this is my first attempt to retrieve a value using an alert box. Here what I am doing is having a file at the server and I want to retrieve that file value in an alert box.
Before that, I am able to get that value through a link. That working code is here-
<!DOCTYPE html>
<html>
<script>
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
}
};
xhttp.open("GET", "localhost:8080/TemperatureReading/", true);
xhttp.send();
</script>
<body>
test
</body>
Request data
</html>
Now, what am I trying to do is have that value in an alert box every time I hit that button.
That code is here---
First I added a return statement in the function so that a variable is returned inside it.
xhttp.send();
return variable;
Than, I added another function for alert box---
<script>
function myFunction() {
alert(variable);
});
</script>
and in the body, I added
<button onclick="myFunction()">Try</button>
But till now I am not succeeded in that.
I am not understanding what am doing wrong here.
Can anyone help me with this thing. Thank you in advance.
EDIT : I have edited the code. Also, I have to only create a HTML file. I am not generating the number. So, what I have to do is just give an HTML and with the help of retrieve value
Do this when you get the response:
if (xhttp.readyState == 4 && xhttp.status == 200) {
document.getElementById("demo").innerHTML = xhttp.responseText;
if(window.localStorage){
window.localStorage.setItem['resp'] = JSON.stringify(xhttp.responseText);//set it here
}
}
now in the function where variable is required:
function myFunction() {
if(window.localStorage){
var resp = JSON.parse(window.localStorage.getItem['resp']); // get it here
alert(resp); // alert it here.
}
}

Collapsing a div element that contains a form using javascript

I have a user sign up form that i am trying to collapse once the user has successfully signed up (and replaced with something like 'please check your email to activate account') . I am having problems collapsing the form (and all the elements inside it) after receiving the correct response from an ajax request. I just cannot figure out where my code is incorrect. Please can someone advise?
Ajax request:
// Create XMLHttprequest
var xmlhttp = new XMLHttpRequest;
xmlhttp.onreadystatechange = function(){
if(xmlhttp.readyState == 4 && xmlhttp.status == 200){
//Need to get a response after processing the submitted data.
if(xmlhttp.responseText == 'Sign up success'){
window.scrollTo(0,0);
document.getElementById('signup_main').style.display='none';
}else{
document.getElementById("status").innerHTML = xmlhttp.responseText;
}
}
}
function adduser()
{
$("#inp").hide(0);
$("#main").html("User added successfully");
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="main">
<div id="inp">
<p> A Div with content or form</p>
<input type="button" value='add' onclick='adduser();'>
</div>
</div>

Categories

Resources