The below code is executing/sending data on body load but i want to make it onclick like
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js" ></script>
<script>
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
$.each(data, function(k, ip) {
save_info = ip +","+location.hostname+",var1,var2";
/* save_info= ip +","+location.hostname+",var1,var2"; */
});
$(document).ready(function() {
var json_object = {"data": save_info};
$.ajax({
url: "http://www.example.com/test/data.php",
data: json_object,
dataType: 'json',
type: 'POST',
success: function(json_object) {
console.log(json_object);
$("#saved").text("Data has been saved.");
},
error: function(json_object) {
console.log(json_object);
$("#saved").text("Failed to save data !");
}
});
})
});
</script>
</head>
<body>
<a href="#" onclick='getJSON()'> click here</a>
<!-- I want to make json send data when this click event happens, suggest how to write onclick here -->
</body>
</html>
Please also suggest me if there is any alternative way using jquery/javascript to record this user's IP address & hostname, I want to send them to a remote page as parameters where it'll be saved.
getJSON() is not a function in itself. You never declared the function.
Do this:
function getJSON() {
$.getJSON("http://ip-api.com/json/?callback=?", function(data) {
var table_body = "";
$.each(data, function(k, ip) {
save_info = ip +","+location.hostname+",var1,var2";
});
});
}
Related
I want to post values of a JavaScript variable to a PHP page, and then use those values there.
I get back a new HTML page, which I did not want to happen. Also, it is showing the error message produced by:
echo"some error";
What am I missing? I don't understand why this happens?
Here is my html file try.html
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php" target="_blank">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
dataType: 'script' // I am not sure about what I write here script,json,html?
});
});
</script>
</body>
</html>
And this is my PHP file try.php
<?php
if(isset($_POST['text']))
{
$text = $_POST['text'];
echo $text;
}
else {
echo"some error";
}
?>
In try.php if you echo something which in turn will comeback to try.html.
If you just want to post the data to try.php and echo there the just use form and submit. You dont need ajax in that.
Ajax is to send the data/receive back without reloading the existing page. The response will be seen in the current page itself.
<html>
<head>
<title>try</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<a id="button" href="try.php">send data</a>
<script>
var sum2= 2010;
$('#button').click(function() {
var val1=sum2;
var json_params = {
text: val1
};
var json_data = JSON.stringify(json_params);
$.ajax({
type: 'POST',
url: 'try.php',
data: json_data,
dataType: "html",
success: function(response)
{
alert(response);
}
});
});
</script>
</body>
</html>
In the try.php page you can place this code
<?php
if (isset($_POST)){
$data = json_decode(file_get_contents('php://input'));
print_r($data);
}
else{
echo "not set";
}
?>
Firstly, remove script from data-type.
This is how you can pass the data to php file:
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
});
dataType - The type of data that you're expecting back from the
server. Here you don't want anything in return then it's fine. If you
are expecting anything like json or something, you can specify it.
If You want anything in response, you can handle in this manner
$('#button').click(function() {
var val1=sum2;
$.ajax({
type: 'POST',
url: 'try.php',
data: { text: val1 },
});
success: function (data) {
//Your success handler code
},
});
success - A callback function to be executed when Ajax request
succeeds.
Firstly remove href from link. By this it is directly redirecting to try.php
<a id="button" href="javascript:void(0);" target="_blank">send data</a>
I'm trying to get and display a field in a SharePoint list
using a Content Editor Web Part. This is just proof of concept, I want the CWP to display the Title (the currency) and the Currency Description. I think I just need a tweak and want to understand what I'm doing wrong. The var query URL displays the title fine.
Ultimately what I want to do is to store the returned value from the Exchange Rate column so that when a user selects a drop don in a separate list and an amount it will convert by the Exchange rate.
Any help is appreciated. Code below:
<script type="text/javascript">
DisplayExchangeRate();
function DisplayExchangeRate()
{
var listName = "Currency Exchange Rates";
var titleField = "Title";
var rateField = "Currency Description";
var query = "http://collaboration-dev.norgine.com/sites/it/Tools/IT- Contracts/_vti_bin/listdata.svc/CurrencyExchangeRates?
$select=Title,ExchangeRate&$filter=Title eq 'Dollars'";
var call = $.ajax({
url: query,
type: "GET",
dataType: "json",
headers: {
Accept: "application/json;odata=verbose"
}
});
call.done(function (data,textStatus, jqXHR){
$.each(data.d.results, function (i, result) {
$("#CurrencyExchangeRatesTitle").text(result.Title);
$("#CurrencyExchangeRatesCurrencyDescription").html
(result.CurrencyDescription);
});
});
call.fail(function (jqXHR,textStatus,errorThrown){
alert("Error retrieving Tips: " + jqXHR.responseText);
});
}
</script>
I don't believe you can put JavaScript directly in a Content Editor Web Part. Try using a Script Editor Web Part instead (housed in the same category of web parts as the CEWP), or pointing your CEWP to a local HTML page with the JavaScript.
http://info.summit7systems.com/blog/dont-script-in-the-wrong-web-part
Also, it looks like you're using JQuery. Do you have a reference to that library elsewhere that is loading successfully?
Below is my Working code , I have saved this code in a text file, and uploaded that file in "Site Assets" library and pointed my CEWP to this code file.
<script type="text/javascript" src="https://test.sharepoint.com/sites/devsite/SiteAssets/jquery-1.9.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
var i,result;
$('#getEmployee').click(function () {
var dispalyResults="";
$.ajax({
url: "https://test.sharepoint.com/sites/devsite/_api/web/lists/getbytitle('Employee')/items",
method: "GET",
headers: { "Accept": "application/json;odata=verbose" },
success: function (data) {
var jsondata = JSON.stringify(data);
result = JSON.parse(jsondata).d.results;
for (i = 0; i < result.length; i++) {
dispalyResults+="<p><h1>"+ result[i].ID + " " + result[i].Title +"</h1></p>";
}
$('#displayResults').html(dispalyResults);
},
fail: function () {
alert("Response fails");
}
})
})
})
</script>
<input type="button" value="GET" name="GET" id="getEmployee"/>
<div id="displayResults"></div>
I have created a button and a DIV tag. When i click the button , it will display the list item Title and ID inside the DIV tag.
I am having trouble passing a Javascript array to a PHP array on the same page when the submit button is pressed. I have seen discussion of JSON.stringify and json_encode on other posts, but I am not sure how to use those functions with my code.
JS:
<script>
var kegs = [];
var textarea = document.getElementById("your_textarea");
$("#kegId").on('keyup', function (e) {
if (e.keyCode == 13) {
kegs.push($(this).val());
$("#kegId").val("");
textarea.value = kegs.join("\n");
};
});
</script>
PHP:
if (!isset($_POST['btn-addkegs'])) {
//I want to set the Javascript array 'kegs' to a php variable here
Using Ajax will do it for you! I wrote this code that sends an array to PHP on the same page. Once you get the array in PHP you can do whatever you want with it :).Just copy and paste this file and called it index.php to see the result. This will totally help you!
<?php
$data = array();
if(isset($_POST['myArray']) && !empty($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = 'You array is: ' . $_POST['myArray'];
echo json_encode($data);
die();
}
?>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
</head>
<body>
<div id = "random"></div>
<script type = "text/javascript">
$(document).ready(function() {
var arr = [2,4,5,6,7];
var myArray = JSON.stringify(arr);
$.ajax({
url: "index.php",
method: "POST",
dataType: "json",
data: {myArray: myArray},
success: function (result) {
alert("result: " + result);
console.log(result);
$("#random").html(result);
}
});
});
</script>
</body>
</html>
This can be achieved by using ajax(), its syntax is:
$.ajax({
url: 'process.php', // file where data processing is done
type: 'POST',
data: {
var1 :val1,
var2 :val2
// parameter set
},
success: function(response){ // response from process.php
// do your stuff here
}
});
Read more about ajax
As you are using the jquery
var jsArray = makeJavascriptArrayhere //
$.ajax({
url: urlToPhpFile, // file where data processing is done
type: Method,
data:jsArray,
success: function(response){ // response from process.php
// do your stuff here
}
});
now in your php file
var_dump($_POST); //see on network liner tabs
I'm trying to show data after ajax call but it was disappeared after showing
here is my code:
<script src="js/jquery.js"></script>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
$(document).ready(function(){
$(".medicine").keyup(function(){
var txt=$(this).val();
$.post("search.php",{medicine:txt},function(result){
$("#search-result").html(result);
});
});
$(document).on('click','#find', function () {
var input = $("#text").val();
var url = 'row.php';
var data = input;
$.ajax({
type: "POST",
url: url,
data: {data:data},
success: function (data) {
$(document).find('table').remove();
$("#temp_table").html(data);
}
});
});
});
</script>
first function is for search bar which is working second one also working but when data comes in success function it show for a second in temporary div and vanished
When your ajax completes, the success callback function removes all <table> elements caused by the use of the .remove() function.
$(document).find('table').remove();
Description: Remove the set of matched elements from the DOM.
If you want to clear the html content of your <table> elements instead of removing them (my guess), use .empty() instead
$.ajax({
type: "POST",
url: url,
data: {
data: data
},
success: function(data) {
$('table').empty();
$("#temp_table").html(data);
}
});
Hi i've got an ajax post and the response div i want from the other file will be generated after $document_ready function. But the div show empty string when i alert it. Here's my code
var cekJawaban = function(){
var form_data={
kode:$("#code").val(),
id_materi:$("#idmateri").val(),
id_user:$("#iduser").val(),
id_lesson:$("#idlesson").val()
};
$.ajax({
url: 'http://localhost/ta2/frontpage/cekKode',
type: 'POST',
async : true,
data: form_data,
dataType: 'html',
success: function(data){
/*var res = resp;
if(resp=="true")
{
$("#alertsukses").show();
$("#submit").hide();
$("#lanjut").show();
}
else
{
$('#salah').html(resp);
$("#alertsalah").show();
}*/
console.log($(data).find('#mocha').text());
},
error: function(xhr) {
}
});
return false;
};
And here's the target url file:
<!DOCTYPE html>
<html>
<head>
<script src="<?php echo base_url('assets/jquery-2.0.3.min.js')?>"></script>
<script src="<?php echo base_url('assets/expect/jquery.expect.min.js')?>"></script>
<script src="<?php echo base_url('assets/mocha/mocha.js')?>"></script>
<link href="<?php echo base_url('assets/mocha/mocha.css') ?>" rel="stylesheet">
</head>
<body>
<script>mocha.ui('bdd');
mocha.reporter('html');</script>
<div id="mocha"></div>
<?php echo $code; ?>
<div id="cek">
</div>
<script type="text/javascript">
describe("Index", function () {
it("Harus punya div",function(){
fn();
})
})
mocha.run();
$(document).ready(function(){
var notif=""
if($('.error').length>0)
{
var err = $('.error').html();
var sub = err.substr(0,err.indexOf('#'));
notif=sub;
}
else
{
notif="pass";
}
$('#cek').text(notif);
});
var fn = function(){
$expect('body').to.exist('Jangan lupa buat body')
.and.to.have.children('p', "Jangan lupa buat p");
};
</script>
</body>
</html>
I think this is not possible, javascript is executed on client side and if you're requesting the page by ajax you will get only the static content of it. You must consider to change the work flow of your code and stick to dynamic content generation of the target url on the server-side code.
if you pursue this workflow you may get the content and also the javascript code which I think you don't want
Instead of putting your javascript document.ready() function in the "target url file", you can put the javascript code into the success-function of the Ajax call.
So you call the url, the url returns your content, and after content has been returned you can execute javascript code in the success()-function.
Example:
$.ajax({
url: 'http://localhost/ta2/frontpage/cekKode',
type: 'POST',
async : true,
data: form_data,
dataType: 'html',
success: function(data){
//Call your document.ready() here instead.
var notif=""
if($('.error').length>0){
var err = $('.error').html();
var sub = err.substr(0,err.indexOf('#'));
notif=sub;
}
}
});