its the code for posting a javascript variable into php...
but its not working..sugesstion...
i want to take value of id from javascript and post into a php.
<!DOCTYPE html>
<html>
<body>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
$( document ).ready(function() {
$("form").submit(function() {
var id = $("input[type=submit]").attr('id');
alert(id);
$.ajax({
type: 'post',
url:('abcde.php')
data: {id1: id},success: function(response){}
alert(id1);
});
});
});
</script>
</head>
<form action="abcde.php" method="POST">
<!-- other form fields -->
<input type="submit" id="a" name="idVal" value="a">
</form>
</body>
</html>
<?php
if(isset($_POST['id']) ){
$id=$_POST['id'];
echo $id;
}
?>
ohh boy, 1st: it's
data: {'id': id}
secondly, your code is really wrong on this part, you are not doing anything in success, and you just randomly put an alert() in, with a variable that doesn't even exist.
So instead of success: function(response){}, it should be success: function(response){alert(response);} and forget about the alert(id1);
Other errors I saw from looking at it quickly: you are submitting your form from AJAX and HTML as well. You should block the default behavior with a function at the beginning of .submit(funcition() {...}. There already is a function for that, but I can't remember.
Lastly, you are sending the form data to the same page you are submitting from. You will get an answer from AJAX with the same page you are looking at. You should extract the php code to a different file and make abcde.php a simple abcde.html file.
One last thing: instead of alerts, you should use Console.log and watch the browser's console for debugging. You will see a bunch of errors, which makes debugging a lot easier.
You should, instead of blindly coding, be more mindful about what is responsible for what. You should be thinking more about the side-effects of you are introducing to your code. This will come with experience, we've all been there. Make sure one 'thing' is only responsible for ONE task.
Given my html file, the console gives an error code:
Reference Error: loadData not defined.
Based from other answers I've rechecked mine where,
My function is declared just before the </body>,
I included the javascript library at the <head></head> ;
and even changed my <input type= submit to <input type= button
and if it helped, I tried deleting my form tags where it is enclosed (but this is for another question regarding query strings).
Here's how it would look like now:
<head>
<script src = "//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
</head>
<body>
{%for document in documents %}
<li> {{document.filename}}
<input type="button" id="{{ document.id }}" onclick="loadData(this.id)" name = "load-data" value="Add to Layer"/>
</li>
{%endfor%}
<script type ="text/javascript">
function loadData(documentId){
$.ajax({
url:"/load",
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}
</script>
</body>
I can't seem to find an explanation why the function won't fire.
Here's the fix (as my friend explained):
I had to put my script up in the <head> tags.
Why? Because the document is already loaded before the script gets to be.
If I want to retain it at the bottom it had to look something like this:
$(document).ready(
$('input').onclick(function(){})
After putting it up the code works.
I've tested your html and everything seems to be working properly. The only error that I found was that $ajax is not a function. It is missing a dot $ajax => $.ajax
Try using:
function loadData(documentId){
$.ajax({
url:"/load",
data: {'documentId': documentId},
type: 'GET',
success: function(){
window.location.href = "http://127.0.0.1:8000/url/locations";
}
});
}
My aim is to get an element <div id="calender"> and all what is in the element shown in a browser. The point is that normal get-html-source won't do the thing. The element what I am looking for does not exists in the html output of php-function file_get_contents.
I have tried to get the source by php with xpath byt the help of http://us3.php.net/manual/en/class.domxpath.php which inludes a nice tool to get what is in any tag in the html page. But the problem here might be that the element (a calender) is formed to the loaded page by javascript and cannot be caught by server side php. So, is there a way I can catch such element (div) by javascript instead.
There are script examples of javascript for this kind of problem (if I have understood them correctly) but currently I cannot get a simple javascript to work. An example below shows how I have tried to built up a code. $ajax thing here is just one path I have tried to solve the problem but don't know how to use it. More here I cannot figure out why the simple javascript functions do not work (just test purposes).
<!doctype html>
<html lang="fi">
<head>
<meta charset="utf-8">
<title>load demo</title>
<style>
body {
font-size: 12px;
font-family: Arial;
}
</style>
<script type="text/javascript">
function ok {
alert "OK";
}
function get_html (my_html){
alert "OK";
var l = document.getElementById('my_link').value;
alert l;
alert my_html;
var url = my_html;
$.ajax({
url: url,
dataType: 'html'
success: function(data){
//do something with data, which is the page 1.html
var f = fs.open("testi_kalenteri.html", "w");
f.write(data);
f.close();
alert "data saved";
}
});
}
</script>
</head>
<body>
<p id ='my_link' onclick='get_html("lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192")'>html-link</p>
<p id ='ok' onclick='ok()'>show ok</p>
</body>
</html>
Briefly, I have a link to a web page, which shows up a (booking) calendar in it but this calendar is missing in the "normal" source code, by file_get_contents (php). If I browse the html source with Chromes tools (F12) I can find the calendar there. T want that information get by javascript or by php or such.
If you read the source code of the page you point to (http://www.yllaksenonkalot.fi/booking/varaukset_akas.php), you notice that the calendar is loaded via an iframe.
And that iframe points to that location :
http://www.nettimokki.com/bookingCalendar.php?id_cottage=3629&utm_source=widget&utm_medium=widget&utm_campaign=widget
Which is in fact the real source of the calendar...
EDIT following your comment on this answer
Considering the real link : http://www.lomarengas.fi/en/cottages/kuusamo-rukasaukko-9192
If the calendar is not part of the generated html, it is surely asynchronously generated (in javascript, client side).
From this asumption, I inspected the source code (again).
In the developper tools of my browser, in the Network section, where you can monitor what files are loaded, I looked for
calls to server (everything but calls to resources : images, stylesheets...).
I then noticed calls to several urls with json file extensions like http://www.lomarengas.fi/api-ib/search/availability_data.json?serviceNumber=9192¤tMonthFirstDate=&duration=7.
I felt I was on the right track (asynchronous javscript calls to generate html with json datas), I looked for javascript code or files that was not the usual libraries files (jquery, bootstrap and such).
I stumbled upon that file : http://www.lomarengas.fi/resources_responsive/js/destination.js.
It contains the code that generates asynchronously the calendar.
tl;dr
The calendar is indeed generated asynchronously.
You can't get the full html with a curl or file_get_content in PHP and
you can't access it with ajax code (due to Same-origin policy).
By the way, you should contact the site to see if you can access their api via PHP with their consent.
Hope it helped you understand the whole thing...
To get <div id="calender"> you can use next code (jquery):
<div id="calender"></div>
<script>
$("#calendar").click(function(){
alert('calendar was clicked');
});
</script>
If I understand you correctly. I think you need appropriate php respond with some correct code inside php file:
// json_handler.php
<?php
if (is_ajax()) {
$return = $_POST;
$return["ok"]="ok";
$return["json"] = json_encode($return);
echo json_encode($return);
}
function is_ajax()
{
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
and this is script wich is inside html:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<a id="click">click</a>
<script>
$("document").ready(function(){
$("#click").click(function(){
var data = {
"request": "request"
};
data=$.param(data);
// alert(data);
$.ajax({
type: "POST",
dataType: "json",
url: "json_handler.php",
data: data,
success: function(data) {
// here you will see echo respond from your php json_handler.php
// also you can add here more javascript (jquery code) to change your page after respond
alert();
}
});
return false;
});
});
</script>
<body>
<html>
http://www.w3schools.com/jquery/jquery_ajax_intro.asp
I am working on a project with Chinese language (gb2312). We have a form that submit customer input data from File 1 to a php File 2 using Ajax. The two files display Chinese without problem. But when the same data was submitted from File 1 to File 2, it turned to be totally wrong characters. For example:
File 1
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<div id="msg">0</div>
<form id="add-form" action="file2.php" method="POST">
<input type=text name='content' value='试试这个' >
<input type="button" id="add-post" value="Run Code" />
</form>
<script>
$(document).ready(function()
{
$("#add-post").click(function()
{
$("#add-form").submit(function(e)
{
$("#msg").html("<img src='/image/progress_bar.gif'/>");
var postData = $(this).serializeArray();
var formURL = $(this).attr("action");
$.ajax(
{
url: formURL,
type: "POST",
data : postData,
contentType: "application/x-www-form-urlencoded;charset=gb2312",
success:function(data, textStatus, jqXHR)
{
$("#msg").html('<pre>'+data+'</pre>');
},
});
e.preventDefault(); //STOP default action
e.unbind();
});
$("#add-form").submit(); //SUBMIT FORM
});
});
</script>
</body>
</html>
File 2
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
</head>
<body>
<?php
echo $_POST['content'];
?>
</body>
</html>
Both of the files display Chinese characters without problem. But when submitting content in Chinese from File 1 to File 2 the content becomes garbled not appears to be the correct characters. I think the problem should be somewhere in the Ajax submit script but do not know how to fix it.
Would you please help me? Thank you in advance.
Yes, the problem is definitely occurring at the Ajax request. If you look at the jQuery documentation for the contentType property, you will see the following note:
The W3C XMLHttpRequest specification dictates that the charset is always UTF-8; specifying another charset will not force the browser to change the encoding.
You can return gb2312 characters when rendering the page for the browser, but it looks like the Ajax request will always be sent in UTF-8. You will therefore need to have your PHP script accept UTF-8 in order to get it to parse the data correctly. I suggest removing the contentType header from the Ajax request.
After your PHP received the UTF8-encoded string, you can convert it back into gb2312 using the iconv function:
$chinese_content = iconv('UTF-8', 'GB2312', $_POST['content']);
I'm trying to read JSON data from a webserver but am lost. I don't get any errors but my code doesn't display anything either. Here's the sample
<!DOCTYPE HTML>
<html>
<head>
<script type="text/javascript"
src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script>
$(document).ready(function(){
$.getJSON('http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?', function(json) { //this works. but doesn't display any alerts or data
//$.getJSON('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo&callback=?', function(json) { //this works. notice the callback
//$.getJSON('http://api.geonames.org/citiesJSON?north=44.1&south=-9.9&east=-22.4&west=55.2&lang=de&username=demo', function(json) { //this also works
alert("good");
alert(JSON.stringify(json));
console.log(JSON.stringify(json));
});
});
</script>
</head>
<body>
<div id = 'placeholder'></div>
</body>
</html>
If you notice I've tried 3 $.getJSON statements with different URLs, 2 work, but the one with the key in the url doesn't display any alert upon success.
The "example" url "http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?" works fine (when example replaced with an actual domain) if posted in the browser, and returns JSON data as
[{"FCCID":"52601","Calls":"WAWZ","StnFreq":"99.1","MktID":"18","StnOwner":"Pillar of Fire","StnNameHD1":"Star 99.1","StnDescrHD1":"Great Christian Music!","StnContentHD1":"Music","StnGenreHD1":"Religious","StnAltGenreHD1":null,"StnLangHD1":"English","StnWebsiteHD1":"www.star991fm.com","StnFBHD1":"facebook.com\/star991fm","StnTwitterHD1":"http:\/\/twitter.com\/star991fm","StnEmailHD1":"","StnSMSHD1":"","StnPhoneHD1":"(800) 791-0991","StnRebrHD1":"none","StnFeatHD1":"0","StnAEHD1":"Unknown","StnLogoHD1":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD1":"","StnNameHD2":"WAWZ-HD2","StnDescrHD2":"Teaching and Preaching","StnContentHD2":"News\/Talk","StnGenreHD2":"Religious","StnAltGenreHD2":null,"StnLangHD2":"English","StnWebsiteHD2":"www.star991fm.com","StnFBHD2":"","StnTwitterHD2":"","StnEmailHD2":"","StnSMSHD2":"","StnPhoneHD2":"(800) 791-0991","StnRebrHD2":"none","StnFeatHD2":"0","StnAEHD2":"Unknown","StnLogoHD2":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD2":"","StnNameHD3":"WAWZ-HD3","StnDescrHD3":"The Energy","StnContentHD3":"Music","StnGenreHD3":"Religious","StnAltGenreHD3":null,"StnLangHD3":"English","StnWebsiteHD3":"www.star991fm.com","StnFBHD3":"","StnTwitterHD3":"","StnEmailHD3":"","StnSMSHD3":"","StnPhoneHD3":"(800) 791-0991","StnRebrHD3":"none","StnFeatHD3":"0","StnAEHD3":"Unknown","StnLogoHD3":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/5\/e\/5e0838767af7ede3d99de2c093be5c2b.png","StnAudioHD3":"","StnNameHD4":"","StnDescrHD4":"","StnContentHD4":"","StnGenreHD4":null,"StnAltGenreHD4":null,"StnLangHD4":null,"StnWebsiteHD4":"","StnFBHD4":"","StnTwitterHD4":"","StnEmailHD4":"","StnSMSHD4":"","StnPhoneHD4":"","StnRebrHD4":"none","StnFeatHD4":"0","StnAEHD4":"Unknown","StnLogoHD4":"","StnAudioHD4":""},{"FCCID":"49587","Calls":"WDHA","StnFreq":"105.5","MktID":"20","StnOwner":"Greater Media","StnNameHD1":"","StnDescrHD1":"The Rock of New Jersey","StnContentHD1":"Music","StnGenreHD1":"Rock","StnAltGenreHD1":null,"StnLangHD1":null,"StnWebsiteHD1":"www.wdha.com","StnFBHD1":"www.facebook.com\/pages\/1055-WDHA","StnTwitterHD1":"http:\/\/twitter.com\/wdhafm","StnEmailHD1":"","StnSMSHD1":"","StnPhoneHD1":"(973) 455-1055","StnRebrHD1":"","StnFeatHD1":"0","StnAEHD1":"Live","StnLogoHD1":"http:\/\/apistatic.ibiquity.com\/uploads\/logos\/e\/b\/eb72e37fe8f446bd44d783b1b641fff0.png","StnAudioHD1":"","StnNameHD2":"","StnDescrHD2":"","StnContentHD2":"","StnGenreHD2":null,"StnAltGenreHD2":null,"StnLangHD2":null,"StnWebsiteHD2":"","StnFBHD2":"","StnTwitterHD2":"","StnEmailHD2":"","StnSMSHD2":"","StnPhoneHD2":"","StnRebrHD2":"","StnFeatHD2":"0","StnAEHD2":"Unknown","StnLogoHD2":"","StnAudioHD2":"","StnNameHD3":"","StnDescrHD3":"","StnContentHD3":"","StnGenreHD3":null,"StnAltGenreHD3":null,"StnLangHD3":null,"StnWebsiteHD3":"","StnFBHD3":"","StnTwitterHD3":"","StnEmailHD3":"","StnSMSHD3":"","StnPhoneHD3":"","StnRebrHD3":"","StnFeatHD3":"0","StnAEHD3":"Unknown","StnLogoHD3":"","StnAudioHD3":"","StnNameHD4":"","StnDescrHD4":"","StnContentHD4":"","StnGenreHD4":null,"StnAltGenreHD4":null,"StnLangHD4":null,"StnWebsiteHD4":"","StnFBHD4":"","StnTwitterHD4":"","StnEmailHD4":"","StnSMSHD4":"","StnPhoneHD4":"","StnRebrHD4":"","StnFeatHD4":"0","StnAEHD4":"Unknown","StnLogoHD4":"","StnAudioHD4":""}]
Please let me know if I'm doing something stupid here. I'm completely new to Javascript and just starting to learn.
$.get( "http://api.example.com/madata.php?zip=08854&key=36e25aa7518a6092&callback=?", function( data ) {
console.log(data.FCCID);
}, "json" );
This should help you. You can do what you want with the returned data.