Sending data to server with $.ajax request - javascript

I have a simple form with 2 input:
<form name="contact" id="contact">
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
On submit I want using jQuery ajax method to send data to print.php. Code looks next:
var contact=$("#contact");
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
I want that Print.php script simply prints sent data, but nothing is happening. Script looks next:
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
echo $fname;
?>
Problem is obviusly in print.php.

you need to use following.
$("form").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST",
url: "print.php",
dataType: "json",
data: {
fname: firstName,
lname: lastName
},
success: functon(dt) {
alert(dt);
}
});
});

There is no $subject variable anywhere.
You set the first name and last name variables properly.
To check your script's response (which will be an error), go to your console and check network, and then repsonse data.
Change $subject to $fname and it should "work"
Also add on .on() submit event handler to your jQuery AJAX call like so:
$('form').on('submit', function() {
//ajax call
});
Edit:
You made an edit and changed $subject to $name. There is no $name variable either.

You do not need the JSON type on the ajax form. And include the preventDefault to avoid natural action(page refreshes when submitting)
contact.on("submit",function(event){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
event.preventDefault();
$.ajax({
type:"POST",
url:"print.php",
data:{
fname:firstName,
lname:lastName
}
});
});

It looks like your problem is that your HTML form doesn't know where to go ounce the submit happens and that is why nothing is happening. You need to tell your HTML form to run javascript.
You could link your HTML form to your javascript by using JQuery's .submit() method document here http://api.jquery.com/submit/
This will trigger your javascript to run once it is submitted if you wrap all your javascript around it.
$("form").submit(function( event ) {
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
});
Also you could give your HTML form an action so it knows what to do when the form is submitted.
Below we are saying run myFunction() when this form is submitted, we will then need to wrap all your javascript in myFunction().
<form name="contact" action=“javascript:myFunction();”>
<input type="text" id="firstName" name="firstName"/>
<input type="text" id="lastName" name="lastName"/>
<input type="submit" value="Send"/>
</form>
Your javascript will look like this
function myFunction(){
var firstName=$("#firstName").val();
var lastName=$("#firstName").val();
$.ajax({
type:"POST",
url:"print.php",
dataType:"json",
data:{
fname:firstName,
lname:lastName
}
});
}
Once you get that far you will want to fix your php. The way you have it now $name is empty and won't print anything. You will want to fill the variable in before you echo it out. I am assuming you want $name to contain a concatenated version of $fname and $lname.
<?php
$fname = $_POST['fname'];
$lname=$_POST['lname'];
$name = $fname . ' ' . $lname;
echo $name;
?>
That should work for you.

Related

PHP - How to avoid reload a form when change route

I have this simple form in index.php:
<div class="form-container">
<form id="create-form" action="create.php" method="POST">
<label for="name">Name:</label>
<input type="text" id="name" name="name">
<br/>
<label for="score">Amount:</label>
<input type="number" id="score" name="score">
<br/>
<input type="submit" name="addBtn" id="addBtn" value="Add" />
</form>
</div>
What create.php contains:
<?php
include 'db.php';
$name = $_POST["name"];
$score = $_POST["score"];
$sql = "insert into demo_table (name, score) values ('$name', '$score')";
$conn->query($sql);
$conn->close();
header("location: index.php");
?>
Currently, I have this script in index.js using JQuery and AJAX but keeps reloading the page because of the index.php call.
$(document).ready(function () {
$('#create-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'create.php',
data: $(this).serialize(),
success: function(response)
{
console.log('agregado');
location.href = 'index.php';
}
});
});
});
Currently this works well, but reloads the page when clicking on the button and when reload the data (last line in create.php). What I am trying to do is to implement AJAX and/or JQuery in order to avoid this and have a complete Single Page Application.
Disclaimer: I am starting learning PHP. So, I am making any mistake, please let me know first of all. I will be attentive to your answers.
Try to make in comment the code location.href = 'index.php'; inside the success method.
Like that :
$(document).ready(function () {
$('#create-form').submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'create.php',
data: $(this).serialize(),
success: function(response)
{
console.log('agregado');
// location.href = 'index.php';
}
});
});
});

Send php response to ajax and display result in div

I have made a simple form through which i can search the keywords and find the related output from database dynamically. The code works perfect without AJAX . But now i have applied some AJAX code to get the response on same page within a div named coupon. I am unable to get the response. I don't know where am i doing wrong. Any suggestions please. Here is the complete code.
form
<form action="" id="search_form" method="POST">
<p><input name="query" autocomplete="off" id="list_search" type="search" required class="list_search" /></p>
<p align="center"><input type="submit" id="click" name="click" class="but" value=" search" /></p>
</form>
<div class="coupons"></div>
AJAX
$("document").ready(function(){
// $(".but").click(function(event){ // here
$("#search_form").submit(function (event) {
{
event.preventDefault();
var myData={ query: $( 'input[name="query"]' ).val() };
$.ajax({
url: 'result.php',
data: myData,
type: 'post',
dataType: "html",
success: function(result){
//console.log(result);
$('.coupons').html(result);
},
error: function() {
alert('Not OKay');
}
});
});
});
result.php
$keyword = mysqli_real_escape_string($con,$_REQUEST['query']); // always escape
$keys = explode(" ", $keyword);
$sql="SELECT c.* , sc.* , sm.* ,ca.* from store_category sc INNER JOIN store_manufacture sm ON sm.sm_id=sc.store_id INNER JOIN categories ca ON ca.cat_id=sc.cat_id INNER JOIN coupons c on c.c_sc_id=sc.sc_id WHERE c.c_name LIKE '%$keyword%' OR sm.sm_brand_name LIKE '%$keyword%' OR ca.cat_name LIKE '%$keyword%' OR c.c_description LIKE '%$keyword%'";
foreach ($keys as $k) {
$sql.="OR c.c_name LIKE '%$k%' OR sm.sm_brand_name LIKE '%$k%' OR ca.cat_name LIKE '%$k%' OR c.c_description LIKE '%$k%'";
}
$result = mysqli_query($con, $sql);
$count=mysqli_num_rows($result);
if($count!=0) {
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$res=$row['c_name'].$row['c_description'];
echo json_encode($res);
}
}
else
{
echo "no result";
}
Do not use a click event and a button does not have a submit event - use the form's submit event instead
$("#search_form").on("submit",function(e) {
e.preventDefault();
$.post("result.php?query="+encodeURIComponent($("#list_search").val()),function(data) {
$('.coupons').html(data); // you likely need to render the JSON instead here or send HTML from server
});
});
You should try with:
var myData={ query: $( 'input[name="query"]' ).val() };
So you can get back a query field on the server.
The Problem is your ajax request does have your value as key in $_REQUEST. There might be some way to handle this but it is not very intuitive.
And right you should register the submit handler on your form not your button.
$("#search_form").submit(function(event){ ... }

how to make submit button both send form thru' PHP -> MySQL and execute javascript?

I'm having an issue. When I hit submit, my form values are sent to the database. However, I would like the form to both send the value to the database and execute my script, as said in the title.
When I hit submit button, the form is sent to the database and the script remains ignored. However, if I input empty values into the input areas, the javascript is executed, and does what I want (which is to show a hidden < div >), but it's useless since the < div > is empty, as there is no output from the server.
What I want is:
submit button -> submit form -> javascript is executed > div shows up > inside div database SELECT FROM values (which are the ones added through the submitting of the form) appear.
Is this possible? I mean, to mix both PHP and JavaScript like this?
Thanks in advance.
By two ways, You can fix it easily.
By ajax--Submit your form and get response
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //action
data: form.serialize(), //your data that is summited
success: function (html) {
// show the div by script show response form html
}
});
});
First submit your from at action. at this page you can execute your script code .. At action file,
<?php
if(isset($_POST['name']))
{
// save data form and get response as you want.
?>
<script type='text/javascript'>
//div show script code here
</script>
<?php
}
?>
hers is the sample as I Comment above.
In javascript function you can do like this
$.post( '<?php echo get_site_url(); ?>/ajax-script/', {pickup:pickup,dropoff:dropoff,km:km}, function (data) {
$('#fare').html(data.fare);
//alert(data.fare);
fares = data.fare;
cityy = data.city;
actual_distances = data.actual_distance;
}, "json");
in this ajax call I am sending some parameters to the ajaxscript page, and on ajaxscript page, I called a web service and gets the response like this
$jsonData = file_get_contents("https://some_URL&pickup_area=$pickup_area&drop_area=$drop_area&distance=$km");
echo $jsonData;
this echo $jsonData send back the data to previous page.
and on previous page, You can see I Use data. to get the resposne.
Hope this helps !!
You need ajax! Something like this.
HTML
<form method='POST' action='foobar.php' id='myform'>
<input type='text' name='fname'>
<input type='text' name='lname'>
<input type='submit' name='btnSubmit'>
</form>
<div id='append'>
</div>
jQuery
var $myform = $('#myform'),
$thisDiv = $('#append');
$myform.on('submit', function(e){
e.preventDefault(); // prevent form from submitting
var $DATA = new FormData(this);
$.ajax({
type: 'POST',
url: this.attr('action'),
data: $DATA,
cache: false,
success: function(data){
$thisDiv.empty();
$thisDiv.append(data);
}
});
});
And in your foobar.php
<?php
$fname = $_POST['fname'];
$lname = $_POST['lname'];
$query = "SELECT * FROM people WHERE fname='$fname' AND lname = '$lname' ";
$exec = $con->query($query);
...
while($row = mysqli_fetch_array($query){
echo $row['fname'] . " " . $row['lname'];
}
?>
That's it! Hope it helps
You can use jQuery ajax to accomplish it.
$('form').submit(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: url, //url where the form is to be submitted
data: data, //your data that is summited
success: function () {
// show the div
}
});
});
Yes, you can mix both PHP and JavaScript. I am giving you a rough solution here.
<?php
if(try to catch submit button's post value here, to see form is submitted)
{
?>
<script>
//do javascript tasks here
</script>
<?php
//do php tasks here
}
?>
Yes, This is probably the biggest use of ajax. I would use jquery $.post
$("#myForm").submit(function(e){
e.preventDefault();
var val_1 = $("#val_1").val();
var val_2 = $("#val_2").val();
var val_3 = $("#val_3").val();
var val_4 = $("#val_4").val();
$.post("mydbInsertCode.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// Form values are now available in php $_POST array in mydbInsertCode.php - put echo 'success'; after your php sql insert function in mydbInsertCode.php';
if(response=='success'){
myCheckdbFunction(val_1,val_2,val_3,val_4);
}
});
});
function myCheckdbFunction(val_1,val_2,val_3,val_4){
$.post("mydbCheckUpdated.php", {val_1:val_1, val_2:val_2, val_3: val_3, val_4:val_4}, function(response){
// put echo $val; from db SELECT in mydbSelectCode.php at end of file ';
if(response==true){
$('#myDiv').append(response);
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>

How to post data without a form

Good day sir/ma'am I am a new programmer, I would like to ask how to post data like the functionality of form that when submitting the form the URL in action will display using javascript.
"WITHOUT USING A FORM" or using xmlHTTP that not return to main page
sample is
HTML
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
JS
function revisetask(idtask)
{
//In this function sir i would like to post here
}
Im very sorry if my english is too bad.. thanks in advance :D
You can use javascript for submitting the values of input boxes,
to do so,
write a javascript function which will read all your input boxes values into javascript variables,
Prepare a URL, and call that URL using window.location.href
function SubmitMyForm
{
var Firstname = document.getElementbyId('FirstName').value;
var Lastname = document.getElementbyId('LastName').value;
var URL="myDBoperations.php?firstname="+Firstname+"&lastname="+Lastname;
window.location.href= URL;
}
On the operations form you will receive these value in GET.
Hope this will help you.
U can use ajax for this. U don't need a form for ajax post, and it won't refresh the page too.
Below is an example code
<input type="text" id="test_name" />
<input type="button" value="Submit" obclick="save_this()" />
<script type="text/javascript">
function save_this(){
var text = $('#test_name');//stores te value in text field
$.ajax({
url: 'http://example.com/test.php',//your URL
type: 'POST',
data: { text: text },
success: function(data){
alert(data);
}
});
}
</script>
test.php
<?php
echo $_POST['text'];
As I've seen in this code:
<input type="button" value="revise" onclick="revisetask(<?php echo $id; ?>)">
I assume and believe that the reason why you don't want to use form because you want your $id to be submitted through javascript/jquery. But alternatively, you could just do it this way:
HTML:
<form method = "POST" action = "updatetask.php">
<input type = "hidden" value = "<?php echo $id; ?>" name = "taskid" id = "taskid"/>
<input type = "submit" value = "UPDATE" name = "updatebutton">
</form>
PHP:
<?php
$taskid = $_POST['taskid'];
?>
In the above code I just set the type hidden and which contains the value of your $id in which would be post in your Php file.
UPDATE:
If it still doesn't fit to what you want then you could just have this other alternative which will be using the GET method: <a href = "updatetask.php?id='<?php echo $id; ?>' REVISE </a>"
That's the only option you have. and if you don't want to show the id in your url then you could just use URL Rewriting (refer to this link: https://www.addedbytes.com/articles/for-beginners/url-rewriting-for-beginners/)
Hope this helps.

Sending e-mail form using PHP and AJAX

I have contact form on my site. It sends message to email. I try to do it without page reload using AJAX, but it seems that AJAX doesn't work: messages are sent but the page still redirecting to call-form.php. What is incorrect in my code? (jQuery is included)
HTML
<form name="freeCall" action="<?php bloginfo(template_url); ?>/mail/call-form.php" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
</form>
PHP - call-form.php
<?
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
}
?>
JS
$(function () {
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
});
Ok, first when you make an AJAX call, you must have a way to know if your PHP returns you something (useful for debugging).
Then, when submitting a form with AJAX, the tag action="" is not needed.
Finally, to prevent a form from being sent when making an AJAX call, add e.preventDefault() with the event called e here, like in my example.
I have improved your code to be more realistic about the latest standards.
HTML :
<form name="freeCall" method="post" class="popover-form" id="free-call-form">
<label for="name1">Name</label><span class="pull-right close">×</span><input placeholder="Name" name="call-name" type="text" id="name1" >
<label for="phone">Phonenumber</label><input name="phone" type="text" value="" placeholder="+375" id="phone" >
<input type="submit" value="Call me back" >
JS :
$(function () {
$("#free-call-form").submit(function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
dataType: "json", // Add datatype
data: form_data
}).done(function (data) {
console.log(data);
alert("It's OK!");
}).fail(function (data) {
console.log(data);
});
});
});
And PHP :
if((isset($_POST['call-name']))&&(isset($_POST['phone'])&&$_POST['phone']!="")){
$to = 'test#gmail.com';
$subject = 'Callback';
$message = '
<html>
<head>
<title>Call me back</title>
</head>
<body>
<p><b>Name:</b> '.$_POST['call-name'].'</p>
<p><b>Phonenum:</b> '.$_POST['phone'].'</p>
</body>
</html>';
$headers = "Content-type: text/html; charset=utf-8 \r\n";
$headers .= "From: Site <info#mail.com>\r\n";
mail($to, $subject, $message, $headers);
echo json_encode(array('status' => 'success'));
} else {
echo json_encode(array('status' => 'error'));
}
With echo json_encode, you know what is the return of your AJAX call. It is better
You're not preventing the default submit action -
$("#free-call-form").submit(function (event) { // capture the event
event.preventDefault(); // prevent the event's default action
Returning false or preventing the default behavior of the event should work for you.
Example with old .submit(), that now is an alias of .on('eventName'); and using return false to avoid form submission.;
$("#free-call-form").submit(function () {
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
return false;
});
Example using .on('eventName') and using e.preventDefault() to avoid form submission.
$("#free-call-form").on('submit', function (e) {
e.preventDefault();
var form_data = $(this).serialize();
$.ajax({
type: "POST",
url: "call-form.php",
data: form_data,
success: function () {
alert("It's OK!");
}
});
});
From Jquery .submit() Documentation: This method is a shortcut for
.on( "submit", handler ) in the first variation, > and .trigger(
"submit" ) in the third.
Also, you would consider not using EVER the user input directly, it would not cause problems in this exact context (or maybe yes) but with your actual approach they can change the mail markup or adding some weirds things there, even scripts, you would consider escape, validate or limit it.
Also as zLen pointed out in the comments:
the action in the form markup is not necessary because you are not using it, you can remove it:
action="<?php bloginfo(template_url); ?>/mail/call-form.php"
What is happening is your form is being submitted, it's not actually the AJAX call which is doing it. To fix it, add
return false;
at the end of the submit function so that the browser doesn't submit the form and the AJAX call happens properly.

Categories

Resources