Parse HTML input value to php over javascript file - javascript

I have the following scenario running:
graph.html --> uses ChartJS to display a line graph and imports graph.js
<html>
<head>
<title>ChartJS - LineGraph</title>
</head>
<body>
<div class="chart-container">
<canvas id="mycanvas"></canvas>
</div>
<form name="form" action="" method="get">
<input type="text" name="input" id="subject" value="">
</form>
<!-- javascript -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/Chart.min.js"></script>
<script type="text/javascript" src="js/graph.js"></script>
</body>
graph.js --> makes a AJAX call on the graph.php file to get the data and format it.
$(document).ready(function(){
$.ajax({
url : "/graph.php",
type : "GET",
success : function(data){
console.log(data);
...
var LineGraph = new Chart(ctx, {
type: 'line',
data: chartdata
});
graph.php --> Calls mysql database to get data
$var = $_GET['input'];
$query = sprintf("SELECT $var FROM wetter");
//execute query
$result = $mysqli->query($query);
I like to change the SELECT statement in the php-file by entering a new SELECT-statement in a input field of the .html file. If I put the normal $_GET[] method into the .php it will not find the input value from the .html file.
How can I parse the input value from the .html to the .php when there is a Javascript file in between?
Do I need to change something in my scenario?

From the code you've shown, it doesn't look like you're passing the input value along with your ajax request, you should add something like
$.ajax({
url : "/graph.php",
type : "GET",
data : {input : $('#subject').val()}, <-- added this
success : function(data){
In order to be able to see the value in $_GET['input'] on the php side.
But there is another issue I believe, your ajax request is sent as soon as your document is ready ($(document).ready(function(){), but at that time your input is most likely going to be empty. You probably want to change it to $('form[name="form"]').on('submit',function(event){event.preventDefault(); ...}), assuming your form only does that one thing (display a graph according to the input)

Related

How to convert JavaScript variable into PHP through ajax

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.

Convert HTML div to image in jQuery

I want to pass an url from my jsp page. It should parse that page, fetch a specific div of html and convert div output in to a image and display it on my page.
Example: I pass www.google.com and output of div i want to convert in image is
I got a good jQuery for the same "http://codepedia.info/convert-html-to-image-in-jquery-div-or-table-to-jpg-png/" but its working on local page only not allowing to pass a URL
can anyone help in this matter.
#Pushkar Sharan you can do this with html2canvas just add some script
like jquery-ui.css, jquery.js, jquery-ui.js,
https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js
then try to understand below code
<html>
<head>
<link href="jquery-ui.css" rel="stylesheet">
<script src="jquery.js"></script>
<script src="jquery-ui.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/0.4.1/html2canvas.js"></script>
<script>
$(window).load(function(){
$('#load').click(function(){ //calling this function when Save button pressed
html2canvas($('#cont'), {//give the div id whose image you want in my case this is #cont
onrendered: function (canvas) {
var img = canvas.toDataURL("image/png",1.0);//here set the image extension and now image data is in var img that will send by our ajax call to our api or server site page
$.ajax({
type: 'POST',
url: "http://localhost/my/index.php",//path to send this image data to the server site api or file where we will get this data and convert it into a file by base64
data:{
"img":img
},
success:function(data){
$("#dis").html(data);
}
});
}
});
});
});
</script>
</head>
<body>
<div id="cont">
</div><br>
<center><input type="button" value="Save" id="load"></center><br>
<div id="dis"></div>
</body>
</html>
Now server site program suppose this is index.php so
index.php
<?php
$img = $_POST['img'];//getting post img data
$img = substr(explode(";",$img)[1], 7);//converting the data
$target=time().'img.png';//making file name
file_put_contents('uploads/'.$target, base64_decode($img));//converting the $img with base64 and putting the image data in uploads/$target file name
//now just check in your upload folder you will get your html div image in that folder
?>

Trouble combining jQuery and .php in Wordpress

I am trying to make a simple translation site here:http://traductordeinglesaespanol.co/. I created a simple php code that uses get to an external translation api which works fine. Here's the code:
<?php
if(!empty($_GET['text'])){
$trans_url ='http://api.mymemory.translated.net/get?q='.urlencode($_GET['text']).'&langpair=en|es' ;
$trans_json = file_get_contents($trans_url);
$trans_array = json_decode($trans_json, true);
echo $trans_array['responseData']['translatedText'];
}
?>
Here is the simple html form:
<form id="form" method="get" action="tran.php">Enter Text to be Translated below:
<input name="text" type="text" id="test" />
<button id="but">Translate</button></form>
<div class="results"></div>
The translation works ok now but I what I would like to do is to grab the tran.php result using jQuery and show it in the "result" class below the form. I am trying to do this by the following:
I loaded by editing the functions.php file so it loads jQuery and a .js script named tran.js. When I inspect element I see both jQuery and the script being loaded. In the script I put this basic code:
jQuery(document).ready(function(){
$('#go').click(function() {
$.ajax({
type: 'GET',
url: 'tran.php',
success: function(data) {
$('.result').html(data);
}
});
});
});
and change action to to handle the form from this page. (tran.php is in the root directory.) But it isn't working at all. I suspect there is/are some crucial mistakes in the coding but being a complete beginer I cannot find where the mistakes are so any advice/correction would be greatly appreciated!
I somehow managed it to work! There was a small typo:
data : 'text=' + to_be_translated;
I replaced the ";" in the end with a comma and now I am getting the result like this: Let's say I input the text name to translate (nobre in spanish!), I get this:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"/> <title>estes</title> </head> nombre
So I have to get rid of these headers somehow! Anyway I want to thank you again very much for your help! Gracias!
You should use ajax this way :
var to_be_translated = "Hello";
$.ajax({
type: 'GET',
url: 'tran.php',
data : 'text=' + to_be_translated,
success: function(data) {
$('.result').html(data);
}
});
Here I added the "data" label, it says the JS variable to_be_translated will be seen as $_GET['text'] in PHP.

Passing a form value to php from a JS function

I am working on the following code and I am trying to pass the content of an input text called "stName" to the php code:
<!DOCTYPE html>
<html><head>
<meta charset="utf-8">
<title>Untitled Document</title>
<link rel="stylesheet" type="text/css" href="jquery.mobile-1.4.4.min.css">
<script src="jquery-1.11.1.min.js"></script>
<script src="jquery.mobile-1.4.4.min.js"></script>
<script type="text/javascript" charset="utf-8" src="cordova.js"></script>
<script charset="utf-8" type="text/javascript">
function connect()
{
$.ajax({
url:'hostname/reply.php',
headers:{"Content-Type": "application/json"},
type:'POST',
data:$('form').serializeArray(),
//data:$(this),
dataType:'JSON',
error:function(jqXHR,text_status,strError){
alert(strError);},
timeout:60000,
success:function(data){
$("#result").html("");
for(var i in data){
$("#result").append("<li>"+data[i]+"</li>");
}
}
});
}
</script>
</head>
<body>
<center><b>My Students</b></center>
<center>
<form>
<input type="text" value="Joe" name ="stName" />
<input onclick="connect()" type="button" value="showStudents" />
</form>
</center>
<center><b>Results</b></center>
<ul data-role="listview" id="result"></ul>
</body>
</html>
And the simple php code is:
<?php
$data = json_decode($_POST['data'], true);
$message[] = $data;
print json_encode($message);
?>
The code that accesses the database has been stripped out. I just want to access the form value and it is not working. Any advice please?
Ajax is no different to what browsers do when you send a form (via the action attribute):
It does a HTTP request to some URL. For POST requests, the default is to send the query string in the body of the request in form:
key1=value1&key2=value2
You may know this from URLs as the part after the ? character.
For parameter data of $.ajax function you pass exactly this query string. However you may also pass an object, which gets converted automatically to a query string. For example, your form data could be represented as this object:
{
stName: "Joe"
}
And it would be converted by $.ajax to the query string and sent in the body of Ajax request:
stName=Joe
This query string would also be sent to your script, would you use the action attribute for the form element.
In your PHP script, you can then access the parameters through the $_POST array, with the keys in the query string being the keys in the $_POST array. For example, to print out stName parameter:
echo $_POST["stName"];
All this doesn't have much to do with JSON. In fact, you don't need JSON in order to use Ajax. Sending query strings is sufficient for many cases. Your code could be rephrased like this:
function connect()
{
$.ajax({
url:'hostname/reply.php',
type:'POST',
data: {
stName: $('#name-input').val() // Give the input an id
},
error:function(jqXHR,text_status,strError){
alert(strError);},
timeout:60000,
success:function(data){
// JSON is decoded for you if Content-Type of response is set appropriately.
});
}

How To Set Language to Chinese Using Ajax Form Submit to A Different PHP File?

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']);

Categories