Learning ajax. How to print the variable on json response - javascript

I am trying to learn ajax, because it will be useful for the project I am developing. I am only getting started at it. I've watched some tutorials and now I testing out some code. I am using laravel. Here is my view:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta name="csrf-token" content="{{ csrf_token() }}">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
</head>
<body>
<button type="button" class="btn btn-warning" id="getRequest">get Request</button>
<div id="teste"></div>
<script type="text/javascript">
var id = 12; // A random variable for this example
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$(document).ready(function(){
$('#getRequest').click(function(){
$.ajax({
method: 'POST', // Type of response and matches what we said in the route
url: '/customer/ajaxupdate', // This is the url we gave in the route
data: {'id' : id}, // a JSON object to send back
success: function(response){ // What to do if we succeed
var theDiv = document.getElementById("teste");theDiv.innerHTML += response->'teste';
console.log(response);
},
error: function(jqXHR, textStatus, errorThrown) { // What to do if we fail
console.log(JSON.stringify(jqXHR));
console.log("AJAX error: " + textStatus + ' : ' + errorThrown);
}
});
})
})
</script>
</body>
</html>
Here is my controller:
<?php
namespace App\Http\Controllers;
use Illuminate\Http\Request;
class AjaxController extends Controller
{
public function updateCustomerRecord(Request $request)
{
$datda = $request->all(); // This will get all the equest data.
$teste = "teste";
return response()->json(['success' => true, 'teste' => $teste]);
echo "ole";
}
}
And lastly we have my routes:
Route::post('/customer/ajaxupdate', 'AjaxController#updateCustomerRecord');
Route::get('/teste', function(){
return view('teste');
});
As you can see this is simple code... When I get more used to Ajax I will do a select from database and show data on the view. But now I am trying to pass data from one variable on the controller to the view using json response. I also wish you could give me a tip how I should do a simple db:select and the best way to pass it through to the view.
I am expecting this code to pass data from controller to view.

There's a mistake in your JavaScript code. You are using arrow -> instead of period or dot .
Please replace this
theDiv.innerHTML += response->'teste';
with this
theDiv.innerHTML = response.teste;

Related

How to solve Error 400 on html page post method

I have make a simple html file to get my data and add button to post data but however i am returning error 400
My get method are running fine with displaying the backend data out in the html but however post method i am returning some errors 400 due to my query which i not sure why is there any way i can prevent this error 400 ?
<!DOCTYPE html>
<html>
<head>
<title>Add recycables</title>
<!-- Stylesheet -->
<link rel="stylesheet" href="/">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.0/jquery.min.js" integrity="sha256-xNzN2a4ltkB44Mc/Jz3pT4iU1cmeR0FkXs4pru/JxaQ=" crossorigin="anonymous"></script>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<body>
<div id = "add"></div>
<P>Add recycables</P>
<p>name: <input type="text" id="name"></p>
<p>type:<input type="text" id="type"> </p>
<button id="add">Add</button>
</body>
<script>
$(document).ready(function(){
var $items = $('#add');
var $name = $('#name');
var $type = $('#type');
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/get",
method:"GET",
// In this case, we are going to use headers as
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:"RecyclableGet(0)",
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, item, xhr,textStatus) {
//console.log(data)
$.each(data, function(i, item){
$items.append('<li>name: '+item.Name +', type: '+ item.RecyclableType + '</li>');
});
},
error:function(xhr,textStatus,err) {
console.log(err);
}
});
$('#add').on('click', function(){
var addRecyclables = {
Name: $name.val,
RecyclableType: $type.val
}
})
$.ajax({
url:"https://ecoexchange.dscloud.me:8080/api/post",
method:"POST",
headers:{
// The query you're planning to call
// i.e. <query> can be UserGet(0), RecyclableGet(0), etc.
query:`RecyclableAdd('${name}','${type}')`,
// Gets the apikey from the sessionStorage
apikey:sessionStorage.getItem("apikey")
},
success:function(data, Newitem, xhr,textStatus){
$items.append('<li>name: '+Newitem.Name +', type: '+ Newitem.RecyclableType + '</li>');
},
error:function(xhr,textStatus,err) {
console.log(err);
}
})
})
</script>
</html>
Json file look like
my html on web

Getting Undefined when reading back a POST from AJAX

If this is a re-post of an already existing. I looked a bunch of different issue already posted about this but didn't feel any matched my issue. If there is one please link it.
I'm trying to learn AJAX and have a form that takes two inputs a serverName, and a isLive. As well as a button to add a server to the list. I already made a json file that has two servers in it and when I GET info from it to update the list it lists the server's serverName and isLive fine. When I go to POST information all I get back when the list is updated is undefined.
Using console logs I know that the information is being passed from the form to Object to be sent by AJAX and that it seems to trigger the success function, but when I look there is nothing added to the Json and it says the fields are undefined.
index.php
<!DOCTYPE html>
<html>
<head>
<title>Ajax</title>
</head>
<body>
<h1>Server List</h1>
<ul id="servers">
</ul>
<h4>Add a Server</h4>
<p>Server Name: <input type="text" id="serverName"></p>
<p>Offline or Online: <input type="text" id="isLive"></p>
<button id="add-server">Add!</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="main.js"></script>
</body>
</html>
main.js
$(function() {
var $servers = $('#servers');
var $serverName = $('#serverName');
var $isLive = $('#isLive');
$.ajax({
type : 'GET',
url: 'servers.json',
success: function(servers) {
$.each(servers, function(i, server) {
$servers.append('<li>Server: '+ server.serverName +', Status: '+server.isLive+'<li>');
});
},
error: function() {
alert('Error loading server status!');
}
});
$('#add-server').on('click', function() {
var server = {
serverName: $serverName.val(),
isLive: $isLive.val(),
};
console.log(server);
$.ajax({
type: 'POST',
url: 'servers.json',
data: server,
success: function(newServer) {
$servers.append('<li>Server: '+ newServer.serverName +', Status: '+newServer.isLive+'<li>');
},
error: function(){
alert('error saving server');
}
});
});
});
servers.json
[{"serverName":"vanilla","isLive":"offline"}, {"serverName":"SkyFactory","isLive":"Online"}]
You can't modify a file in the server with JavaScript. Check this may help:
Use JQuery to Modify external JS File

load json data into js

I am learning how to load json data into .js file. I have created a employee.json file. I saved my js and json file and on the desktop. What I trying to do is to put all the id in json files into an array in the js. I do not know what could be wrong. Hope someone could help me out. Thank you in advance.
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>JSON with jQuery</title>
</head>
<body>
<p id="demo"></p>
<h1><h2>
<script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
type: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
}
});
document.getElementById("demo").innerHTML = res.toString();
</script>
</body>
</html>
{
"person": [
{
"id" : 1,
"firstName" : "Lokesh"
},
{
"id" : 2,
"firstName" : "bryant"
}
{
"id" : 3,
"firstName" : "kobe"
}
]
}
Error 1: Typing error. <script src = "<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>. You mistyped the src of the script, accidentally adding another another <script> start tag.
Error 2: Misplaced statement. document.getElementById("demo").innerHTML = res.toString(); should be placed in the success callback function, so it will be executed only after the server responds. If it executes prematurely, res will still be [].
Error 3: type: 'GET' should be method: 'GET', according to the docs (though 'GET' is default so you don't need to explicitly write this).
Use this:
<p id="demo"></p>
<h1><h2>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script>
var res = [];
$.ajax({
url: 'employee.json',
dataType: 'json',
method: 'get',
cache: false,
success: function(data) {
$(data.people).each(function(index, value) {
res.push(value.id);
});
document.getElementById("demo").innerHTML = res.toString();
}
});
</script>
You can't use the local json to read. it gives cross origin request failure. so deploy both the files (html and json) into a we server and execute. or place the json data onto some web url(http://somesite/myjson) and then request that url and see.
First of all, the JSON shouldn't be existed as in physical "file". It has to be generated by a backend language / web service etc. The JSON tags inside a manually created "file" have high chance of data invalidity upon parsing.
Solution
Use a Web Service to generate valid JSON output. And from Javascript end, use:
JSON.stringify( data );

passing data from js file to php using jquery ajax

ajaxcheck.js
var val = "hai";
$.ajax(
{
type: 'POST',
url: 'ajaxphp.php',
data: { "abc" : val },
success :function(data)
{
alert('success');
}
}
)
.done(function(data) {
alert("success :"+data.slice(0, 100));
}
)
.fail(function() {
alert("error");
}
);
ajax.html
<!DOCTYPE html >
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="ajaxcheck.js"></script>
<title>ajax request testing</title>
</head>
<body>
</body>
</html>
ajaxphp.php
<?php
$v_var = $_POST["abc"];
print_r($_POST);
if(isset($_POST["abc"]))
{
echo $v_var;
}
else
{
echo "Data not received";
}
?>
When I run the ajax.html file ,I get success alert. But when I run ajaxphp.php file it shows notice like:
undefined index abc
Why is that the data is not received in $v_var ? where i am mistaking ?please help.
Actually the ajaxphp.php file is used to receive the data from the
post method and i will give response .
In First case by using ajax post method it will call to ajaxphp.php file.
In Second case your using direct file call without any post data(that's way it shows error)
Try this
var val = "hai"
$.post( "ajaxphp.php", {'abc':val}function( data ) {
alert( "Data Loaded: " + data );
});
jQuery expects an object as data, remove the double-quotes:
data: { abc : val }

Phonegap/Android error: Uncaught ReferenceError: url is not defined at file:///android_asset/www/js/login.js:17

I created a phonegap app for Android and i put the login "logic" into a javascript file. Somethimes the login function works, sometimes it doesn't. When it doesn't, i get the following error:
10-24 10:01:13.211: Web Console(25080): Uncaught ReferenceError: url
is not defined at file:///android_asset/www/js/login.js:17
Everything is there and when i used cordova2.0.0 it was working fine, but i had to switch to cordova 2.1.0. Since the switch it doesn't always work fine.
Here's how i include the resources in the html file:
<html>
<head>
<title>Hello World</title>
<script type="text/javascript" charset="utf-8" src="js/cordova-2.1.0.js"></script>
<link rel="stylesheet" href="css/jquery.mobile-1.1.1.min.css" />
<script type="text/javascript" src="js/jquery-1.8.1.min.js"></script>
<script type="text/javascript" src="js/jquery.mobile-1.1.1.min.js"></script>
<script type="text/javascript" charset="utf-8" src="js/login.js"></script>
</head>
...
here's my login.js
$('#page_login_submit').live('click',function(){
var name = $('#page_login_name').val();
if (!name) { alert('Please enter your user name.'); return false; }
var pass = $('#page_login_pass').val();
if (!pass) { alert('Please enter your password.'); return false; }
$.ajax({
url: "http://scoreboard.pronovix.net/?q=scoreboard/user/login.json",
type: "POST",
data: 'username=' + encodeURIComponent(name) + '&password=' + encodeURIComponent(pass),
dataType: "json",
error: function(jqXHR, textStatus, errorThrown) {
alert('Login fail: ' + url + '+' + data); //that's line 17
console.log(JSON.stringify(jqXHR));
console.log(JSON.stringify(textStatus));
console.log(JSON.stringify(errorThrown));
},
success: function (data) {
window.location.href = 'index.html';
}
});
return false;
});
Can anyone tell the reason why?
Any help is very much appreciated!
Sincerely,
Zoli
You are trying to reference the url variable to print out in your error but you have not defined it anywhere.
Remember the error function does not have access to the parameters of the ajax function.
Possible solution
If you implement the beforeSend function you can save the url then use it later
beforeSend: function (jqXHR, settings) {
url = settings.url + "?" + settings.data;
}
This solution was taken from Access the URL of an jQuery Ajax Request in the Callback Function

Categories