How to make this work? - javascript

I´m trying to learn ajax, sitting here sinse 3 hours and trying to understand what I need to make it run.
I´m using it on Scriptly with Xampp.
This is my code:
<head>
<title>Titel</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Ajax Example!</title>
<script src="js\jquery/jquery.js"></script>
<script>
$(document).ready(function(){
$("#btnSubmit").click(function(){
//alert("hello");
$.ajax({
type: "POST",
url: "http://localhost/inde.php",
data: {
myName: "durgesh technoclass"
},
success: function(output){
alert(output);
}
});
});
});
</script>
</head>
<body>
<form>
<button id="btnSubmit">Click me !</button>
</form>
I even watched a tutorial on Youtube and copied all the code from there.
The rating of the tutorial is good, the code seems to work for him, but why doesn´t it work for me ?! I don´t understand that.
The Jquery works, but ajax doesn´t. The Script just reloads the page and displays nothing.
Please help.
Edit:
May it be that it doesn´t work, because xampp doesn´t run an actual server ?
On request, here´s the code of the "inde.php":
<?php
echo "Welcome from Server";
?>
Edit 2:
Solution:
I messed up the path of the inde.php.
Just fixed it.
It works but there´s a mistake in the code. It had been fixed by Tanvir Ahmad Sohan. You can find his fix in his answer down there.

Try this...
<script>
$(document).ready(function(){
$("#btnSubmit").click(function(event){
event.preventDefault();
//alert("hello");
$.ajax({
type: "POST",
url: "http://localhost/inde.php",
data: {
myName: "durgesh technoclass"
},
success: function(output){
alert(output);
}
});
});
});
</script>
As your button is inside a form, when you click the button, form is being submitted to the same page, so it just reloads. To prevent this from happening use preventDefault() to prevent the default behaviour.

Related

Jquery TypeError when replacing page content

I'm trying to achieve the following:
A simple Java Spring application, after receiving a GET request, sends me an HTML page with a form. When the button is pressed in this form, there is a POST request with an XML content sent back to the Spring app, which, in turn, responds with an HTML page. I would like to be able to display this response as a proper page in a browser, including all the scripts being downloaded and fully functional.
The form HTML page:
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<meta charset="UTF-8" />
<title>Request Report Form</title>
</head>
<body>
<form method="post" action="">
<script>
function sendXml()
{
event.preventDefault();
const request = '<?xml version="1.0" encoding="UTF-8"?>\n' +
<!-- skip -->
$.ajax({
type: 'POST',
url: url,
dataType: 'html',
data: request,
contentType: 'application/xml;'
}).done(function (data) {
$("html").html(data);
}).fail(function (data) {
$("html").html(data.responseText);
});
}
</script>
</form>
</body>
</html>
The $("html").html(data); part above is supposed to replace the current page's content with the content received from the server, as far as I understand. But the page is not being displayed. There is an error message in the browser's console: "TypeError: n.head is null", it seems to have to do with JQuery, see the image link.
My questions are, why does JQuery kicks in and what is it trying to do? And how do I fix this error?
I don't know much about frontend side of development, so please go easy on me ;-)
Edit
Just realised that my first question is moot, I am trying to display the response page using JQuery, so obviously, it kicks in at that point. But the call fails for some reason.
The content of the response from the server that I'd like to see rendered by the browser:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Progress Report</title>
<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">
<script src="https://code.highcharts.com/highcharts.js"></script>
</head>
<body data-user="eyJjaGFydCI6eyJyZW5kZXJUbyI6IlByb2dyZXNzIiwidHlwZSI6ImNvbHVtbiJ9LCJzZXJpZXMiOlt7Im5hbWUiOiJQcm9ncmVzcyIsImRhdGEiOlsxLDEsMCwwLDAsMCwwLDAsMCwwXX1dLCJ0aXRsZSI6eyJ0ZXh0IjoiUHJvZ3Jlc3MifSwieEF4aXMiOlt7InR5cGUiOiJsaW5lYXIiLCJjYXRlZ29yaWVzIjpbIlJlZ2lzdGVyZWQ8YnI+KDQuNi4xMykiLCJTZXNzaW9uIDE8YnI+KDEyLjcuMTUpIiwiU2Vzc2lvbiAyIiwiU2Vzc2lvbiAzIiwiU2Vzc2lvbiA0IiwiU2Vzc2lvbiA1IiwiU2Vzc2lvbiA2IiwiU2Vzc2lvbiA3IiwiU2Vzc2lvbiA4IiwiRmluaXNoZWQiXX1dLCJ5QXhpcyI6W3sidGl0bGUiOnsidGV4dCI6IlNlc3Npb24gU3RhcnRlZCJ9LCJtaW4iOjB9XX0=">
<div id="wrap">
<div class="container">
<div class="report"></div>
</div>
</div>
<script>
window.onload = function (event) {
event.preventDefault();
$(".report").append("<div class='chart'><div id='Progress'><img src='staticMedia/img/loader.gif' /></div></div>");
userData = $("body").data("user"); // get user report data
var chart = new Highcharts.Chart(JSON.parse(atob(userData)));
// destroys legend if only 1 series
if (chart.series.length < 2) {
chart.legend.destroy();
}
}
</script>
</body>
</html>
Found an answer here: stackoverflow.com/a/11984907/3182810. Replacing
$("html").html(data);
in the form with
document.open();
document.write(data);
document.close();
does the trick.

Refresh currentsong shoutcast

I know there are a lot of these questions about this one, but unfortunately i cant find the right answer so i try it again.
I simply want to display the current song from "http://178.19.116.253/currentsong?sid=1" on my site that must refresh every x seconds.
I rather not use php cause it will make a background process for all users, so i've seen a lot of little scripts like this..
<div id="sc_stats"><?php include_once 'sc_stats.php'; ?></div>
var refreshId = setInterval(function() {
$.get("sc_stats.php", function(data) {
$("#sc_stats").html(data);
});
}, 10000);
But i cant get mine to work without php.
Someone can help me with this?
You don't need to use php, the following snippet which only uses jQuery will display the current song and refresh it every second.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<div class="nowplaying"></div>
<script src="https://cdn.jsdelivr.net/jquery/3.2.0/jquery.min.js"></script>
<script>
setInterval(function() {
$.ajax({
url: "http://178.19.116.253/currentsong?sid=1",
dataType: "html",
success: function(data) {
$('.nowplaying').text(data);
console.log(data);
}
});
}, 1000);
</script>
</body>
</html>
Note: In order to get this to work, either:
This piece of code must run on the same domain/server as your stream
Or CORS must be enabled on your server. More about CORS can be found here
You can test CORS with the following Chrome plugin: Allow-Control-Allow-Origin:

Requete ajax to a php file that returns "undefined"

I saw that I was not the only one with such a problem, but I did not find a solution.
So the problem comes from an application much more complex than that, but trying to target the problem I realized that even a simple "Ajax" request between 2 or 3 files returns me "undefined".
Here are my files :
index.php
<body>
<button>Button</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="./main.js"></script>
</body>
main.js
$(document).ready(function()
{
$('button').click(function(){
$.post('test.php', function(data, status){
console.log('data: ' + data, status);
});
});
});
test.php
<?php
echo "lorem ipsum";
?>
When I click on the button the Ajax request returns that in there console:
data: undefined success
When my file is an index.php file it always returns "undefined" no matter the context (Of course if there is no Javascript error).
But by doing several tests I realized different results with the same content but with other file extensions, the returns are not always the same, for example:
index.html instead of index.php, same main.js and same test.php
data: success
index.html instead of index.php, and if I call a test.txt file that contains for example "lorem ipsum" it returns this :
data: lorem ipsum success
That's my problem, thank you in advance for your answers.
well, i think you have to send json instead of echo like this:
return json_encode('lorem ipsum');
try this i hope it help.
Put this code in your test.php file
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>Demo</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<button>Button</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$('button').click(function(){
$.post('abc.php', function(data, status){
console.log('data: ' + data, status);
});
});
});
</script>
</body>
</html>
in your abc.php file just put this and check and put test.php and abc.php in same folder or if abc.php is in another location just change the url of abc.php in $.post
<?php echo "hello"; ?>
I found the problem, it came from my work environment, I used this plugin https://github.com/JosephLenton/PHP-Error and by disabling it everything was working correctly ^^'
Now I have to figure out how to keep it activated while making Ajax requests xD
Thank you all for your help and sorry for wasting your time. :/
here try this:
$(document).ready(function() {
$("#button").click(function() {
$.ajax({
url: "test.php",
success: function(result) {
$("#div").html(result);
}
});
});
});
Then for the php code:
$array = array("" => "lorem", "" => " ipsum");
echo json_encoded($array);

Display JS charts in Div using jQuery.AJAX

Hi I am trying to display javascript charts in DIV tag. I want to call a url using jQuery.ajax. Following is my code.
<html>
<head>
<meta charset="utf-8" />
<link rel="stylesheet" href="./jquery-ui.css" />
<script src="./jquery-1.9.1.js"></script>
<script src="./jquery-ui.js"></script>
<script>
$(function() {
$( "#btnRun" ).click(function() {
$.ajax({
type: "GET",
url: "http://code.shutterstock.com/rickshaw/guide/start.html",
success: function(response) {
$('#divResult').html(response); // Assign the values to the DIV
}
});
});
});
</script>
</head>
<body>
<input type="button" value="Run" id="btnRun" /> </br>
<div id="divResult"></div>
</body>
</html>
I am able to call url. But not able to display content existing in that url. Can anyone help me to solve this problem.
I think you have a couple of problems here:
You're probably not allowed to do this because of Access-Control-Allow-Origin.
You can't load more JavaScript into a page asynchronous trough another HTML-file.
I got solution for my problem. I added OBJECT tag in DIV. Here is code.
$( "#btnRun" ).click(function() {
$('#divResult').html('<object data="http://code.shutterstock.com/rickshaw/guide/start.html" />');
});
Thanks for All.

jQuery ajax doesn't work with last version of chrome

Hey guys,
I have a little problem with a simple ajax request. I can't figure it out why jquery ajax method doesn't work with the last version of chrome ... on ff work great so as on opera but on chrome i don't get any response and no errors. This is my js code:
function load(idno){
var url = 'index.php';
$.get(
url,
{
pagina:"ajax",
show:"cars",
brand:idno
},
function(data) { document.getElementById("model").innerHTML=data },
"html"
);
}
Any reason you're not just using jQuery.load()? Eg
$('#model').load('index.php', {
pagina: 'ajax',
show: 'cars',
brand: idno
});
At a guess, I'd say the problem is with the innerHTML call. A more robust method would be to use jQuery.html(), eg
function(data) { $('#model').html(data); }
Edit
Just whipped up this test and it works fine
<?php
// test.php
echo '<pre>', print_r($_REQUEST, true), '</pre>';
<!-- test.html -->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<div id="model">
Default text
</div>
<p><button id="fetch-data">Fetch Data</button></p>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
jQuery(function($) {
$('#fetch-data').click(function() {
$('#model').load('test.php', {
pagina: 'ajax',
show: 'cars',
brand: 123
});
return false;
});
});
</script>
</body>
</html>
When I click the button, I can see all the request variables sent to the script
After a long long nith I've managed to resolve the problem. My JS code is good and maybe Phil's too ... I didn't try that in this version but the real problem in Chrome is that onclick attributes on option tags aren't allowed. So I made the event
<select onchange='loadData(this.value,'models')'></select>
and it is working great. Thank you Phil anyway.
because of Security reason chrome not allow cross-domain communication if request is not from a trusted sites,
if you want to use $.ajax in chrome so you need to disbale web security of chrome
use this comman.
your_chrome_path --disable-web-security
after doing this $.ajax works fine.

Categories

Resources