Passing a form value to php from a JS function - javascript

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.
});
}

Related

Parse HTML input value to php over javascript file

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)

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.

jQuery POST to PHP appears in browser, but not the PHP file

I've been pulling my hair out over this problem and I must have searched through over fifty other questions on here, to no avail. I'm trying to code a website using PHP, MariaDB, jQuery, and other web development technologies, however I've encountered issues trying to post variables from the client-side (with jQuery) to the server-side (PHP). I created a very simple file just to isolate the problem that I'm having:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<script type="text/javascript" src="jquery.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "index.php",
data: {'name': "name1"},
});
});
</script>
<body>
<?php
if(isset($_POST["name"])){
$i=$_POST["name"];
echo "num: ".$i;
}
else{
echo "No information supplied";
}
?>
</body>
</html>
I refresh the page, and I constantly get the failure message "No information supplied". I know the POST is getting sent to the browser, because I can see it in Firebug, and its status code is 200 OK, so I know that I must be doing something correctly. Is my PHP syntax messed up? I know that this will work just fine when I'm pulling data from forms embedded in the regular HTML.
Thank you for your assistance, and I apologize in advance if this is a really simple problem. I'm trying to learn web development as well as possible. I feel like I've tried everything, down to using the longer .ajax way of sending a POST variable, rather than using .post().
Here is your answer, you will be testing to see if there is an ajax request, if so process it, if not spit out your original page. As for the ajax call we are adding a success callback that will then update your body tags with your returned. data
<?php
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'){
if(isset($_POST["name"])){
$i=$_POST["name"];
echo "num: ".$i;
}
else{
echo "No information supplied";
}
die;
}
?>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html" charset="utf-8" />
<script type="text/javascript" src="jquery.js"></script>
</head>
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
type: "POST",
url: "index.php",
data: {'name': "name1"},
success: function(data){
$('body').html(data);
}
});
});
</script>
<body>
this is the original body content
</body>
</html>
Your PHP code runs before you trigger the ajax request, because the server interprets and runs PHP before you get to see the resulting HTML in the browser
What you need is add a success callback in the ajax request object which will get the result of ajax request and do something useful with it, such as place it into a <div> element. The example below simply displays it
$.ajax({
type: "POST",
url: "index.php",
data: {'name': "name1"},
success: function(serverReponse){ alert(serverResponse) }
});

jQuery AJAX function returning strange output

I'm playing around with AJAX requests to a php file via jQuery, and I'm getting some strange output.
main.php:
<!DOCTYPE html>
<head>
<link rel="stylesheet" href="/stylesheets/style.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<?php
include('main.html');
?>
<script type='text/javascript'>
$('#startButton').click(function() {
$.ajax({
method: "POST",
url: "test.php",
}).done(function(data) {
alert(data);
});
});
</script>
</body>
test.php:
<?php
echo 'Hello';
?>
Instead of alerting 'Hello' on button click, my program alerts the html of main.php. Any idea what's going on?
Figured it out - I'm using GoogleAppEngine and my app.yami file was not configured to direct requests to test.php, as it defaults all requests to main.php, hence the returned html.
Apologies for not stating that I was using GAE - I didn't think it was relevant.
Credit to #Dagon for suggesting that it was a redirecting error which led me to the correct answer.

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