Getting form $_POST data from Ajax/Jquery in php - javascript

As always thanks in advance if you can help with this one.
I'm trying to use Ajax to call a script and post the form data at the same time. Everything works as expected except the $POST data which comes back blank when I try to echo or print it. Can anyone shine a light on what I have missed here please?
<form id="guestlist" name="guestlist">
<?php // Collect CLUBS data to pass to guestlist script ?>
<input type="hidden" name="gl_clubname" value="<?php echo $ptitle; ?>" />
<input type="hidden" name="gl_clubnumber" value="<?php echo $phoneno_meta_value; ?>" />
<input type="hidden" name="gl_clubemail" value="<?php echo $email_meta_value; ?>" />
<?php // Collect USERS data to pass to guestlist script ?>
<input type="hidden" name="gl_name" value="<?php echo $fullname;?>" />
<input type="hidden" name="gl_email" value="<?php echo $email;?>" />
<input type="hidden" name="gl_dob" value="<?php echo $birthday;?>" />
<input type="hidden" name="gl_propic" value="<?php echo $profile_url;?>" />
<div id="clubcontactleft">
<textarea id="clubmessage" name="gl_message" placeholder="Your message" rows="4" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/userreview.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 94px; width:250px; margin-bottom:15px;"></textarea>
<input type="text" name="gl_when" placeholder="Enquiry Date" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/calendaricon.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
<input type="text" name="gl_phonenumber" placeholder="Phone Number" style="background-image:url('http://www.xxxxx.com/wp-content/themes/xxxxx/images/phonecall.jpg');
background-repeat:no-repeat; padding-left:40px; background-size:40px 38px; width:250px;">
</div>
<div class="guestlistbutton">Send Message</div>
</form>
<script type="text/javascript">
$(document).ready(function($){
$(".guestlistbutton").on('click',function(event) {
event.preventDefault();
$("#clubcontactform").empty();
var url = "http://www.xxxxxx.com/wp-content/themes/xxxxxx/guestlist.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#guestlist").serialize(), // serializes the form's elements.
success: function(data)
{
$('#clubcontactform').append(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
Here is the php file that it pulls in
<?php
echo 'Pulling in guestlist.php<br/>';
$gl_message = $_POST['gl_message'];
print_r($gl_message);
echo $gl_message;
?>
Thanks!

Every thing seems to be correct only you forget to include the jquery file. please include and try once. If still persist the issue will create the Jsfiddle

I checked your code in my local machine and I got the following error "Caution provisional headers are shown". If you have the same message in your browser console, this information can help you: "CAUTION: provisional headers are shown" in Chrome debugger
Also, I see that js work perfectly. Problem in your url address. Try send your form to itself, just write html part and php part of code in one file.

<div>
<form id="Get_FRm_Data">
/*
Some field using.....
/*
</form>
<button type="button" name="submit" class="submit_act">Submit</button>
</div>
<script>
var file_pathname = window.location.protocol + "//" + location.host + "/foldername/";
$(document).on("click", ".submit_act", function ()
{
var $this_val=$(this);
$this_val.html("Loading...").prop("disabled",true);
var $data_ref = new FormData($("#Get_FRm_Data")[0]);
$data_ref.append("action", "fileaction_name");
$pathname = file_pathname + "filename.php";
$.ajax({
url: $pathname,
type: 'POST',
data: $data_ref,
cache: false,
contentType: false,
processData: false,
dataType: 'json',
success: function (result, status)
{
console.log(result);
if (status == "success")
{
$this_val.html("Submit").prop("disabled",false);
}
}
});
});
</script>
<?php
if (isset($_POST['action']))
{
$action = $_POST['action'];
if($action=="fileaction_name")
{
print_r($_POST);
}
}
?>

Related

Ajax is not working when I fetch data from MySQL

I'm building an ecommerce.and for this I'm fetching data products from database, I want to let people add products in cart without refreshing the page, I have tried AJAX but I don't know why but it works only when data is not in a loop, I'm in PHP, and MySQL.
Code:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="upcart(<?php echo $list['id']; ?>)">
</form>
<?php
}
?>
<script>
$(document).ready(function() {
function upcart(id){
e.preventDefault();
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId"+ id).serialize(),
// dataType: "text",
success: function (response) {
alert("success");
}
// return false;
});
};
});
</script>
Use events instead of manually calling the javascript function.
We then don't need to generate id's for the forms since it we will have access to the correct form in the callback.
The PHP part:
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" class="some-form-class">
<input type="hidden" name="name" value="value" />
<input type="submit" />
</form>
<?php
}
?>
The JS part:
<script>
$(document).ready(function() {
// Bind the forms submit event
$('.some-form-class').on('submit', function (event) {
event.preventDefault();
// Here we can use $(this) to reference the correct form
$.ajax({
method: "POST",
url: "data.php",
data: $(this).serialize(),
success: function (response) {
alert("success");
}
});
});
});
</script>
NOTE: Magnus Eriksson answer is far cleaner
since function upcart(id) is not in the global scope, onclick="upcart(<?php echo $list['id']; ?>)"> will fail due to the missing function
You need to declare that function in the global scope
Also, you need to prevent the form submission properly
<?php
$results = $conn->query("SELECT * FROM idd");
while ($list = $results->fetch_assoc()){
?>
<form method="POST" id="formId<?php echo $list['id'] ?>">
<input type="hidden" name="name" value="value">
<!-- <input type="hidden" name="name" id="id" value="value"> -->
<input type="submit" onclick="return upcart(<?php echo $list['id']; ?>)">
</form>
<?php
note the return upcart .... - very important
NOT INSIDE $(document).ready(function() { since you don't need to wait for document ready to declare a function!
function upcart(id) {
$.ajax({
method: "POST",
url: "data.php",
data: $("#formId" + id).serialize(),
success: function (response) {
alert("success");
}
});
return false; // to prevent normal form submission
}

AJAX file upload giving undefined file error

let me first explain what I aim to do, then display my code.
What I want to do is make a page which basically updates a user's details in the database, I did this part first and everything works perfectly here, through AJAX. Next I wanted to update the profile picture of the user as well through AJAX, so I made a normal file upload PHP page to make sure that my PHP code was working correctly and it was. Now I just needed to perform the upload via AJAX, and this is where I get stuck. I keep getting an error message from the PHP page which states undefined index: file.
Please feel free to ask any questions, and thank you for the responses.
Here is my HTML form:
<form action="upload.php?upload&type=profile" method="post" enctype="multipart/form-data">
<label for="profile">Profile Picture</label><br />
<img id="preview" width="200" height="200" src="<?php echo $user->getProfile(); ?>" alt="Profile Picture Preview" /><br />
<br />
<input type="file" name="file" id="file" onchange="loadImage(this);" /><br />
<label for="username">Username</label><br />
<input type="text" name="username" id="username" value="<?php echo $user->getUsername(); ?>" /><br />
<label for="email">Email Adress</label><br />
<input type="text" name="email" id="email" value="<?php echo $user->getEmail(); ?>" /><br />
<label for="bio">Biography</label><br />
<textarea name="bio" id="bio" cols="40" rows="5"><?php echo $user->getBio(); ?></textarea><br />
<label for="password">New Password</label><br />
<input type="password" name="password" id="password" /><br />
<label for="oldPass">Current Password</label><br />
<input type="password" name="oldPass" id="oldPass" /><br />
<label for="first">First Name</label><br />
<input type="text" name="first" id="first" value="<?php echo $user->getFirstName(); ?>" /><br />
<label for="last">Last Name</label><br />
<input type="text" name="last" id="last" value="<?php echo $user->getLastName(); ?>" /><br />
<br />
<input type="submit" name="update" value="Save" id="update" /> <input type="button" name="reset" value="Reset Fields" onclick="resetFields()" />
</form>
Here is my js file containing the AJAX:
$(document).ready(function() {
$("#update").click(function() {
profile = "pictures/default.jpg";
username = $("#username").val();
email = $("#email").val();
bio = $("#bio").val();
newPass = $("#password").val();
oldPass = $("#oldPass").val();
first = $("#first").val();
last = $("#last").val();
// First an ajax request to upload the image as it requires separate request
$.ajax({
type: "POST",
url: "upload.php?upload&type=profile",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(resp) {
alert(resp);
},
error: function (resp) {
alert(resp);
}
});
// Now the updates in the profile
$.ajax({
type: "POST",
url: "update.php",
data: "mode=details&profile="+profile+"+&username="+username+"&email="+email+"&bio="+bio+"&password="+newPass+"&oldPass="+oldPass+"&first="+first+"&last="+last,
success: function(resp) {
// resp contains what is echoed on update.php
alert(resp);
}
});
return false;
});
});
Finally, here is my PHP Code:
include "base.php";
// Kick user off this page if they are not logged in
if (!isset($user)) {
echo "<meta http-equiv='refresh' content='0.1;url=index.php'>";
exit();
}
if (isset($_GET['upload'])) {
switch ($_GET['type']) {
case "profile": {
$dir = "pictures/";
$maxFileSize = 2000000; // 2mb
$extensions = array("jpg", "jpeg", "png", "gif");
$currentPath = pathinfo($_FILES['file']['name']);
$fileType = $currentPath['extension'];
$targetFile = $dir.$user->getUsername()."Profile.".$fileType;
}
break;
default: {
echo "<meta http-equiv='refresh' content='0.1;url=index.php'>";
exit();
}
break;
}
$upload = true;
// Check the file size
if ($_FILES['file']['size'] > $maxFileSize) {
echo "The file is too large.";
$upload = false;
}
// Limit file types
if (!in_array($fileType, $extensions)) {
echo "This file type is not allowed.";
$upload = false;
}
// Check if file upload is allowed and upload if it is
if ($upload) {
if (move_uploaded_file($_FILES['file']['tmp_name'], $targetFile)) {
echo basename($_FILES['file']['name']);
} else {
echo "There was an error during file upload.";
}
}
}
Your code has a few issues. For one since your button was located within a Form and you were only associating a click on that button then the form was submitting itself as normal and pretty much confusing jquery. In order to capture the form properly in jquery you need to run it as a submit instead and add the e.preventDefault(); so that your code in ajax runs instead of the actual form submitting on the page.
You need to add e.preventDefault(); so that your form does not submit itself since you have form tags. Also change from click to submit
$("form").submit(function(e) {
e.preventDefault();
profile = "pictures/default.jpg";
username = $("#username").val();
email = $("#email").val();
bio = $("#bio").val();
newPass = $("#password").val();
oldPass = $("#oldPass").val();
first = $("#first").val();
last = $("#last").val();
// First an ajax request to upload the image as it requires separate request
$.ajax({
type: "POST",
url: "upload.php?upload&type=profile",
data: new FormData(this),
contentType: false,
cache: false,
processData: false,
success: function(resp) {
alert(resp);
},
error: function (resp) {
alert(resp);
}
});
// Now the updates in the profile
$.ajax({
type: "POST",
url: "update.php",
data: "mode=details&profile="+profile+"+&username="+username+"&email="+email+"&bio="+bio+"&password="+newPass+"&oldPass="+oldPass+"&first="+first+"&last="+last,
success: function(resp) {
// resp contains what is echoed on update.php
alert(resp);
}
});
return false;
});
If you are dealing with multiple forms on a page, or dynamically created forms then you will want to use
$(document).on('submit', 'form', function(e) {
...
});
Even better give your form a class for dynamic data
$(document).on('submit', '.myform', function(e) {
...
});

AJAX not submitting fom

I am working with a script wherein I should be able to submit a form without page reload with the help of AJAX. The problem is that the form is not submitted to the database. Any help would be appreciated. I had messed with the codes but nothing works for me.
Here is the javascript code:
<script type="text/javascript">
setInterval(function() {
$('#frame').load('chatitems.php');
}, 1);
$(function() {
$(".submit_button").click(function() {
var textcontent = $("#content").val();
var usercontent = $("#username").val();
var namecontent = $("#nickname").val();
var dataString = 'content=' + textcontent;
var userString = 'content=' + usercontent;
var nameString = 'content=' + namecontent;
if (textcontent == '') {
alert("Enter some text..");
$("#content").focus();
} else {
$("#flash").show();
$("#flash").fadeIn(400).html('<span class="load">Loading..</span>');
$.ajax({
type: "POST",
url: "chatitems.php",
data: {
dataString,
userString,
nameString
},
cache: true,
success: function(html) {
$("#show").after(html);
document.getElementById('content').value = '';
$("#flash").hide();
$("#frame").focus();
}
});
}
return false;
});
});
</script>
this is my form:
<form action="" method="post" name="form">
<input type="hidden" class="form-control" id="username" name="username" value="<?php echo $username; ?>" readOnly />
<input type="hidden" class="form-control" id="nickname" name="nickname" value="<?php echo $nickname; ?>" readOnly />
<input type="hidden" class="form-control" id="chat_role" name="chat_role" value="<?php echo $pm_chat; ?>" readOnly />
<input type="hidden" class="form-control" id="team" name="team" value="<?php echo $manager; ?>'s Team" readOnly />
<input type="hidden" class="form-control" id="avatar" name="avatar" value="<?php echo $avatar; ?>" readOnly />
<div class="input-group">
<input type="text" class="form-control" id="content" name="content" />
<span class="input-group-btn">
<input type="submit" name="submit" class="submit_button btn btn-primary" value="Post"></input>
</span>
</div>
</form>
and finally, this is my PHP code:
<?php
include('db.php');
$check = mysql_query("SELECT * FROM chat order by date desc");
if(isset($_POST['content']))
{
$content=mysql_real_escape_string($_POST['content']);
$nickname=mysql_real_escape_string($_POST['nickname']);
$username=mysql_real_escape_string($_POST['username']);
$ip=mysql_real_escape_string($_SERVER['REMOTE_ADDR']);
mysql_query("insert into chat(message,ip,username,nickname) values ('$content','$ip','$username','$nickname')");
}
$req = mysql_query('select * from chat ORDER BY date desc');
while($dnn = mysql_fetch_array($req))
{
?>
<div class="showbox">
<p><?php echo $dnn['username']; ?> (<?php echo $dnn['ip']; ?>): <?php echo $dnn['message']; ?></p>
</div>
<?php
}
?>
I know there is something wrong with my code somewhere but had spent few days already but no avail. Im hoping that someone would help.
UPDATE
The form is being submitted successfully with this code only data: dataString but when I added the nameString and the userString thats when everything doesnt work as it should. I tried messing around that code but still got nothing.
To find out what is wrong with this you need to establish that:
a) The click event is firing, which you could test by adding a console.log('something'); at the top of that function.
b) The AJAX function is working somewhat correctly, which again you could check by adding a console.log() in the success callback of the AJAX request. You can also check console for errors, e.g if the chatitems.php is 404'ing
c) That all the data you're collecting from the DOM e.g var textcontent = $("#content").val(); contains what you're expecting it to. Again console.log().
d) That the page you're calling is successfully processing the data you're sending across, so die() a print_r() of the $_POST values to check the data it's receiving is in the format your expecting. You also need to add some error handling to your mysql code: https://secure.php.net/manual/en/function.mysql-error.php (or better yet use PDO or MySQLi https://secure.php.net/manual/en/book.pdo.php), which will tell you if there's something wrong with your MySQL code. You can check the return of you're AJAX call (which would include any errors) by console.log(html) in your success callback.
Information you gather from the above will lead you to your bug.
If i understand right, it seem you try to bind event before the button is available. Try (depend on the version of JQuery you use) :
$(document).on('click, '.submit_button', function(){
...
});

jQuery openPopup modal doesn't close after submit

I've put a modal popup box for getting inputs and then stores via ajax. It's inserted values succesfully.. but the popup stills after submittion. i've try everything like window.close(); ... ('#modalname').hide(); but nothing works for me. please help me to fix this bug.
Here's my part of working code,
<!--css for display subject in row (starts)-->
<span class="b-messages__subject">
<span>
<a href="index.php?subject=<?php echo $results[$result]['subject']; ?>&username=<?php echo $results[$result]['username']; ?>#openModal" onclick="fetch_select(<?php echo $results[$result]["id"]; ?>);">
<?php echo "Reply"; ?>
</a>
</span>
</span>
<!--css for display subject in row (ends)-->
and then modal div is,
<!--Modal box starts-->
<div id="openModal" class="modalDialog" align="center">
<div>
X
<h2><strong>Reply Message</strong></h2>
<br>
<label><strong>Enter Your Message Here</strong></label>
<br>
<label><b>From:</b> <?php echo $user; ?></label>
<span id="content-info" class="info"></span>
<br/>
<!--set session username for hidden-->
<input type="hidden" name="username" id="username" value="<?php echo $user; ?>">
<textarea name="content" id="content" class="demoInputBox"></textarea>
<!--send fusername with hidden-->
<input type="text" name="fusername" id="fusername" value="<?php echo $_GET["username"] ?>">
<!--send subject with hidden-->
<input type="text" name="subject" id="subject" value="<?php echo $_GET["subject"] ?>">
<!--status init="0"-->
<input type="hidden" name="status" id="status" value="0">
<!--time-->
<input type="hidden" name="created" id="created" value='<?php echo date("Y-m-d H:i:s"); ?>'>
<br><br>
<input type="button" name="submit" id="but-sub" value="Send Message" onClick="add();" />
</div>
</div>
<!--Modal box ends-->
My js file contains:
function add() {
/*initialize valid and assign to function validate()*/
var valid = validate();
//alert(valid); returns true
//if function validate() returns valid.. then go away
if (valid){
$.ajax({
url: "add.php",
type: "POST",
data: {
username: $("#username").val(),
fusername: $("#fusername").val(),
subject: $("#subject").val(),
content: $("#content").val(),
status: $("#status").val(),
created: $("#created").val()}
});
}
}
I am not sure if you are using JSON, but you should definitely be checking the response for pass or fail. Try adding success after your data like this (doesn't include check for pass or fail, but should close modal upon success response of the AJAX):
$.ajax({
url: "add.php",
type: "POST",
data: {
username: $("#username").val(),
fusername: $("#fusername").val(),
subject: $("#subject").val(),
content: $("#content").val(),
status: $("#status").val(),
created: $("#created").val()
},
success: function (returndata) {
//try this first
$("#openModal").modal('hide');
//try this second and uncomment if you aren't using jquery/bootstrap modal
//$("#openModal").hide();
}
});
Put your form elements in a <form></form>.
The modal should close if form is submited.

auto submit form on pageload using AJAX and get html type result?

I'm trying to autosubmit a form on page load using ajax and then get the HTML (a bunch of divs that will be echo-ed on the AJAX URL) back to my AJAX page.
first off, my code auto submits the form but it will ignore the AJAX call so the user will be taken to the form's action page.
also, if I remove the auto submit code from my AJAX code and submit the form manually via the submit button I get nothing back from the AJAX URL page!
This is my entire code:
window.onload = function(){
document.forms['myformR'].submit()
// this is the id of the form
$("#myformR").submit(function() {
var url = "results.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
dataType: "html", //expect html to be returned
success: function (response) {
$("#prores").html(response);
}
});
return false; // avoid to execute the actual submit of the form.
});
}
any advise would be appreciated.
EDIT, THIS IS MY ajax PHP URL page:
<?php
session_start();
?>
<?php
include "config/connect.php";
$searchList = "";
$clause = " WHERE ";//Initial clause
$sql="SELECT *
FROM `yt`
INNER JOIN `ATTRIBUTES` ON yt.subcats=ATTRIBUTES.type";//Query stub
if(isset($_POST['submit'])){
if(isset($_POST['keyword'])){
foreach($_POST['keyword'] as $c){
if(!empty($c)){
##NOPE##$sql .= $clause."`".$c."` LIKE '%{$c}%'";
$sql .= $clause . " (ATTRIBUTES.sizes LIKE BINARY '$c' OR ATTRIBUTES.colors LIKE BINARY '$c' OR ATTRIBUTES.type LIKE BINARY '$c')";
$clause = " OR ";//Change to OR after 1st WHERE
}
}
$sql .= " GROUP BY yt.id ";
//print "SQL Query: $sql<br />"; //<-- Debug SQl syntax.
// Run query outside of foreach loop so it only runs one time.
$query = mysqli_query($db_conx, $sql);
//var_dump($query); //<-- Debug query results.
// Check that the query ran fine.
if (!$query) {
print "ERROR: " . mysqli_error($db_conx);
} else {
// Use $query inside this section to make sure $query exists.
$productCount = mysqli_num_rows($query);
$i=0; // count the output amount
if ($productCount > 0) {
while($row = mysqli_fetch_array($query, MYSQLI_ASSOC)){
$sizesOption ="";
$colorOption ="";
$id = $row["id"];
$product_name = $row["product_name"];
$details = $row["details"];
$details = preg_replace("/\\\\r\\\\n/", "", $details);
$price = $row["price"];
$category = $row["category"];
$manu = $row["manu"];
$sizez = $row["sizez"];
$colours = $row["colours"];
$colours = preg_replace('/\.$/', '', $colours);
$sizez = preg_replace('/\.$/', '', $sizez); //Remove dot at end if exists
$array = explode(',', $sizez);
$arrayC = explode(',', $colours); //split string into array seperated by ','
foreach($array as $value) //loop over values
{
//echo $value . PHP_EOL; //print value
$sizesOption .='<option>'.$value.'</option>';
}
foreach($arrayC as $valueC) //loop over values
{
//echo $value . PHP_EOL; //print value
$colorOption .='<option>'.$valueC.'</option>';
}
$searchList .= '<div align="center" class="mypro" style="position:relative; width:270px; height:470px; border:solid 1px #CCC; margin:10px; float:left; overflow:hidden; padding:5px;">
<a class="overlay" href="product.php?id='.$id.'"></a>
<!--<a class="overlayBtns" href="">Quick View</a>-->
<div class="overlayAdd">
<a style="font: bold 11px Arial;
text-decoration: none; background-color: #FFF; color: #333333; padding: 10px; border:none; border-radius:4px; width:120px; height:30px;" id="go" rel="leanModal" name="test" href=".test'.$id.'">Qick View <i style="color:#000; font-size:18px;" class="fa fa-eye"></i></a>
<div style="display:none; display:none; width:580px; height:auto; background-color:#FFF; border-radius:4px; padding:12px;" class="test'.$id.'">
<h2>'.$product_name.'</h2>
<p style="text-align:left;">'.$details.'</p>
<form id="form'.$id.'" class="form1" name="form1" method="post" action="cart.php">
<p>
<p style="text-align:left; font-weight:bold;">Size</p>
<select id="sizeSelect" name="sizeSelect" style="">
'.$sizesOption.'
</select>
<p style="text-align:left; font-weight:bold;">Colour</p>
<select id="colorSelect" name="colorSelect" style="">
'.$colorOption.'
</select>
</p>
<p style="text-align:left; font-weight:bold; width:100px; float:left;">Quantity</p>
<input min="1" type="number" id="quantity" name="quantity" value="1" />
</p>
<p>
<input type="hidden" name="pid" id="pid" value="'.$id.'" />
<input type="hidden" name="moneyPrice" id="moneyPrice" class="moneyPrice" value="" />
<input type="hidden" name="moneyCurreny" id="moneyCurreny" class="moneyCurreny" value="" />
<input style="background-color:#000; color:#FFF;" type="submit" value="ADD TO BASKET" />
</form></p>
<br><br>
View Item Full Details<br><br>
<div class="share-buttons" data-url="http://enzua.com/product.php?id='.$id.'" data-text="http://enzua.com/product.php?id='.$id.'"></div>
</div></div>
<img width="100%" src="product_images/'.$id.'Image1.jpg" alt="" />
<p style="padding:2px;">'.$product_name.'</p>
<p style="padding:2px;">'.$manu.'</p>
<div style="padding:5px;" class="price">
<div class="prod-price"><span class=money>£'.$price.'.00</span></div>
</div>
</div>';
}
}
}
}
}
?>
<?php
echo $searchList;
exit();
?>
AND THIS IS MY HTML FORM:
<form class="myformR" id="myformR" name="myformR" method="post" action="results.php">
<input type="hidden" name="keyword[]" value="dress" />
<input id="smt" type="submit" value="submit" name="submit" />
</form>
<div id="prores"></div>
use below code
$(window).load(function(){
// this is the id of the form
var url = "results.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data:$( "#myformR" ).serialize(),
dataType: "html", //expect html to be returned
success: function (response) {
$("#prores").html(response);
}
});
});
If I understand you problem correctly you just want to submit the form on page load and currently with your code it is not submitting via ajax.
can you please try the following code
$("#myformR").submit(function(e) {
e.preventDefault();
// your code
}
I guess what you need is this
$("#myformR").submit(function() {
var url = "results.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: new FormData( this ),
processData: false,
contentType: false,
dataType: "html", //expect html to be returned
success: function (response) {
$("#prores").html(response);
}
});
return false; // avoid to execute the actual submit of the form.
});
send the formdata to the backend with the information about the form
Hope this helps

Categories

Resources