multiple forms on page onclick ajax function not working - php

I have an ajax search function that produces a list of names from database. Each name is echoed back as a form button so when user clicks on the name another ajax call will bring up all info related to that name. However, it is not working. I have tried several variations of the ajax function below but either nothing happens at all or the page just gets refreshed with no results.
Any ideas on how to get this to work?
This is the latest ajax (which does nothing)
$(function GetInfo() {
$('form').on('click', function (e) {
var tourName = $('#tourName').val();
var FirstName = $('#FirstName').val();
var LastName = $('#LastName').val();
alert("PLEASE ENTER A NAME" + FirstName + LastName);
$.ajax({
type: "POST",
url: 'process.php',
data: "tourName=" + tourName + "&firstname=" + firstname + "&lastname=" + lastname,
success: function(data){
$("#search_results").html(data);
}
});
e.preventDefault();
});
});
And this is the php loop that produces the forms (names):
$string = '';
if (mysql_num_rows($query)){
while($row = mysql_fetch_assoc($query)){
$FirstName = $row['FirstName'];
$LastName = $row['LastName'];
$Name = $row['FirstName']." ".$row['LastName'];
$string .= "<form method='post' action=''>
<input type='hidden' name='FirstName' value='$FirstName'>
<input type='hidden' name='LastName' value='$LastName'>
<input type='button' class='button' name='person_name' value='$Name' onClick='GetInfo()'></form><br /><br />\n";
}
}else{
$string = "No matches found!";
}
mysql_close($con);
echo $string;
Just incase anyone has the same issue, I got the following code to work:
function GetInfo(form) {
var person_name = form.person_name.value;
var tourName = form.tourName.value;
var firstname = form.FName.value;
var lastname = form.LName.value;
$.ajax({
type: "POST",
url: "process.php",
data: "person_name=" + person_name + "&tourName=" + tourName + "&firstname=" + firstname + "&lastname=" + lastname,
success: function(data){
$("#search_results").html(data);
}
});
return false;
}
And in the form
$string .= "<form method='post' id='$form'>
<input type='hidden' name='tourName' value='$tourneyName'>
<input type='hidden' name='FName' value='$FirstName'>
<input type='hidden' name='LName' value='$LastName'>
<input type='button' class='button' name='person_name' value='$Name' onClick='GetInfo (this.form)'></form><br /><br />\n";
}
}else{
$string = "No matches found!";
}

You should add an ID to you form and target instead of using $('form') use $('#yourformid')

Use this:
$(function GetInfo(el) {
var tourName = $('#tourName').val();
var FirstName = $(el).siblings('[name=FirstName]').val();
var LastName = $(el).siblings('[name=LasstName]').val();
alert("PLEASE ENTER A NAME" + FirstName + LastName);
$.ajax({
type: "POST",
url: 'process.php',
data: { tourName: tourName, firstname: FirstName, lastname: LastName },
success: function(data){
$("#search_results").html(data);
}
});
e.preventDefault();
});
And you need to change the HTML to use:
onclick='GetInfo(this)'

The solution is posted above. It seems rather simple now that it's done.

$('#send_email').click(function() {
$.ajax({
type : 'POST',
url : '<?php echo base_url()?>contact',
data : $( '#contact_form' ).serialize(),
success : function(msg){
$('#results').html(msg);
if(msg == "Successfully Subscribed"){
$( "#email_news" ).val('');
}
}
});
return false;
});

Related

how to insert data with ajax and php without page refresh

I real need your help since I'm a beginner in php and Ajax. My problem is that, I can not send data in the database via my appended form in post.php, also when the button of id #reply clicked it sends empty data to database by refreshing the page. When the reply link is pressed I only get the Result of reply link to be shown without other information (name and comment). I need your help to make my appanded form to be able to add/send data to the database without refreshing the page, I also need to disable the form from index.php to make replies when the reply button / link is pressed. Thank you.
post.php
<?php include("config.php"); //inserting
$action=$_POST["action"];
if($action=="addcomment"){
$author = $_POST['name'];
$comment_body = $_POST['comment_body'];
$parent_id = $_POST['parent_id'];
$q = "INSERT INTO nested (author, comment, parent_id) VALUES ('$author', '$comment_body', $parent_id)";
$r = mysqli_query($conn, $q);
if(mysqli_affected_rows($conn)==1) { header("location:index.php");}
else { }
}
// showing data
error_reporting( ~E_NOTICE );
function getComments($conn, $row) {
$action=$_POST["action"];
if($action=="showcomment"){ $id = $row['id'];
echo "<li class='comment'><div class='aut'>".$row['author']."</div><div class='comment-body'>".$row['comment']."</div>";
echo "<a href='#comment_fo' class='reply' id='".$row['id']."'>Reply</a>";
$result = mysqli_query($conn, "SELECT * FROM `nested` WHERE parent_id = '$id' ORDER BY `id` DESC");
}
if(mysqli_num_rows($result)>0) { echo "<ul>";
while($row = mysqli_fetch_assoc($result)) { getComments($conn,$row); }
echo "</ul>"; } echo "</li>";
}
if($action=="showcomment"){
$q = "SELECT * FROM nested WHERE parent_id = '".$row['id']."' ORDER BY `id` DESC";
$r = mysqli_query($conn, $q);
while($row = mysqli_fetch_assoc($r)){ getComments($conn,$row); }
}
?>
<!DOCTYPE HTML><head><script type='text/javascript'>
$(document).ready(function(){
$("a.reply").one("click", function() {
var id = $(this).attr("id");
var parent = $(this).parent();
$("#parent_id").attr("value", id);
parent.append(" <br /><div id='form'><form><input type='text' name='name' id='name'><textarea name='comment_body' id='comment_body'></textarea><input type='hidden' name='parent_id' id='parent_id' value='0'><button id='reply'>Reply</button></form></div>");
$("#reply").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){ showComment(); }
});
});
});
});
</script></head></html>
//index.php
<html><head><script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function showComment(){
$.ajax({
type:"post",
url:"post.php",
data:"action=showcomment",
success:function(data){ $("#comment").html(data); }
});
}
showComment();
$(document).ready(function(){
$("#button").click(function(){
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
</script></head><body>
<form id="form_comment">
<input type="text" name="name" id='name'/>
<textarea name="comment_body" id='comment_body'></textarea>
<input type='hidden' name='parent_id' id='parent_id' value='0'/>
<input type="button" id="button" value="Comment"/>
</form>
<div id="comment"></div> </body></html>
$(document).ready(function(){
$("#button").click(function(e){
e.preventDefault(); //add this line to prevent reload
var name=$("#name").val();
var comment_body=$("#comment_body").val();
var parent_id=$("#parent_id").val();
$.ajax({
type:"post",
url:"post.php",
data:"name="+name+"&comment_body="+comment_body+"&parent_id="+parent_id+"&action=addcomment",
success:function(data){
showComment();
}
});
});
});
Here is a simple incomplete ajax example.
FromPage.php
Here is the ajax that I'd use. The variables can be set however you like.
<script type="text/javascript">
var cars = ["Saab", "Volvo", "BMW"];
var name = "John Smith";
$.ajax({
url: 'toDB.php',
type: 'post',
dataType: 'html',
data: {
carArray: cars,
firstName: name
},
success: function(data) {
console.log(data); //Testing
}
});
</script>
toDB.ph
This is the second page - the one that writes the values to the database etc.
<?php
$cars = $_POST['carArray'];
$FirstName=$_POST['firstName'];
//Used to test - it will print out the array
print("<pre>");
print_r($cars);
print("</pre>");
//Do something with $cars array and $FirstName variable
?>

ajax call returns only last id

I am trying to develop an add to cart function via ajax, the problem is that no matter which product I add to cart, it adds the last item on the list and then increments the same product upon clicking on any other product. Here is my code:-
<?php
$i = 1;
while($row = mysqli_fetch_array($run_products)){
$op_id = $row['option_id'];
echo "<tr>";
echo "<td>" . $i . "</td>";
echo "<td>" . $row['option_desc'] . "</td>";
echo "<td>
<form action='' method='post' class='p_form'>
<input type='text' name='product_id' value='$op_id' pid='$op_id'>
<input type='text' name='quantity' value='1' pid='$op_id'>
<input class='btn btn-primary add' type='submit' name='add_to_cart' value='Add to Cart' id='product' pid='$op_id'>
</form>
</td>";
echo "</tr>";
$i++;
}
?>
Here is jquery:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.p_form',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
//data: {id:id},
data:$('.p_form').serialize(),
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Here is action.php, the $product_id always returns as 4 (for example) if the last id in the last is 4
if (!empty($_POST)){
$product_id = $_POST['product_id'];
echo $product_id;
}
Need to do it like below:-
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {//instead of form click add event on form button click
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data:element.parent('.p_form').serialize(), //serialize clicked button parent form
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
Trigger click event on button click not on the form click:
This will work for you for each product.
<script type="text/javascript">
$(document).ready(function(){
$(document).on('click','.add',function (event) {
event.preventDefault();
var element = $(this);
var id = element.attr("pid");
//alert(id);
$.ajax({
url: 'action.php',
method: 'post',
data: {id:id}, //send id of product you wish to add
success: function(data){
$('#message').html(data);
}
});
return false;
});
});
</script>
And on server side:
if (!empty($_POST)){
$product_id = $_POST['id'];//get only that id posted in ajax call
echo $product_id;
}

How to get and pass data from html to php using ajax

Hi I would love to know how can I pass the strings from a form to a php that will test if there is something in it and then post an alert message using this form to try and get data from it and then show if it was passed correctly.
HTML code:
<form action='' method=''>
Name:<input type='text' name='name' id='name'>
Age:<input type='text' name='age' id='age'>
message:<textarea name='message' id='message'></textarea>
<input type='submit' value='Send'>
</form>
Output:
<?php
if(isset($_POST['name']) && isset($_POST['age']) && isset($_POST['message'])){
$a = $_POST['name'];
$b = $_POST['age'];
$c = $_POST['message'];
if($a != NULL && $b != NULL && $c != NULL)
{
echo "
<script type='text/javascript'>
window.alert('Success'+ a + b + c)
</script>
";
}
};?>
While still in the same page from before but shows what I have typed in there into the alert box.
I would also appreciate if it comes with instruction on how to use it with get and post functions and also with links if it can be done?
For an easy way you can Make following changes to your code:
HTML:
<form action='' method='' id="myform">
Name:<input type='text' name='name' id='name'>
Age:<input type='text' name='age' id='age'>
message:<textarea name='message' id='message'></textarea>
<input type='submit' value='Send'>
</form>
PHP:
(your_page_with_php_script)
<?php
if(isset($_POST['name']) && isset($_POST['age']) && isset($_POST['message'])){
$a = $_POST['name'];
$b = $_POST['age'];
$c = $_POST['message'];
if($a != NULL && $b != NULL && $c != NULL)
{
echo "Success ".a." ".b." ".c;
}
};
?>
Script: (Include jquery first)
$('#myform').submit(function(){
var name = $('#name').val();
var age = $('#age').val();
var message = $('#message').val();
$.ajax({
type: "POST",
url: "your_page_with_php_script.php",
data: "name="+name+"&age="+age+"&message="+message,
}).done(function( msg ) {
alert( "Data Saved: " + msg );
});
});
edit the following according to the need:
$.ajax({
type: 'POST',
url: 'your_php_page.php',
data: { postVar1: 'theValue1', postVar2: 'theValue2' },
beforeSend:function(){
// this is where we append a loading image
$('#ajax-panel').html('<div class="loading"><img src="/images/loading.gif" alt="Loading..." /></div>');
},
success:function(data){
// successful request; do something with the data
$('#ajax-panel').empty();
$(data).find('item').each(function(i){
$('#ajax-panel').append('<h4>' + $(this).find('title').text() + '</h4><p>' + $(this).find('link').text() + '</p>');
});
},
error:function(){
// failed request; give feedback to user
$('#ajax-panel').html('<p class="error"><strong>Oops!</strong> Try that again in a few moments.</p>');
}
});
The requesting page should have a div with id="ajax-panel"
You must use Jquery with Ajax...
<script>
$("#submit").click(function()
{
var name = $('#name').value();
var age= $('#age').value();
var message= $('#message').value();
$.ajax({
url: "urpage.php",
data: {name : name, age : age, message : message},
type: "POST",
success: function(output) {
alert(output); //This will show ur output in an alert box
} }
})
});
</script>
Hope this works

How to get value on multiple textbox with jquery?

I have form like this:
<input type='text' name='people' id='namepeople'>
<input type='hidden' name='idpeople' id='idpeople'>
<input type='text' name='address' id='address' disabled>
<input type='text' name='age' id='age' disabled>
<input type='text' name='status' id='status' disabled>
and a jQuery script:
$("#namepeople").keyup(function()
{
var namepeople= $(this).val();
var name= namepeople;
$.ajax({
type: "POST",
url: "check.php",
data: "namepeople=" + name,
dataType: "json",
success: function(data)
{
$("#idpeople").val(data[0]);
$("#address").val(data[1]);
$("#age").val(data[2]);
$("#status").val(data[3]);
}
});//ajax
});//keyup
And php code :
<?
mysql_connect("localhost","root","");
mysql_select_db("dbajax");
$name = $_POST["namepeople"];
$sql = mysql_query("select * from anggota where upper(username) like '%$name'");
$row = mysql_fetch_array($sql);
$kt=mysql_num_rows($sql);
if($kt > 0)
{
$idnya=$row["id_anggota"];
$address=$row["address"];
$age=$row["age"];
$status=$row["status"];
}
else
{
$idnya="";
$address="";
$age="";
$status="";
}
echo "$idnya|$address|$age|$status";
?>
This is working out just for value of idpeople, but the other value are not coming out. How to get value on multiple textbox with jQuery?
You should modify your ajax call to send the entire form, because right now it only sends idpeople. You should use $('#myForm').serialize() as shown below, where myForm is the id of your form element. Then, within php you can access all your data with $_POST like $_POST['people'] for example. BUT, if you have your inputs disabled like in your example, they will not be sent to your PHP.
$.ajax({
type: "POST",
url: "check.php",
data: $('#myForm').serialize(),
dataType: "json",
success: function(data)
{
$("#idpeople").val(data[0]);
$("#address").val(data[1]);
$("#age").val(data[2]);
$("#status").val(data[3]);
}
You also need to change your php to return JSON. change the last line of your php to this:
echo json_encode(array($idnya,$address,$age,$status));
Your issue is on the return echo I believe. do the following:.
$res = array($idnya,$address,$age,$status);
$json = json_encode($res);
echo $json;
exit();
And you should be good

Values from javascript to PHP

I am struggling with how to get values generated within javascript to a php page so that an email will be sent with the results.
function sendmemail(){
var data = 'result=' + result.val();
$.ajax({
url: "process.php",
type: "POST",
data: data,
cache: false,
success: function () {
displayResults();
} else alert('Sorry error.');
});
}
That else part is a syntax error, you can't add an else clause in that way.
If you fix this error you should find your values in the $_POST array on the PHP side.
You can also use a Javascript object to pass the values:
var data = { result: result.val() }
which is more readable.
process.php...
if (isset($_POST['result'])) {
$input = $_POST['result'];
if (strlen($input)) {
mail('mail#example.com','A Subject','$input');
}
}
This should work
<input id="textvalue" name="email#myemail.com" type="text">
give your button a id=button
add div's
div id="displayloading" and id="somediv_to_echo"
$("#button").click(function() {
$('#displayloading').fadeIn('slow', function() {
my_value = $("#textvalue").val().replace(/ /g,"+");
$("#somediv_to_echo").load("mail_send.php?d=" + my_value + "&md=" + new Date().getTime());
$("#textvalue").val("");
});
});
Lets do it form the begining.
HTML:
<form id="frm">
<input type="text" name="email" value="sample#sample.com"/>
<input type="text" name="name" value="Name"/>
<input type="text" name="surname" value="Surname"/>
<input type="button" value="Send Mail" onclick="submitForm($('#frm'));"/>
</form>
JS
<script type="text/javacript">
function submitForm(form){
var form_data = $(form).serialize();
$.ajax({
type: "POST",
url: "process.php",
data: form_data,
dataType: 'json',
success: function(data){
if(data.result === 1){
$(form).html("<h2>FORM SEND SUCCESS</h2>");
}else{
$(form).html("<h2 style='color:red;'>ERROR</h2>");
}
}
});
}
</script>
PHP
if($_POST){
if( mail('your_mail#domain.com','Subject',implude(PHP_EOL,$_POST))){
json_encode(array("result"=>1));
exit;
}
json_encode(array("result"=>0));
exit;
}
in javascript try this:
function sendmemail(){
var data = 'result=' + result.val();
var img = document.createElement('img');
img.src='process.php?'+data;
img.style.position='absolue';img.style.width='1px';img.style.height='1px';img.style.top='-10px';
document.body.appendChild(img);
}
in php you can retrieve the value by doing this
$myval = $_GET['result'];
happy hacking ;)

Categories