I have overridden the .submit function of a form on this web-page, because the webpage is loaded inside the #mainContent in an "index.php", and I want the Submit button to replace only this #mainContent.
I am trying to get the data from this form to a .php file in order to make queries to a database (or simply echo populated variables, to indicate that data was passed).
I am very new to AJAX. Can someone explain to me how to pass the data to the .php file, or point me to a resource that will give me some clarification?
Right now I'm simply trying to pass a string to a variable and echo it back.
Could someone clarify what the first element in the "data: {thisElement: notThisOne}," refers to? Is it the "name" of an attribute in the form? The name of the variable it will be passing to the php script in the 'url:' ?
Thanks for clarify this.
Here is my 'search.html' file (which is embedded in another 'index.php' file):
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="main" data-role="content" id="main">
<div id="holder">
<h1>Search</h1>
<div class="left">
<form name="searchForm" id="searchForm" onsubmit="return false;">
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<legend><h3>Course</h3></legend>
<select name="courseSelect" id="courseSelect" name="courseSelect">
<option value="*">All</option>
<option value="COMM2216">COMM-2216</option>
</select>
</fieldset>
<p>
<fieldset data-role="controlgroup" data-type="horizontal" data-role="fieldcontain">
<legend><h4>Type:</h4></legend>
<input type="radio" name="lecLab" value="lec" id="lec"/>
<label for="lec">Lecture</label>
<input type="radio" name="lecLab" value="lab" id="lab">
<label for="lab">Lab</label>
<input type="radio" name="lecLab" value="*" id="both" checked="checked">
<label for="both">Both</label>
<p>
</fieldset>
<input type="submit" value="Go">
</form>
</div>
</div>
</div>
<script src="./scripts/searchGo.js"></script>
</body>
</html>
The 'searchGo.js':
$(document).ready(function() {
$("#searchForm").submit(function(e)
{
//e.preventDefault();
$.ajax({
type: "POST",
url: "./scripts/php_test.php",
data: {courseSelect: "Lecture, or Lab?"},
success: function(){
alert($lecOrLab);
$("#holder").load("./scripts/php_test.php");
}
}) ;
});
});
Finally, the 'php_test.php':
<html>
<head>
</head>
<body>
<?php
$courseSelect = $_POST['courseSelect'];
echo ($courseSelect);
?>
</body>
</html>
Am I collecting the data in the php_test.php incorrectly? Or assigning it in the 'data: {},' (of searchGo.js) incorrectly?
Thanks for clarification.
First you shouldn't perform a search with POST, you are not modifying states(Deleting or updating records). Use a GET request instead.
The data in the ajax request is what you want to pass to the request. Use jQuery serialize that encodes a set of form elements as a string for submission.
$.ajax({
type: "GET",
url: "./scripts/php_test.php",
data: $("#searchForm").serialize(),
success: function(data){
$("#holder").html(data);
}
});
Now, in your php file you should be looking at the $_GET. Something like this:
$courseSelect = $_GET['courseSelect'];
//now query your db and return your results based on your form fields.
PHP try:
echo json_encode($courseSelect);
Javascript: I'm not seeing where $lecOrLab is defined? Also for the success method, you're not getting the response correctly. Try this:
success: function(response){
var resp = $.parseJSON(response);
console.log(resp);
// do stuff with resp
}
Related
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create a webpage, that allows user to input values, then send to 192.168.1.101:8081 via GET request.
$(document).ready(function()
{
$(".sendButton").click(function()
{
var a = $(this).attr('value');
var b = $(this).attr('value');
$.get("http://192.168.1.101:8081/", {valueA=a}, "&" , {valueB=b});
});
});
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<form action="/action_page.php">
<fieldset>
<legend><b><font size="4">Reference Points:</font></b></legend>
Value A:<br>
<input type="text" value="">
<br>
<legend><b><font size="4">Reference Points:</font></b></legend>
Value B:<br>
<input type="text" value="">
</fieldset>
<br>
<br><input type="submit" class="sendButton" value=" SEND "/b>
</form>
</body>
</html>
I know there're syntax errors. Because I know nothing about html and javascript, and only basic of php, so please excuse me.
So, when the "SEND" button is clicked, the 192.168.1.101:8081 will receive a the values from the inputs in the webpage. How? please help. Thanks
You're in the right path.
I'd suggest you to use the submit event instead:
https://api.jquery.com/submit/
Also USE AJAX, it takes care of asynchronous calls to the server.
Add an id attribute to your form and do something like this:
data: $(this).serialize() will take care of getting all the input values.
$('#you-form-id').on('submit', function (e) {
e.preventDefault();
var path = "http://192.168.1.101:8081/";
$.ajax({
url: path,
type: "POST",
data: $(this).serialize(),
async: true,
success: function (data) {
console.log(data);
$('div#ajax-results').html(data.output);
location.reload();
}
});
});
Using $_GET method:
<form name="form" action="" method="get">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_GET['subject']; ?>
Using $_POST method:
<form name="form" action="" method="post">
<input type="text" name="subject" id="subject" value="Car Loan">
</form>
To show the value:
<?php echo $_POST['subject']; ?>
reference
Here is an example of passing data through URL within a site
<a href='page2.php?id=2489&user=tom'>link to page2</a>
reference 2, Passing variables with data between pages using URL
when I use this code nothing and call the ajax nothing happens and I was looking at some online forums saying I need to use json encode to pass variables over ajax but it just echos it at the top of the webpage.
AjaxTesting
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#test").click(function(){
$.ajax({
event.preventDefault(),
url:'ajaxUser.php',
type:'POST',
dataType: 'json',
success:function(data){
alert(data.id);
}
)};
});
</script>
</head>
<body>
<form method="post">
<input name="userName">
<input name="submit" type="button" value="Submit" id="test">
</form>
</body>
</html>
ajaxUser
<?php
echo json_encode(array('id' => 123, 'messageid' => "test"));
?>
You don't have event parameter called in click function. Don't call preventDefault() within ajax function ,also you need to code your js within document.ready() if you want to write in header element !!
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form method="post">
<input name="userName">
<input name="submit" type="button" value="Submit" id="test">
</form>
<script>
$("#test").click(function(event){
event.preventDefault();
$.ajax({
url:'ajaxUser.php',
type:'POST',
dataType: 'json',
success:function(data){
alert(data.id);
}
});
});
</script>
</body>
</html>
Should work
The php code needs to be in a different file named AjaxTesting.php and you never call the function post() in the javascript. So we can call it inside a form submit event handler
Try adding:
$(function(){
$('form').submit(function(event){
event.preventDefault()
post();
})
});
Also note that the html page needs to be running on the same server and not from local file for ajax to work
i have a form which i am trying to send values through ajax. But i receive following error:
Uncaught TypeError: Illegal invocation
I am stuck and can't find where am i wrong. Any suggestions please?
Ajax
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" </script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit_custom").click(function() {
e.preventDefault();
var postData = new FormData();
postData.append('file[]', $('input[type=file]')[0].files[0]); // after this line
postData.append('trxid', $('input[name=trxid]'));
postData.append('orderid', $('input[name=orderid]'));
postData.append('custid', $('input[name=custid]'));
if(proceed)
$.post('upload.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}else{
output = '<div class="success">'+response.text+'</div>';
$("#upload_form").slideUp(); //hide form after success
}
$("#upload_form").hide().html(output).slideDown();
}, 'json');
});
});
});
</script>
</head>
<body>
<h2>Hello <?php echo $user ?> </h2> <p> "You have successfully done purchasing process.</p>
<div id="upload_form">
<p>To send your size details for your order please upload the following file:</p>
<p>Download custom size form Provide us your custom size: File.pdf</p>
<form enctype="multipart/form-data" action="" method="post">
<input type="text" name="trxid" value="<?=$trx?>">
<input type="text" name="orderid" value="<?=$orderid?>">
<input type="text" name="custid" value="<?=$customerid?>">
<input type="file" name="file">
<input type="submit" id="submit_custom">
</form>
</div>
</body>
</html>
You are getting Illegal invocation because jQuery can't serialize the postData object for $.post.
I think you need to add .val().
postData.append('file[]', $('input[type=file]')[0].files[0].val()); // after this line
postData.append('trxid', $('input[name=trxid]').val());
postData.append('orderid', $('input[name=orderid]').val());
postData.append('custid', $('input[name=custid]').val());
I've been reluctant to open a question, but after fighting this for 6+ hours I'm now cross-eyed.
I've got some experience with PHP and HTML but Ajax and jQuery is new to me (I first heard about it yesterday).
I want the page to display the submitted values inside the div class="result" without refreshing. Anyway, the workflow:
j.php loads > user fills out two text fields (phone and gz) > click Submit button > jpost.php is called and echos variables > PHP variables need to display is div class=result on j.php
j.php =
<html>
<head>
<script src="//code.jquery.com/jquery-latest.js"></script> <!-- load jquery via CDN -->
<script>
$(document).ready(function() {//start document ready
$('#submit-button').click(function (){
$.ajax({
type: 'POST',
url: 'jpost.php',
data: $("#cdr").serialize(),
success: function(d){
$(".result").html(d);
}
});
});
});//end document ready
</script>
</head>
<body>
<div id="cdr">
<div>
<input type="text" id="phone" name="phone" value="" placeholder="phone" size="40" />
</div>
<div>
<input type="text" id="gz" name="gz" value="" placeholder="gz" size="40" />
</div>
<div>
<button id="submit-button">Submit</button>
</div>
</div>
<div class="result"></div>
</body>
</html>
jpost.php
<?php
$phone = $_POST['phone'];
$gz = $_POST['gz'];
echo $phone;
echo $gz;
print_r($_POST);
echo "grrrr"
?>
So all I want is $gz and $phone to echo out in my result div on j.php, but all that shows up is:
Array ( ) grrrr
This makes me believe that my variables are being lost somewhere :P or I'm echoing them incorrectly.
Thanks so much for any help!
Short
The problem was :
1.You need a form in order to serialise the data ( and not a div ) 2. You need to prevent the default behaviour of the event
Long
In order to serialise the data, you need to have a form. i created the form with id #cdr-form
Also, you need to make sure to prevent the default behaviour of the button ( event ) with e.preventDefault() . Read more about it here
<html>
<head>
<script src="//code.jquery.com/jquery-latest.js"></script> <!-- load jquery via CDN -->
<script>
$(document).ready(function() {//start document ready
$('#submit-button').click(function (e){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'http://localhost/~metaly/tests/j.php',
data: $("#cdr-form").serialize(),
success: function(d){
$(".result").html(d);
}
});
});
});//end document ready
</script>
</head>
<body>
<div id="cdr">
<form id="cdr-form">
<div>
<input type="text" id="phone" name="phone" value="" placeholder="phone" size="40" />
</div>
<div>
<input type="text" id="gz" name="gz" value="" placeholder="gz" size="40" />
</div>
<div>
<button id="submit-button">Submit</button>
</div>
</form>
</div>
<div class="result"></div>
</body>
</html>
HTML CODE
<form action="send.php" method="post">
<input type="hidden" name="qty" id="quantity" value="">
<input type="submit" id="submit">
</form>
JAVASCRIPT CODE
var qty=10;
$("#submit").click(function(){
$("#quantity").val(qty);
});
PHP FILE (send.php)
<?php
$showqty=$_POST['qty'];
echo $showqty;
?>
My code above is receiving an error on the php file. It says that the index qty is undefined. How can I send an integer value of a variable from javascript to php?
You do not have any issues with you javascript or you PHP code.
when you recieve undefined error, it means that the object is not even posted to the send.php file. so the problem is with the object or the way you are sending it, not with the value in it.
with a look at you code I saw that you have two action tags and no method tag and that is what causing the error.
with no method tag, the form uses GET method instead of POST method.
so you just have to change this line:
<form action="send.php" action="post">
with this line:
<form action="send.php" method="post">
simply use
var qty = document.getElementById("qty").value
action="post"> should be method="post">
This may help you:
<!doctype html>
<html lang="en">
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">
$(document).ready(function(e) {
var qty=10;
$("#submit").click(function(e){
var qty=10;
$.ajax({
url:'send.php',
type:'POST',
data:{'qty':qty},
success: function(e){
alert(e);
//do some thing
}
});
});
});
</script>
</head>
<body>
<form id="myform" action="send.php" method="post" onSubmit="return false;">
<input type="submit" id="submit">
</form>
</body>
</html>
send.php
<?php
$showqty=$_POST['qty'];
echo $showqty;
?>