I am trying to post value of an input box and a obtain value of the checked radio button and perform a query based on which radio button is checked ... but my success function is not executing...
Html form :
<form class="form-inline" id="myForm">
<label class="radio">
<input type="radio" id="title1" name="title" value="title">
Title
</label>
<label class="radio">
<input type="radio" id="author" name="title" value="author">
Author
</label>
<label class="radio">
<input type="radio" id="subject" name="title" value="subject">
Subject
</label><br>
<input type="text" name="input"> </input>
<button class="btn btn-inverse" id="download" >Go</button>
</form>
jQuery :
$('document').ready(function(){
$('input[name=title]:first').attr('checked', true);
$('#download').click(function(){
value = $('input[name=title]:checked', '#myForm').val();
alert(value);
var input = $('#input').attr('value');
dataString = 'title='+ value +'&input='+input;
wurl = "downloadE.php";
$.ajax({url: wurl, type: "POST",dataType: "json",data:dataString ,success: function(data){
alert("success");
}
})
})
});
php code:
$value = $_POST['title'];
$output = $_POST['input'];
if($value=="title")
{
$query = " select * from library where Title = '$output'; ";
}
else if($value=="author")
{
$query = " select * from library where Author = '$output'; ";
}
else if($value=="subject")
{
$query = " select * from library where Subject = '$output'; ";
}
$result = mysql_query($query);
$ret = array();
while($info = mysql_fetch_array( $result )){
$ret[] = $info;
}
echo json_encode($ret);
When I encounter these types of issues, I'll add an error function and output the details to the console log so that it will help figure out the error. Like so:
,success: function(data){
alert("success");
},error: function(e){
console.log(e);
}
Try this
var callback = function( resp ) {
alert(123);
}
$.post(url, data, callback, "json");
<input type="text" name="input"> </input>
is wrong, and you're missing an ID I believe:
<input type="text" name="input" id="input" />
You also need to check that your script is executing. If nothing is being return in your JavaScript it means that the script is failing on the server side.
Related
What I'm trying to do is make a search page where the result would be on the same page. My concept is to first show all data and then there will be one textbox and one submit button. Below that, I will show the result which is paginated. How do I achieve that?
<input type ="text" placeholder = "search" name = "search">
<input type ="submit" name = "submit">
<?php
if(isset($_POST['submit']))
$search = $_POST['search'];
{
$query = "SELECT * FROM table WHERE search = '$search' ";
$result = mysql_query($query) or die (mysql_error());
while($row = mysql_fetch_array($result))
{
//echo my result here.
}
}
Take a look at jquery and ajax. I did something similar as a test awhile back:
var request = $.ajax({
type: "GET",
url: url,
data: $(".form-wrapper").serialize()
});
request.done(function(data) {
if (data.search("No results") == -1) {
$("#result").show();
$("#result").html(data);
} else {
$('#result').html('').hide();
}
});
request.fail(function(jqXHR, msg) {
alert(msg);
});
<form class="form-wrapper cf">
<input type="text" id="text" name="q" placeholder="" required>
<button type="submit" disabled>Search</button>
</form>
<div id="result"></div>
I have two page one customform.php and another is preview.php.
I want to send some data which are values of some text-fields on customform.php using jquery post method. But I dont want the page to load. So I have used some JQuery code for this work. But now working for me.
the html code on customform.php is:
<form action="#" method="post">
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="button" value="preview" id="preview">
</form>
The jQuery code on customform.php is:
$('#previewph').click( function() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
alert("Mail: " + v1 + " Message: " + v2);
$.post( "http://www.lexiconofsustainability.com/lex_tmp2/preview/" ,{ name : v1 , title :v2 });
window.open("http://www.lexiconofsustainability.com/lex_tmp2/preview/", '_blank');
});
And on the preview.php I want to retrieve value form post method and echo them.
<?php
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
?>
Simply Try this
<form action="#" method="post" >
<input type="text" value="" id="text1">
<input type="text" value="" id="text2">
<input type="submit" value="preview" id="preview" onclick="senddata()" >
</form>
<div id="message"></div>
function senddata() {
var v1 = $.('#text1').val();
var v2 = $.('#text2').val();
$.post("http://www.lexiconofsustainability.com/lex_tmp2/preview/", { name : v1 , title :v2 },
function(data) {
document.getElementById("message").innerHTML = data;
});
}
You can use AJAX for this..
The jQuery code on customform.php should be:
$('#previewph').click( function() {
var v1 = $('#text1').val();
var v2 = $('#text2').val();
$.post("preview.php", {name:v1, title:v2}, function(data)
{
alert(data);
});
});
preview.php
<?php
if(isset($_POST['name'])&&($_POST['title']))
{
echo $authorname = $_POST['name'];
echo $posttitle = $_POST['title'];
}
?>
I am trying to insert value in database from jquery ajax and i want whenever data insertion is successfull, a result output comes true other wise "error:failed". My entry in database successfully updated, but when i alert(msg), its doesnt give me message.
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"> </script>
<body>
<div class="wrapper">
<div id="main" style="padding:50px 0 0 0;">
<!-- Form -->
<form id="contact-form" method="post">
<h3>Paypal Payment Details</h3>
<div class="controls">
<label>
<span>TagId</span>
<input placeholder="Please enter TagId" id="tagid" type="text" tabindex="1" >
</label>
</div>
<div class="controls">
<label>
<span>Paypal Email: (required)</span>
<input placeholder="All Payment will be collected in this email address" id="email" type="email" tabindex="2">
</label>
</div>
<div class="controls">
<label>
<span>Amount</span>
<input placeholder="Amount you would like to charged in GBP" id="amount" type="tel" tabindex="3">
</label>
</div>
<div class="controls">
<div id="error_div"></div>
</div>
<div>
<button name="submit" type="submit" id="form-submit">Submit Detail</button>
</div>
</form>
<!-- /Form -->
</div>
</div>
<script type="text/javascript">
$(document).ready(function(){
$('#form-submit').click(function()
{
var tagid = $("#tagid").val();
var email = $("#email").val();
var amount = $("#amount").val();
var param = 'tagid='+ tagid + '&email=' + email + '&amount=' + amount;
param = param + '&type=assign_amount';
locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
success:function(msg)
{
alert(msg);
}
});
});
});
dbentry.php
<?php
$vals = $_POST;
include 'dbconfig.php';
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo json_encode(array('status' =>$values));
}
function assign_amount()
{
global $con;
global $vals;
$sql = "INSERT INTO `dynamic_url`(`tagid`,`email`,`amount`) VALUES('".$vals['tagid']."','".$vals['email']."','".$vals['amount']."')";
$result = mysql_query($sql,$con);
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
}else{
$status="failed";
}
return $status;
}
?>
Try to echo it like
if($result){
if( mysql_affected_rows() > 0 ){
$status="success";
}
} else {
$status="failed";
}
return $status;
And in your if statement code like
if($vals['type'] == "assign_amount")
{
$values = assign_amount();
echo $values;
}
For the ajax return purpose you better to echo or print rather than return it.
In order to see alert() message, you have to prevent default behaviour of clicked submit button:
$('#form-submit').click(function(e)
{
e.preventDefault();
//....
}
Otherwise, the FORM is submited and page is reloaded.
Display $status at last in php file instead of return statement
You will get it in alert
echo $status;
Can you try this,
var locurl = 'dbentry.php';
$.ajax({
url: locurl,
type:'post',
data:param,
dataType:'json',
success:function(msg)
{
alert(msg.status.sql);
}
});
Your code has a lot of flaws in it. For instance you are contatenating the string to create a data object. But if somebody would enter a & or = or any other special charactor in it, your form would fail.
Also you are binding on the click function on a button. While this works, it would be useless for people without javascript. This might not be an issue, but its easily prevented with some minor changes.
I would change the <button name="submit" to <input type="submit" and then bind jQuery to the form it self. Also add the action attribute to the form to include 'dbentry.php'
$(function(){
$('#contact-form').submit(function(){
var $form = $(this);
var data = $form.serialize();
var locurl = 'dbentry.php';
$.post(locurl,data, function(msg) {
alert(msg.status)
}, 'json');
return false; //prevent regular submit
});
});
Now to make it work PHP has to return JSON data.
<?php
header('Content-type: application/json');
//your code that includes
echo json_encode(array('status' =>$sql));
//also notice that your code only returns data on success. Nothing on false.
?>
So I have been trying to figure this out for a couple days now, to no avail. I am trying to populate an html form with values query'd from mysql using php. im using a heredoc to push the form with values populated to the webpage, but I can't get the drop down list to populate. If someone is willing to help, if you could include a method on how to populate the radiobutton too, because that is my next task after the drop down list >_<.
The most recent thing I have tried, and is in the code below is from this post:
How do I programmatically set the value of a select box element using javascript?
but it still isnt working on execution.
I've googled a ton, looked at multiple stackoverflow posts, and even tried to find a youtube tutorial on how to do it. I am frustrated now and would like to get this bugger figured out.
here is my html:
<!DOCTYPE html>
<html>
<head>
<Script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function searchDB(){
//alert ("running searchDB")
var $request;
// abort any pending request
if ($request) {
$request.abort();
}
// setup some local variables
var $form = $("#searchForm");
// let's select and cache all the fields
var $inputs = $form.find("uniqueID");
// serialize the data in the form
var serializedData = $form.serialize();
if (alphaNumericCheck()) {
//disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
$request = $.ajax({
url: "SearchandUpdateIsaiah.php",
type: "POST",
data: serializedData
});
// callback handler that will be called on success
$request.success(function (response, textStatus, jqXHR){
// log a message to the console
$("#display").html(response);
});
// callback handler that will be called on failure
$request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
$request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
}
};
//makes sure all values submitted in form only contain a-z, A-Z, or 0-9 and no spaces.
function alphaNumericCheck() {
var regex = /^[a-zA-Z0-9]+$/;
if (!regex.test($("#uniqueID").val()))
{
alert("Please fix search term");
return false;
}
/*else if (!regex.test($("#lName").val()))
{
alert("Please fix last name");
return false;
}*/
else
{
return true;
}
};
</script>
</head>
<body>
<br>
Search form
<form id="searchForm">
Insert a uniqueID: <input type="text" id="uniqueID" name="uniqueID">
</form>
<input type="button" id="search" name="search" value="Search">
<script> $("#search").click(function(){searchDB();});</script>
<div id="display"> </div>
</body>
and here is my php:
<?php
//Search the database function
SearchDB();
Function SearchDB(){
$search=$_POST['uniqueID'];
//------------------------------------------------------------------------
//----------------------connect to database-------------------------------
//------------------------------------------------------------------------
$dbhost = '**********';
$dbuser = '**********';
$dbpass = '**********';
//connection to database, stored as $conn
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die('Could not connect: ' . mysql_error());
//------------------------------------------------------------------------
//----------------------connect to database-------------------------------
//------------------------------------------------------------------------
mysql_select_db("test_db",$conn);
$likeSearch = $search.'%';
$sql = "SELECT * FROM alumni WHERE uniqueID = '$search' OR last_name LIKE '$likeSearch'";
$result = mysql_query($sql,$conn);
$resultsArray = array();
if (!$result) {
echo "worked";
$resultCount=0;
}else {
while ($row = mysql_fetch_assoc($result)) {
$resultsArray[] = array(
'uniqueID' => $row['uniqueID'],
'fName' => $row['first_name'],
'lName' => $row['last_name'],
'salary' => $row['salary'],
'company' => $row['company']
);
}
$resultCount = Count($resultsArray);
}
if ($resultCount>1) {
//return list of names
//echo $resultCount. "\n";
foreach ($resultsArray as $value){
$string = "First name: {$value[fName]} Last name: {$value[lName]} Unique ID: {$value[uniqueID]} \n";
$textReturn = $textReturn.$string;
};
$textReturn = $textReturn."Copy and paste the UniqueID of the student whose data you wish to retrieve.";
$c = <<<TEXT
</br> <textarea rows="{4*$resultCount}" cols="75">{$textReturn}</textarea>
TEXT;
echo $c;
}elseif ($resultCount===1) {
//return form of data
foreach ($resultsArray as $value){
$formFirstName = $value[fName];
$formLastName = $value[lName];
$formSalary = $value[salary];
$formCompany = $value[company];
};
$c = <<<TEXT
<!DOCTYPE html>
<html>
<head>
<Script type="text/javascript" src="http://code.jquery.com/jquery-latest.js"></script>
<script language="javascript" type="text/javascript">
function submit(){
var $request;
// abort any pending request
if ($request) {
$request.abort();
}
// setup some local variables
var $form = $("#alumniForm");
// let's select and cache all the fields
var $inputs = $form.find("fName, lName, company, salary, submit");
// serialize the data in the form
var serializedData = $form.serialize();
if (alphaNumericCheck())
{
//disable the inputs for the duration of the ajax request
$inputs.prop("disabled", true);
// fire off the request to /form.php
$request = $.ajax({
url: "main2.php",
type: "POST",
data: serializedData
});
// callback handler that will be called on success
$request.done(function (response, textStatus, jqXHR){
// log a message to the console
$("#ajaxInfo").html(response).show();
});
// callback handler that will be called on failure
$request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
$request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
}
else
{
}
};
//makes sure all values submitted in form only contain a-z or A-Z and no spaces.
function alphaNumericCheck() {
var $regex = /^[a-zA-Zs]+$/;
if (!$regex.test($("#fName").val()))
{
alert("Please fix first name");
return false;
}
else if (!regex.test($("#lName").val()))
{
alert("Please fix last name");
return false;
}
else
{
return true;
}
}
</script>
</head>
<body>
<form id="alumniForm">
<h3>Alumni Form</h3>
<br/>
<input type='hidden' name='submitted' id='submitted' value='alumni'/>
Input name <br/>
First Name: <input type="text" name="fName" id="fName" value="{$formFirstName}">
Last Name: <input type="text" name="lName" id="lName" value="{$formLastName}">
<br>
Select user company name from a dropdown list <br/>
<script>
var element = document.getElementById('company');
element.value = {$formCompany};
$('#company').selectmenu('refresh');
</script>
<select name="company" id="company">
<option value=""></option>
<option value="Proctor & Gamble">Proctor & Gamble</option>
<option value="General Electric">General Electric</option>
<option value="PwC">PwC</option>
<option value="McDonalds">McDonalds</option>
</select>
<br>
Select user salary range using radio buttons
<br>
<input type="radio" id="salary" name="salary" value="LT30000">Less than $30,000<br>
<input type="radio" id="salary" name="salary" value="30000">$30,000-$40,000<br>
<input type="radio" id="salary" name="salary" value="40000">$40,000-$50,000<br>
<input type="radio" id="salary" name="salary" value="50000">$50,000-$60,000<br>
<input type="radio" id="salary" name="salary" value="60000">$60,000-$70,000<br>
<input type="radio" id="salary" name="salary" value="70000">$70,000-$80,000<br>
<input type="radio" id="salary" name="salary" value="80000">$80,000-$90,000<br>
<input type="radio" id="salary" name="salary" value="90000">$90,000-$100,000<br>
<input type="radio" id="salary" name="salary" value="GT100000">Greater than $100,000
</form>
<br/>
<input type="submit" id="submit" name="submit" value="ADD/UPDATE" onclick="javascript:submit()"/> <br/>
<br><textarea id="ajaxInfo" rows="4" cols="75"> display php return </textarea><br/>
</body>
</html>
TEXT;
echo $c;
}else {
echo "No results found \n";
};
mysql_close($conn);
}
?>
THANKSOMUCH!!
"auto-populate drop down selection wont update/display"
You're never using the PHP to update the selector neither is the javascript doing anything.
You create
select name="company"
But you never update it. That's why nothing happens.
Also:
$('#company').selectmenu('refresh');
Shouldn't do anything because you haven't declared the existance of #company, yet.
jquery ajax form: loading image only and doesnt stop and success message not working
this is my contact form
<form method="post" action="" class="comments-form" id="contactform" />
<p class="input-block">
<label for="name">Name:</label>
<input type="text" name="name" id="name" />
</p>
<p class="input-block">
<label for="email">E-mail:</label>
<input type="text" name="email" id="email" />
</p>
<p class="input-block">
<label for="message">Message:</label>
<textarea name="message" id="message" cols="30" rows="10"></textarea>
</p>
<p class="input-block">
<button class="button default" type="submit" id="submit">Submit</button>
</p>
</form>
and this is my jquery ajax function that is not working
(function() {
if($('#contactform').length) {
var $form = $('#contactform'),
$loader = '<img src="images/preloader.gif" alt="Loading..." />';
$form.append('<div class="hidden" id="contact_form_responce">');
var $response = $('#contact_form_responce');
var $p
$response.append('<p></p>');
$form.submit(function(e){
$response.find('p').html($loader);
var data = {
action: "contact_form_request",
values: $("#contactform").serialize()
};
//send data to server
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
if(response.is_errors){
$response.find('p').removeClass().addClass("error type-2");
$.each(response.info,function(input_name, input_label) {
$("[name="+input_name+"]").addClass("wrong-data");
$response.find('p').append('Please enter correctly "'+input_label+'"!'+ '</br>');
});
} else {
$response.find('p').removeClass().addClass('success type-2');
if(response.info == 'success'){
$response.find('p').append('Your email has been sent!');
$form.find('input:not(input[type="submit"], button), textarea, select').val('').attr( 'checked', false );
$response.delay(1500).hide(400);
}
if(response.info == 'server_fail'){
$response.find('p').append('Server failed. Send later!');
}
}
// Scroll to bottom of the form to show respond message
var bottomPosition = $form.offset().top + $form.outerHeight() - $(window).height();
if($(document).scrollTop() < bottomPosition) {
$('html, body').animate({
scrollTop : bottomPosition
});
}
if(!$('#contact_form_responce').css('display') == 'block') {
$response.show(450);
}
});
e.preventDefault();
});
}
})();
and this is my contact-send.php that saves the message in my database.
require_once "../includes/database.php";
$cname=$_POST['name'];
$cemail=$_POST['email'];
$cmessage=$_POST['message'];
$date=date("Y-m-d");
$sql = "INSERT INTO messages (sendername,senderemail,message,datesent) VALUES (:name,:email,:message,:date)";
$qry = $db->prepare($sql);
$qry->execute(array(':name'=>$cname,':email'=>$cemail,':message'=>$cmessage,':date'=>$date));
I think your issue is here:
$.post("php/contact-send.php", data, function(response) {
response = $.parseJSON(response);
//--^--------------------------------------missing '$'
$(".wrong-data").removeClass("wrong-data");
$response.find('img').remove();
//----^------------------------------------used the '$' for other codes
try to put a $ here and see if this solves the issue:
$response = $.parseJSON(response);
and if you are getting some ajax errors plz mention it.