ajax with json how to - javascript

I try AJAX and JSON.
I have got this very simple scripts. Could you help me to get it work?
html file
<div class="esemeny">
<h2>Event</h2>
<p></p>
<button>click</button>
</div>
json file, I call it eventresult.json
{name: whatever,
}
and the javascript file
$(function(){
$('button').on('click', function(){
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
Thank you

You didn't tell what did want to do exactly, anyway I think, this what you want to do:
JSON:
{
name: "whatever"
}
JS:
$(function(){
$('button').on('click', function(){
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
type: 'GET' // you want to get content
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});
Hope that helps a bit

I guess your JSON should look like
{
name: "whatever"
}
Mind the double quotes and the unnecessary comma.

Well,you actually didn't descripte the question clearly.You can have a debug that can be seen from your firebug console,like this:
$.ajax('/javascript/eventresult.json', {
dataType: 'json',
success: function(result){
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
}).fail(function(jqXHR, textStatus, errorThrown){console.log(textStatus+':'+ errorThrown)})

Here are some suggestions that should make it work:
Make sure you include the necessary script files in your html file:
<head>
<script type='text/javascript' src='http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js'></script>
</head>
<div class="esemeny">
<h2>Event</h2>
<p></p>
<button>click</button>
</div>
<script src="javascript.js"></script>
Make sure you use valid json in the json file
{
"name": "whatever"
}
Use .click() function in your javascript:
$(function() {
$('button').click(function() {
$.ajax('/trials/eventresult.json', {
dataType: 'json',
success: function(result) {
var esemeny = $('.esemeny');
esemeny.find('p').html(result.name);
}
});
});
});

Related

jQuery shows output but instantly dissapears

I'm creating a PHP application where I have to send a JavaScript variable to the same page and then use it in PHP. However when I run my code the output shows and is correct but it goes away and dissappears.
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { id: 1},
success: function(result) {
$('body').html(result);
console.log(result);
},
error: function() {
alert('Some error happened. Please try again!');
}
});
I accessed the posted variable via PHP post variable and the output is correct but I cant get it to stay on the screen. Is the innerHTML of my ajax.php being overwritten?
The console shows correct output also !
Are you doing something else with your html <body> element? If I were you, I'd make a new element in the body and put your results there.
$.ajax({
type: 'POST',
url: 'ajax.php',
data: { id: 1},
success: function(result) {
$('#results').html(result);
console.log(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<html>
<head>
<title>Title</title>
</head>
<body>
<div id="results"></div>
</body>
</html>
You are calling body attributes, try changing this line:
$('body').html(result);
To;
$("#myResult").html(result);
You can now print your response by adding this to your HTML code:
<div id="myResult"></div>
If you want to select via a Class instead:
$(".myResult").html(result);
Here, the ID selector # is replaced by the Class selector . so your div will now become:
<div class="myResult"></div>
Now try this:
$.ajax({
type: 'POST',
url: 'ajax.php',
data: {id: 1},
success: function(result) {
// $('body').html(result);
// $(".myResult").html(result);
$("#myResult").html(result);
console.log(result);
},
error: function() {
alert('Some error found. Please try again!');
}
});
On the HTML side enter this:
<div class="myResult"></div>

How To add another post name/variable inside ajax script

<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: "epdate="+$("#epdate").val(),
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
i have this code and i want to add another variable
inside ajax script adding another
data: "empname="+$("#empname").val(),
dopesnt work i hope someone would help me. thank you
and how can i call a postname or make a postname into session an call it into another php page?
Actually, there are multiple ways, either separate them using a & character.
<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: "epdate=" + $("#epdate").val() + "&empname="+$("#empname").val(),
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
Or alternatively, you can use an object which holds the name-value pair.
<script type="text/javascript">
$(function() {
$("#epdate").bind("change", function() {
$.ajax({
type: "GET",
url: "change6-emp.php",
data: { epdate : $("#epdate").val(), empname : $("#empname").val() },
success: function(html) {
$("#output").html(html);
}
});
});
});
</script>
UPDATE 1: You can also pass it as an array in the following format,
data : [{
name : 'epdate',
value : $("#epdate").val()
}, {
name : 'empname',
value : $("#empname").val()
}],
UPDATE 2: There is build in functions in jQuery to do the same, use [serialize()][] or serializeArray() method for that. You can apply it on a form element or input elements and which generates based on the input elements name attribute.
data : $('#epdate,#empname').serialize(),
// or
data : $('#epdate,#empname').serializeArray()
,

How can I display the data from the JSON on my webpage?

I am writing a script that sends an ajax request. The Cloud seems to response with the JSON, but how can I display the data from the JSON on my webpage?
Here the link for the pretty printed JSON.
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<script>
function myFunctionPost() {
jQuery.ajax( {
url: 'https://iotmmss0018275632trial.hanatrial.ondemand.com/com.sap.iotservices.mms/v1/api/http/app.svc/T_IOT_77877E443B666B7FED2F?$format=json',
type: 'POST',
crossDomain: true,
dataType: 'jsonp',
success: function( response ) {
console.log(response);
},
error : function(error) {
console.log(error);
}
} );
}
</script>
</body>
</html>
To achieve this you can use JSON.stringify() space argument. You will also need to wrap the output with <pre> </pre> will preserve the line spacing.
function myFunctionPost() {
$.ajax( {
url: 'https://jsonplaceholder.typicode.com/posts',
type: 'GET',
success: function(response) {
$('#pp').html('<pre>' + JSON.stringify(response, undefined, 4) + '</pre>');
},
error: function(error) {
console.log(error);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<button onclick="myFunctionPost()">Start</button>
<p id="pp"></p>
</body>
</html>
Source: Does jQuery have a JSON/javascript object to HTML pretty print function similar to PHP's var_dump?
By var responseObject = json.parse(response) to make a javascript object.
And then do as you would with JS object?
Hard to tell exact code without knowing what do you wanna display, in what HTML.

AJAX Replace Span String with External Date String

Good morning,
I have Livestamp.js on my website and an external .php file that parses a date string from the VATSIM data file.
The code for the PHP file is:
<?php
require_once './vendor/autoload.php';
$logFile = './vendor/skymeyer/vatsimphp/app/logsusers.log';
$vatsim = new \Vatsimphp\VatsimData();
$vatsim->setConfig('cacheOnly', true);
$vatsim->setConfig('logFile', $logFile);
if ($vatsim->loadData()) {
$info = $vatsim->getGeneralInfo()->toArray();
echo "{$info['update']}";
} else {
echo "Cannot load data";
}
?>
This is my code for pulling the date string from the external file into my website:
<script type="text/javascript">
function get_update() {
$.ajax({
type: 'POST',
url: 'update.php',
data: {
request: 'true'
},
success: function(reply) {
$('.data-livestamp').html("" + reply + "");
}
});
}
$(document).ready(function() {
get_update();
});
</script>
The Livestamp.js code for the HTML has to look something like this: <span data-livestamp="1454063536"></span>
How can I change the AJAX code to either replace the example date string with the data string from my PHP file or to insert the contents of the PHP file in between the quotation marks in the <span data-livestamp="1454063536"></span> line?
Thanks very much in advance.
simply you can do this !
success: function(reply) {
$("[data-livestamp]").data('livestamp', reply)
}
Try this:
success: function(reply) {
$("[data-livestamp]").attr('data-livestamp', reply)
}
I worked the answer out:
<script type="text/javascript">
function get_update() {
$.ajax({
type: 'POST',
url: 'update.php',
data: {
request: 'true'
},
success: function() {
$('#update').livestamp(new Date());
}
});
}
$(document).ready(function() {
get_update();
});
</script>

Ajax not working using jquery url post method

I am trying to make a stepy-form for my project. What I want to do is I want to submit all my data step by step in stepy-form so I used an AJAX request for this purpose, but When I am trying to save it it's not working. So I used noConflict Method to avoid jQuery conflicts but I still have the same problem. I am using adminEX template And Not getting any error message. So can anyone help me?
<script src="ajax/jquery.min.js"></script>
<script>
$.noConflict();
Jquery(document).ready(function(){
$('#stepy_form').click(function(){
$.ajax({
type: 'POST',
url: 'ajax/insert_all.php',
data: {
txtVehicleNo: txtVehicleNo,
SltType: SltType,
txtPANNumber: txtPANNumber,
txtManufacture: txtManufacture,
txtModel: txtModel,
txtEngineNumber: txtEngineNumber,
txtChassisNumber: txtChassisNumber,
txtOwnerName: txtOwnerName,
txtUnlaidenWt: txtUnlaidenWt,
txtGVW: txtGVW
// qid: 'form1'
},
//alert('hello');
//async: true,
//cache: false,
success: function(result) {
alert('SUCCESS');
//$('#target').html(result);
}
});
});
});
</script>
And this one is the URL ,insert_all.php
$qid = $_POST['qid'];
echo $qid;
You are not using 'no conflict' with jquery and accessing it using $. Change $ with jQuery like this
$.noConflict();
jQuery(document).ready(function(){
jQuery('#stepy_form').click(function(){
jQuery.ajax({
type: 'POST',
url: 'ajax/insert_all.php',
data: {
txtVehicleNo: txtVehicleNo,
SltType: SltType,
txtPANNumber: txtPANNumber,
txtManufacture: txtManufacture,
txtModel: txtModel,
txtEngineNumber: txtEngineNumber,
txtChassisNumber: txtChassisNumber,
txtOwnerName: txtOwnerName,
txtUnlaidenWt: txtUnlaidenWt,
txtGVW: txtGVW
},
success: function(result) {
alert('SUCCESS');
//$('#target').html(result);
}
});
});
});

Categories

Resources