I want to post some values from a simple HTML form, validate them with an ajax call and if successful submit to a PHP script and redirect to that script. I have got the ajax part set up, just not sure how to post and redirect (as if you would on a standard form submit without ajax).
Here's what I have:
HTML:
<div id=audiencesearch>
<h1>Audience Search</h1>
<form id="audiencesearchform">
<p>Passion Point</p>
<select id="passionselect">
<option selected="selected">Please select</option>
<option>3D</option>
<option>Music</option>
<option>Playstation</option>
</select>
<p>Gender Bias</p>
<select id="genderselect">
<option selected="selected">Please select</option>
<option>Male</option>
<option>Female</option>
</select>
<p>Sort Group By Age Range</p>
<select id="ageselect">
<option selected="selected">Please select</option>
<option>Under 21</option>
<option>21 - 30</option>
<option>31 - 40</option>
<option>41 - 50</option>
</select>
<br/>
<br/>
<input onClick="ajaxaudiencesearch()" class="submitaudiencesearch" value="Search" type="button"/>
Ajax Call:
<script type="text/javascript">
function ajaxaudiencesearch(){
var passionpoint = $("select#passionselect").val();
var genderbias = $("select#genderselect").val();
var agerange = $("select#ageselect").val();
var passedstring = 'passion='+ passionpoint + '&gender=' + genderbias + '&age=' + agerange;
$.ajax({
type: "POST",
url: "processaudiencesearch.php",
data: passedstring,
success:function(retval){
if (retval == 'oktoprocess'){
audiencesearchprocess();
} else {
audiencesearcherror();
}
}
})
}
function audiencesearcherror(){
$('#audienceerror').html('GOTTA SELECT EM ALL');
}
function audiencesearchprocess(){
window.location.href = "searchresults.php";
//THIS IS WHERE I WANT TO POST AND MOVE TO SEARCHRESULTS.PHP
}
</script>
PHP to handle Ajax:
<?php
include('sonymysqlconnect.php');
session_start();
$nullselection = "Please select";
//get the posted values
$postedpassion = ($_POST['passion']);
$postedgender = ($_POST['gender']);
$postedage = ($_POST['age']);
if (($postedpassion != $nullselection ) && ($postedgender != $nullselection ) && ($postedage != $nullselection)){
echo 'oktoprocess';
} else {
echo 'error';
}
?>
Preferably I could achieve this using jQuery. I'm sure it's extremely simple but I'm not sure how to do it?!
It's worth mentioning that this is all set up correctly. I have used PHP includes.
Thanks in advance...
Why not add action and method attributes to your form and then submit it with .submit()?
With plain html / php it is not even really a true redirect, its just the url value in "action" that can be found in the form element
<form action="/someUrl/someAction" method="POST">
...
</form>
If you're doing it with ajax (jquery), you'd say:
$.ajax({
url: '/someUrl/someAction',
type: 'POST',
data: {
argName1: 'argVal1',
argName2: 'argVal2'
},
success: function( response ) {
// keep in mind that response is usually in json...
// which means you'd be accessing
// the data in object notation: response.data.someVal
if(response == 'whatYouWanted') {
//do something... like redirect?
window.location = '/new/page';
}
});
Related
I m searching something of easy. I must pass value from a form html to a file PHP by jquery. I try this code with zero result. If someone can say me where i m mistaking. Thx
for JQUERY
$('#Save').click(function(){
var realvalues = new Array();//storing the selected values inside an array
$('#Privilege[] :selected').each(function(i, selected) {
realvalues[i] = $(selected).val();
});
$.ajax({
type: "POST",
url: "test5.php",
data: {"Privilege[]": realvalues},
success:function(data){
$("#subscrres").html(data)
}
});
});
For HTML
<form method="post">
<select id="Privilege[]" multiple>
<option value="yahoo">yahoo</option>
<option value="chrome">chrome</option>
<option value="mozilla">mozilla</option>
</select>
<input type="button" id="Save" Value="SEND"/>
For PHP. Content file test5.php
if(isset($_POST['Privilege'])){
$myvar =$_POST['Privilege'];
foreach($_POST['Privilege'] as $one)
echo $one."<br/>";
}
I don't receive nothing on PHP. Someone can help me ?
If you are trying to access multi select element using id the you don't need to set id like Privilege[], you can set any unique identity like privilege-selector but if you are giving name for any multi select element then name must be like Privilege[]
Here is the html :
<form id="form" method="post">
<select id="privilege-selector" multiple>
<option value="yahoo">yahoo</option>
<option value="chrome">chrome</option>
<option value="mozilla">mozilla</option>
</select>
<input type="button" id="Save" Value="SEND"/>
</form>
Please check this below ajax request to post selected data to the server
$("#Save").on("click",function(){
var selection = [];
$.each($("#privilege-selector option:selected"),function(index,element){
selection.push($(element).val());
})
$.ajax({
url : "test5.php",
type : "POST",
data : {Privilege:selection},
success : function(_response){
var res = JSON.parse(_response);
if(res.code == "1"){
console.log(res.data);
} else {
alert(res.message);
}
}
})
});
and here is your server file that will handle the incoming request data
$serverResponse = [];
if(isset($_POST['Privilege']) && !empty($_POST['Privilege'])){
$formattedData = [];
foreach($_POST['Privilege'] as $key => $value){
$formattedData[] = array(
"id" => $key+1,
"name" => $value
);
}
$serverResponse = ["code"=>"1","message"=>"formatted data","data"=>$formattedData];
} else {
$serverResponse = ["code"=>"0","message"=>"Please select at least on value"];
}
echo json_encode($serverResponse);
How do I want to post a form using jquery serialize function? I tried to post the form value but on the php part, the value is not shown. Below are my codes:
html
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
jQuery
$(document).on("click", "#submit", function(e){
e.preventDefault();
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
data = $('form').serialize();
$.post('result.php',
{
data : data
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
});
PHP
if(isset($_REQUEST["sort"])){
$sort = $_REQUEST['sort'];
$id_staff = $_REQUEST['id_staff'];
echo "Your Id : $id_staff <p/>";
echo "You choose : $sort";
}
If I console.log(data), I get: id_staff=12345&sort=1
Your server is receiving a string that looks something like this (which it should if you're using jQuery serialize()):
"param1=someVal¶m2=someOtherVal"
...something like this is probably all you need:
$params = array();
parse_str($_GET, $params);
$params should then be an array that contains all the form element as indexes
If you are using .serialize, you can get rid of this:
var sort = $("#sort").val(),
id_staff = $("#id_staff").val(),
You data will be available as follows with .serialize:
your-url.com/sort=yoursortvalue&id_staff=youridstaff
It should be:
$(document).ready(function(e) {
$("#myform").submit(function() {
var datastring = $( this ).serialize();
$.post('result.php',
{
data : datastring
}, function(data){
$("#loader").fadeOut(400);
$("#result").html(data);
});
})
})
On PHP side you simple need to access it using the $_GET['sort'].
Edit:
To view the data, you should define a div with id result so that the result returned is displayed within this div.
Example:
<div id="result"></div>
<form name="myform">
ID : <input type="text" name="id_staff" id="id_staff">
<select name="sort" id="sort">
<option value="0">Choose Status</option>
<option value="1">All</option>
<option value="2">Pending</option>
<option value="3">Approve</option>
<option value="4">Not Approve</option>
</select> <input type="button" id="submit" value="Papar" />
<div id="loader"></div>
</form>
I am able to do it this way:
jQuery
<script type="text/javascript">
$(document).ready(function() {
var form = $("#myform");
$("#myform").submit(function(e) {
e.preventDefault();
$.ajax({
type: "POST",
url: 'result.php',
data: form.serialize(),
success: function(response) {
console.log(response);
$("#result").html(response);
},
error: function() {
alert('Error Submitting');
}
})
})
})
</script>
PHP
if(isset($_POST["id_staff"])){
$sort = $_POST['sort'];
$id_staff = $_POST['id_staff'];
echo "<p>Your Id : $id_staff</p>";
echo "You choose : $sort";
}
Do give a comment if it need improvement or better solution.
I have a select option, to get the value from this, I used jquery (please see below code). After I display the selected value in the textbox, I'm now having problem on how to get the value of textbox to process a such code. Even simply echo of the value is not working. What's the problem with the code? Please help. Thanks.
Select option:
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
Jquery:
$('#shiptype').change(function () {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
}
});
Text Field:
<input type='text' id='strkey' name='keyname' />
Display the value:
$key = $_POST['keyname'];
echo $key;
Please try this code :
HTML file contains this below code. File name test.html.
Form to submit your data.
<form id="frm_post">
<select name='shiptype' id='shiptype'>
<option value="0">Please select...</option>
<option value="LOC">LOCAL</option>
<option value="IM">IMPORT</option>
</select>
<input type="text" name="name" id="strkey">
<input id="btn_post" type="button" name="submit" value="Submit">
</form>
This is a div for your output.
<div>
<p id="output"></p>
</div>
This is jquery for ajax call function.
<script>
$(document).ready(function(){
$('#shiptype').change(function() {
var selectedValue = $(this).val();
var strloc = "LOCAL";
var strimp = "IMPORT";
if (selectedValue == "LOC") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
} else if (selectedValue == "IM") {
$('#strkey').val(selectedValue);
//alert($('#strkey').val());
}
});
$("#btn_post").click(function(){
var parm = $("#frm_post").serializeArray();
$.ajax({
type: 'POST',
url: 'your.php',
data: parm,
success: function (data,status,xhr) {
console.info(data);
$( "#output" ).html(data);
},
error: function (error) {
console.info("Error post : "+error);
$( "#output" ).html(error);
}
});
});
});
</script>
And for PHP File to get the post value like this below. File name your.php.
<?php
// $key = $_POST['keyname'];
// echo $key;
print_r($_POST);
?>
Your post result will be show up in output id. Hope this help you out. :D
and thank you in advance for reading this. I'm new in php and jquery. I've managed to do few forms in php that worked, and now feel a big need (because of how my webpage is shaping) to make them work with jquery. I'm trying but something is not right. This is the form:
<form action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method ="post" id="form_Add">
<br>
<div class="Add_field" id="title_div">Title:<input typee="text" class="Add_text" maxlength="100" name="title" id="title"></div>
<br>
<div class="Add_field">Discription:<input typee="text" class="Add_text" maxlength="1000" name="discription" id="discription"></div>
<br>
<div class="Add_field" id="content_div">Content:<textarea class="Add_text" maxlength="65535" name="content" id="content" rows="5" cols="15"></textarea></div>
<br>
<div class="Add_field"><label for="shortstory"><input typee="radio" name="prose" class="" id="shortstory" value="1">Short story</label></div>
<div class="Add_field" id="prose_div"><label for="chapter"><input typee="radio" name="prose" class="" id="chapter" value="2">Chapter</label></div>
<br>
<div class="Add_field" id="typey">type:
<select name="type1">
<option value="1" selected="selected">Fantasy</option>
<option value="2">Action</option>
<option value="3">Romance</option>
</select>with elements of
<select name="type2" id="type2">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>and
<select name="type3" id="type3">
<option value="" selected="selected"></option>
<option value="1">fantasy</option>
<option value="2">action</option>
<option value="3">romance</option>
</select>
</div>
<div class="Add_field"><input typee="submit" name="Add_story" class="Add_button" id="submit_story" value="Add story"></div>
</form>
<div id="response">Something</div>
That is script:
<script>
$('#form_Add').on('submit', function (e) {
e.preventDefault();
checkAdd();
});
var selectType = function(){
var type2 = $('#type2').val();
if(type2 === ""){
$('#type3').attr('disabled', 'disabled');
$('#type3').val("");
}
else{
$('#type3').removeAttr('disabled');
}
}
$(selectType);
$("#type2").change(selectType);
function checkAdd(){
var title = $('#title').val();
var content = $('#content').val();
if(title === ""){
$('#titleErr').remove();
$('#title_div').append("<p id='titleErr'>Please add the title.</p>");
}
else{
$('#titleErr').remove();
}
if(content.replace(/ /g,'').length <= 18){
$('#contentErr').remove();
$('#content_div').append("<p id='contentErr'>Content needs to be at least 19 characters long.</p>");
}
else{
$('#contentErr').remove();
}
if($("#shortstory").not(":checked") && $("#chapter").not(":checked")){
$('#proseErr').remove();
$('#prose_div').append("<p id='proseErr'>Check one of the above.</p>");
}
if($("#shortstory").is(":checked") || $("#chapter").is(":checked")){
$('#proseErr').remove();
}
if($("#titleErr").length == 0 && $("#contentErr").length == 0 && $("#proseErr").length == 0){
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', { // when using this bit of script I get 403 Forbidden in Firebug console
title: $('#title').val(),
discription: $('#discription').val(),
content: $('#content').val(),
prose: $('input[name=prose]:checked').val(),
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
}, function(d){
alert(d);
console.log(d);
$('#response').html(d);
});
}
/*
var postData = $("#form_Add").serialize(); // when using this bit of script instead of one on top, I get alert fail and ReferenceError: data is not defined in Firebug console
var formURL = $("#form_Add").attr("action");
$.ajax(
{
url : formURL,
typee: "POST",
data : postData,
datatypee: 'json',
success:function(data, textStatus, jqXHR)
{
alert("success");//data: return data from server
console.log(data.error);
},
error: function(jqXHR, textStatus, errorThrown)
{
//if fails
alert("fail");
console.log(data.error);
}
});
}
*/
};
</script>
And here is php code:
<?php
session_start();
if(isset ($_SESSION['arr'])){
$arr = $_SESSION['arr'];
$uid = $arr['id'];
}
$title = $discription = $content = $prose ="";
if (isset($_POST["Add_story"])) {
$title = stripslashes($_POST["title"]);
$title = mysqli_real_escape_string($connection , $title);
$discription = stripslashes($_POST["discription"]);
$discription = mysqli_real_escape_string($connection , $discription);
$content = stripslashes($_POST["content"]);
$content = mysqli_real_escape_string($connection , $content);
$prose = stripslashes($_POST["prose"]);
$prose = mysqli_real_escape_string($connection , $prose);
$type1 = $_POST["type1"];
$type2 = $_POST["type2"];
$type3 = $_POST["type3"];
$pQuery = "INSERT INTO prose (u_id, data, title_s, discription_s, content_s, prose_s, type1_s, type2_s, type3_s, shows_s)
VALUES ('{$uid}', CURDATE(), '{$title}', '{$discription}', '{$content}', {$prose}, '{$type1}', '{$type2}', '{$type3}', 0)";
$resultP = mysqli_query($connection, $pQuery);
if ($resultP) {
$title = $discription = $content = $prose ="";
}
else {
die("Query failed." . mysqli_error($connection));
}
}
?>
Php code is on the top of the document. Source is on bottom and form is in the middle (I'm using jquery-1.11.1.min.js - source is added in main page, as this one is included in it). I've also tried putting php in separate file and pointing to it through form action instead of <?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?> but without any joy. I'm guessing my problem is with post data. It probably has to be in an array or object (and I'm doing it wrong) and when it reaches processing there is some sort of incompatibility. Probably using select and radio buttons complicates the process.
Any tips you can share I will greatly appreciate. Thank you for your time.
You have a serious typo in your submit button
<input typee="submit" name="Add_story"
^ extra "e"
which should read as
<input type="submit" name="Add_story"
Your code's execution relies on your conditional statement:
if (isset($_POST["Add_story"])){...}
Plus, you've made the same typo for all your other inputs typee="xxx"
Change them all to type
A simple CTRL-H (typee/type) in a code editor such as Notepad++ even in Notepad will fix that in a jiffy.
I noticed you have given id's to both <select name="type2" id="type2">
and <select name="type3" id="type3"> but not for <select name="type1">, so that could also be another factor that could affect your code's execution, seeing that you have:
type1: $('#type1').val(),
type2: $('#type2').val(),
type3: $('#type3').val()
Edit:
You've also put a commented message which I only saw now and should have been made clear in your question:
// when using this bit of script I get 403 Forbidden in Firebug console
over to the right of
$.post('"<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"', {
so I didn't see that.
Try changing it to either, and in single quotes only:
$.post('<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>', {
or
$.post('your_file.php', $(this).serialize(), function(data){
This page may help:
https://www.codeofaninja.com/2013/09/jquery-ajax-post-example.html
It contains an example in there that you can base yourself on.
which contains
$.ajax({
type: 'POST',
url: 'post_receiver.php',
data: $(this).serialize()
})
and may need to be added to your script.
You commented out url : formURL, - try using url: 'your_PHP_file.php', in its place, that being the PHP/SQL file that you're using.
If none of this helped, than let me know and I will simply delete this answer.
I am trying to make a set of webpages that will display a unique graph based on a simple form that only has a selector box and a submit button. Basically what I want to happen is when the user changes the month in the selector and presses submit, a new chart set will render on the same page.
Here is the HTML initial page:
<HTML>
<HEAD>
<SCRIPT src="http://code.jquery.com/jquery-1.10.1.min.js"></SCRIPT>
</HEAD>
<BODY>
<CENTER>
<FORM ID="form1" METHOD="post" ACTION="">
<SELECT NAME="monthSelector">
<OPTION VALUE="0">Select Month...</OPTION>
<OPTION VALUE="1">January</OPTION>
<OPTION VALUE="2">February</OPTION>
<OPTION VALUE="3">March</OPTION>
<OPTION VALUE="4">April</OPTION>
<OPTION VALUE="5">May</OPTION>
<OPTION VALUE="6">June</OPTION>
<OPTION VALUE="7">July</OPTION>
<OPTION VALUE="8">August</OPTION>
<OPTION VALUE="9">September</OPTION>
<OPTION VALUE="10">October</OPTION>
<OPTION VALUE="11">November</OPTION>
<OPTION VALUE="12">December</OPTION>
</SELECT>
<INPUT TYPE="submit" VALUE="Show Charts">
</FORM>
<DIV ID="response"></div>
<SCRIPT>
function submit()
{
$(function()
{
var month = 3;
var formdata = "month=" + month;
$.ajax({
type: 'POST',
url: 'showCharts.php',
data: formdata,
success: function(data) {
$("#response").html(data);
}
});
});
}
</SCRIPT>
</CENTER>
</BODY>
</HTML>
and here is showCharts.php:
<?php
include("../FusionCharts/FusionCharts.php");
include("../DBConnect.php");
$month = $_POST['month'];
echo $month;
//insert complex queries and fusioncharts code that already works!
?>
Someone please help me, I've been staring at this for hours and can't make any progress.
You can also use the .load method of jQuery:
function submit()
{
var month = 3;
var formdata = month;
$('#response').load('showCharts.php?month='+formdata);
}
Also, you will need to set:
$month = $_REQUEST['month'];
Another way to do it would be:
$('select').change(function() {
var formdata = { month: document.getElementsByName('monthSelector')[0].value };
$('#response').load( 'showCharts.php', formdata);
});
Try replacing
<FORM ID="form1" METHOD="post" ACTION="">
for
<FORM ID="form1" METHOD="post" ONSUBMIT="submit(); return false;">
It should work.
In the part of jQuery, put this:
function submit()
{
var month = $('select[name="monthSelector"]').val();
$.ajax({
type: 'POST',
url: 'showCharts.php',
data:{'month':month},
success: function(data)
{
$("#response").html(data);
}
});
}
One more thing: try to improve the HTML code, it will give a better image to your webpage.
Are you sure the submit function is even called? Do you bind the form's submit event at all?
I would do something like $("#form1").submit(submit);
Also, you should return false at the end of submit() to block the default form action (which is refresh the current page I believe)
Try to update the variable formdata to make it a json object rather than a string.
<SCRIPT>
function submit()
{
$(function()
{
var month = 3;
var formdata = {'month': month}; //change made here
$.ajax({
type: 'POST',
url: 'showCharts.php',
data: formdata,
success: function(data) {
$("#response").html(data);
}
});
});
}
</SCRIPT>
Your jQuery code should be as follows:
$(function() {
var month = 3;
var formdata = { month: month };
$('#response').load( 'showCharts.php', formdata );
$('#form1').submit(function( e ) {
e.preventDefault();
var formData = { month: this.monthSelector.value };
$('#response').load( 'showCharts.php', formData);
});
});
When using the ajax .load() method, here is what you should be aware of:
Request Method
The POST method is used if data is provided as an object; otherwise,
GET is assumed.
Therefore, with the above jQuery code, your PHP script need not be changed.