Ajax Post Error Loading Page - php

I have a form in which Ajax is used to send data to a php file.
THE DATA SENDS PROPERLY...EVERYTHING WORKS FINE...
BUT an "Error loading page" message pops up (using jquerymobile)
html file
<div data-role="page" id="cc">
<div data-role="header">
<h1>Home</h1>
</div>
<div data-role="content">
<form id="cname" align="left" action="post">
<label for="name">Name:</label>
<input type="text" id="name" name="name" value="" />
<input type="submit" value="Submit" data-inline="true">
</form>
<div id="result" style="visibility: hidden"></div>
</div>
</div>
<script type="text/javascript">
$("#cname").submit(function (e) {
e.preventDefault();
$.ajax({
url: 'http://www.clubbedin.isadcharity.org/createclub.php',
crossDomain: true, //set as a cross domain requests
type: 'post',
data: $("#cname").serialize(),
success: function (data) {
$("#result").html(data);
},
});
});
</script>
php file
header("access-control-allow-origin: *");
$name = $_POST['name'];

Your form must also have have this attribute:
data-ajax="false"
Without it jQuery Mobile will initialize its own ajax logic for form posting and you don't want that. Read more about it here or read my other answer on how to properly handle forms in jQuery Mobile.

Try adding this in your JavaScript:
jQuery.support.cors = true;

Try adding
Access-Control-Allow-Methods: GET, POST, OPTIONS
Access-Control-Allow-Credentials: true
Access-Control-Allow-Headers: Content-Type, *
to your header

Related

FormData not posting data to php backend script

I have this form
<form id="home" class="validate-form" method="post" enctype="multipart/form-data">
<!-- Form Item -->
<div class="form-group">
<label>How much money do you need? (USD)</label>
<div class="input-group">
<div class="input-group-addon">USD</div>
<input id="moneyAmount" type="number" name="amount" class="form-control slider-control input-lg" value="100000" min="10000" max="1000000" data-slider="#moneySlider" required>
</div>
<div id="moneySlider" class="form-slider" data-input="#moneyAmount" data-min="10000" data-max="1000000" data-value="100000"></div>
</div>
<!-- Form Item -->
<div class="form-group">
<label>How long? (months)</label>
<div class="input-group">
<input id="monthNumber" type="number" name="months" class="form-control slider-control input-lg" value="10" min="6" max="12" data-slider="#monthSlider" required>
<div class="input-group-addon">months</div>
</div>
<div id="monthSlider" class="form-slider" data-input="#monthNumber" data-min="6" data-max="12" data-value="10"></div>
</div>
<div class="form-group">
<label>Telephone Number</label>
<!-- Radio -->
<input type="number" name="telephone" class="form-control" required/>
</div>
<!-- Form Item -->
<div class="form-group">
<label>3 Months Bank or Paypal </label>
<!-- Radio -->
<input type="file" name="statements" class="ml btn btn-primary btn-lg" /><span>Upload</span>
</div>
<!-- Form Item -->
<div class="form-group">
<label>Monthly repayment</label>
<span id="formResult" class="form-total">USD<span>262.99</span></span>
</div>
<div class="form-group form-submit">
<button type="submit" class="btn-submit btn-lg"><span>Send a request!</span></button>
</div>
</form>
that i am using to post a file and some data via formData. This is the jquery code
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
var formData = new FormData($(this)[0]);
$.ajax({
url: 'http://example.com/home.php',
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
return false;
});
and finally the php script
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
$rawData = file_get_contents("php://input");
return print_r($rawData);
?>
On the client side, the console.log(data) is empty. Why am i not able to get the posted data?.
Actually php://input allows you to read raw POST data but
php://input does not work when enctype="multipart/form-data"
for detailed info :
http://php.net/manual/en/wrappers.php.php
<?php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST');
header("Access-Control-Allow-Headers: X-Requested-With");
echo '<pre>'l
// for upload data
print_r($_FILES);
echo '<br>';
// for posted data
print_r($_POST);
echo '</pre>';
?>
jQuery supported get all form data with function serialize or serializeArray.
In your code use
$( "#home" ).on( "submit", function( event ) {
event.preventDefault();
var formData = $( "#home" ).serialize();
$.ajax({
url: 'http://example.com/home.php',
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data)
},
cache: false,
contentType: false,
processData: false
});
});
In PHP use var_dump($_REQUEST) to get all input without file type. With file type you can read PHP Upload File
Form which you are sending through ajax is not correct.
You can give your whole form to FormData() for processing
var form = $('#home')[0]; // You need to use standard javascript object here
var formData = new FormData(form);
use this formData to send with ajax

PHP image upload through Ajax serialize()

File upload through ajax serialize():
<form id="addform" class="form-horizontal" enctype="multipart/form-data" >
<div class="form-group">
<label for="link" class="control-label col-xs-3">Image</label>
<div class="col-xs-6">
<input id="file" name="file" type="file" class="form-control">
</div>
</div>
</form>
AJAX CODE using serialize():
$('#save11').click(function(){
$.ajax({
type : "POST",
url : "page/add-journal.php",
data :$('#addform').serialize(),
success : function(data)
{
alert(data);
window.location.href="home-page.php";
}
});
});
Here PHP code:
<?php
include '../dbConnection.php';
$tmp=$_FILES['file']['tmp_name'];
$serverpath="upload/".$_FILES['file']['name'];
$file=$_FILES['file']['name'];
move_uploaded_file($tmp,$serverpath);
$sql="insert into journal set file='".$file."'";
$query=mysql_query($sql);
?>
Only give me solution using serialize() only. If not so give me best solution.
I have made some changes in your code.. you can use below code for uploading images using ajax
<form id="addform" class="form-horizontal" enctype="multipart/form-data" >
<div class="form-group">
<label for="link" class="control-label col-xs-3">Image</label>
<div class="col-xs-6">
<input id="file" name="file" type="file" class="form-control">
</div>
<input type="submit" name="save" value="save" />
</div>
</form>
<script>
$('#addform').submit(function(e) {
e.preventDefault();
var data = new FormData(this); // <-- 'this' is your form element
$.ajax({
url: 'page/add-journal.php',
data: data,
cache: false,
contentType: false,
processData: false,
type: 'POST',
success: function(data) {
alert(data);
window.location.href = "home-page.php";
}
});
});
</script>
Note:
you haven't provided that how you submit your form, so I have put a submit button
You are using mysql functions, but they are officially deprecated now from php, you should use mysqli or PDO.
Form id in HTML is addform and in ajax you are using #addformkey. You will have to change the id at one place. I doubt this will work though.
only give me solution using serialize () only
https://api.jquery.com/serialize/
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls, such as <input>, <textarea>, and <select>: $( "input, textarea, select" ).serialize();
I doubt it can serialize a file.

Passing variable data between jQuery and PHP using AJAX shorthand

I'm trying to create a search feature that searches a database based on the criteria a user has entered. Right now, I'm just trying to get the jQuery variable data into PHP. I've decided to use the shorthand AJAX $.post method because this is just a demo project. I know there are numerous similar questions like mine, but I have yet to find an answer to any of them that I can use.
So what I'm trying to do is, the user will click on a drop down menu and select an option. AJAX then sends the selected value to the PHP file and the PHP will eventually perform a database search based on what was selected. The issue is, in PHP, I'm getting a string of "Search" when the data is parsed and I echo it but when I do a console log on the variable that was sent, I'm getting the correct text. Can anyone tell me where I'm going wrong?
Here's what I have so far.
AJAX
$("#search_form").on("submit", function(ev){
ev.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
console.log(data);
})
})
PHP
ob_start();
require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo $criteria;
HTML
<form id="search_form" method="post">
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search" id="search" />
<input type="submit" class="button" value="Search_Now" />
</fieldset>
As Requested
Here is a fiddle of the drop down menu to show how it works.
http://jsfiddle.net/xvmxc0zo/
Your form is being submitted via default form submission; the ajax call is misplaced, it should be within the submit handler, which should prevent default form submission.
Note that I have removed both name and id attributes from the submit button; you do not need them. Just let the submit button do it's job and listen for the submit event on the form where you would then use event.preventDefault(); to make sure the form does not submit, then you can make your ajax call.
$("#searchBy").on("click", ".option", function(){
$('#search').val( $(this).text() );
});
$('form').on('submit', function(e) {
e.preventDefault();
$.post("../php/test.php", $(this).serialize(), function(data){
//jsonData = window.JSON.parse(data);
console.log( data);
})
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="hidden" name="search" id="search" />
<input type="text" name="search_text" id="search_text" />
<input type="submit" class="button" value="Search" />
</fieldset>
</form>
In your PHP use echo $criteria; instead of echo json_encode($criteria);.
I'd suggest to use the way of jQuery documentation to check changes in your drop down.
$( "select" ).change(function () {
$( "select option:selected" ).each(function() {
$.post("../php/test.php", {search: $(this).text()}, function(data){
jsonData = window.JSON.parse(data);
});
});
})
You are getting "Search" on the PHP side because that is the value of your submit button.
You want the post to occur when you click on an option? Try adjusting your selector as follows:
$("#searchBy .option").on("click", function () {
var search = $(this).text().trim();
$.post("../php/test.php", { search: search }, function (data) {
jsonData = window.JSON.parse(data);
})
});
I think your header.php is provoking the error. I created a test file myself with your code and that works perfectly fine:
<?php
if($_POST)
{
ob_start();
//require("../includes/header.php");
$criteria = $_POST["search"];
ob_clean();
echo json_encode($criteria);
exit;
}
?>
<fieldset id="search_by">
<div class="select" name="searchBy" id="searchBy">
<p>Search By...</p>
<div class="arrow"></div>
<div class="option-menu">
<div class="option">Airport Identifier</div>
<div class="option">Top Rated</div>
<div class="option">Instructor</div>
<div class="option">Malfunctions/Maneuvers</div>
</div>
</div>
<input type="text" name="search_text" id="search_text" />
<input type="submit" name="search" id="search" class="button" value="Search" />
</fieldset>
<script src="http://code.jquery.com/jquery-1.11.1.min.js"></script>
<script>
$("#searchBy").on("click", ".option", function(){
var search = $(this).text();
$.post("<?=$_SERVER['PHP_SELF']?>", {search: search}, function(data){
jsonData = window.JSON.parse(data);
console.log(jsonData); //Prints the correct string
})
});
</script>

How do I prevent AJAX from sending me to the top of the page?

I have the following signup form near the bottom of a new website. As soon as the AJAX response loads, the page skips to the top of the page. As far as I can tell, I have included "return false" correctly. What am I missing? Thank you!
## index.php ##
<script type="text/javascript" src="mailing-list.js"></script>
<div class="signup container">
<form id="signup-form" action="<?=$_SERVER['PHP_SELF']; ?>" method="get">
<fieldset>
<legend><h2 style="align:center;">Enter Your Email Address</h2></legend>
<div class="row">
<div class="offset4 span3">
<input class="email" type="text" name="email" id="email" />
</div>
<div class="span1">
<input type="submit" name="submit" value="Join" class="btn btn-large btn-primary" />
</div>
</div>
<div id="response">
<? require_once('inc/store-address.php'); if($_GET['submit']){ echo storeAddress(); } ?>
</div>
</fieldset>
</form>
</div>
## and mailing-list.js ##
$(document).ready(function() {
$('#signup-form').submit(function() {
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
$(document).ready(function() {
$('#signup-form').submit(function(e) {
e.preventDefault();
// update user interface
$('#response').html('Adding email address');
// Prepare query string and send AJAX request
$.ajax({
url: 'inc/store-address.php',
data: 'ajax=true&email=' + escape($('#email').val()),
success: function(msg) {
$('#response').html(msg);
}
});
return false;
});
});
I doubt it is executing the default form submit behavior. Prevent it byt using the preventDefault method.
$(function(){
$('#signup-form').submit(function(e) {
e.preventDefault();
//your existing code goes here
});
});
You need to prevent the form from submitting the data (even if it is to the same file). Otherwise the page will reload before your ajax call is done. You do this with .preventDefault();
Try
...
$('#signup-form').submit(function(event) {
event.preventDefault();
// update user interface
...

Submit multiple forms with jQuery php mysql

I have any page for answer/question. i retrieve list of question for admin. admin see this. now i need to send answer to each question. so i for each question put textarea and form with post action. now i need to when send answer of question message, if send message to external php files = true; of message(ID) remove(jquery slideup effect). for this i have jquery submit form code ( without refresh page ) but I have big problem. this worked ONLY with one form ! and not worked for all list form ( question + answer form ) . how to worked my code for multiple form ? I chose the right way?
html code :
<form action="insert.php?id=42" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=45" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=48" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
<form action="insert.php?id=50" id="forms" method="POST" name="form">
<div id="box">
<div class="messagequestion"></div>
<div class="messagereply"><textarea></textarea><input type="submit" class="submit" name="submit" value="submit"></div>
</div>
</form>
Thanks
Your major issue is probably that you are trying to reuse ids. All the forms have the id of "forms" and you are also sharing the id "box".
All ids should uniquely identify an element. Use a class when you need to classify an element. I'd recommend you change id="forms" on all the forms to class="reply_form" and then also change id="box" on all the divs to class="reply_box". Then change styles set for #forms and #box to those set for .reply_form and .reply instead.
EDIT - tweaks made in jsfiddle after some discussion with the OP.
http://jsfiddle.net/gvnfg/5/
just change the selector. id attribute must be unique in html
$("[name='form']").submit(function() {
$this = $(this);
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: $(this).serialize(),
cache: false,
beforeSend: function() {
$('#loading').show();
$('#result').hide();
},
success: function(data) {
if(data==1){
$('#loading').hide();
$('#result').fadeIn('slow').html("ok");
$('#result').addClass('true');
$this.slideUp(1000);
}
else {
$('#loading').hide();
$('#result').fadeIn('slow').html(data);
$('#result').addClass('errors');
}}
});
e.preventDefault();
return false;
});
use Jquery .each() method:
$(document).ready(function() {
$('#forms').each(function() {
this.submit(function() {
$.ajax({ ... });
});
});
})

Categories