jQuery Mobile: How to correctly submit form data - php

This is a jQuery Mobile question, but it also relates to pure jQuery.
How can I post form data without page transition to the page set into form action attribute. I am building phonegap application and I don't want to directly access server side page.
I have tried few examples but each time form forwards me to the destination php file.

Intro
This example was created using jQuery Mobile 1.2. If you want to see recent example then take a look at this article or this more complex one. You will find 2 working examples explained in great details. If you have more questions ask them in the article comments section.
Form submitting is a constant jQuery Mobile problem.
There are few ways this can be achieved. I will list few of them.
Example 1 :
This is the best possible solution in case you are using phonegap application and you don't want to directly access a server side php. This is an correct solution if you want to create an phonegap iOS app.
index.html
<!DOCTYPE html>
<html>
<head>
<title>jQM Complex Demo</title>
<meta name="viewport" content="width=device-width, height=device-height, initial-scale=1.0"/>
<link rel="stylesheet" href="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.css" />
<style>
#login-button {
margin-top: 30px;
}
</style>
<script src="http://www.dragan-gaic.info/js/jquery-1.8.2.min.js"></script>
<script src="http://code.jquery.com/mobile/1.2.0/jquery.mobile-1.2.0.min.js"></script>
<script src="js/index.js"></script>
</head>
<body>
<div data-role="page" id="login" data-theme="b">
<div data-role="header" data-theme="a">
<h3>Login Page</h3>
</div>
<div data-role="content">
<form id="check-user" class="ui-body ui-body-a ui-corner-all" data-ajax="false">
<fieldset>
<div data-role="fieldcontain">
<label for="username">Enter your username:</label>
<input type="text" value="" name="username" id="username"/>
</div>
<div data-role="fieldcontain">
<label for="password">Enter your password:</label>
<input type="password" value="" name="password" id="password"/>
</div>
<input type="button" data-theme="b" name="submit" id="submit" value="Submit">
</fieldset>
</form>
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
</div>
</div>
<div data-role="page" id="second">
<div data-theme="a" data-role="header">
<h3></h3>
</div>
<div data-role="content">
</div>
<div data-theme="a" data-role="footer" data-position="fixed">
<h3>Page footer</h3>
</div>
</div>
</body>
</html>
check.php :
<?php
//$action = $_REQUEST['action']; // We dont need action for this tutorial, but in a complex code you need a way to determine ajax action nature
//$formData = json_decode($_REQUEST['formData']); // Decode JSON object into readable PHP object
//$username = $formData->{'username'}; // Get username from object
//$password = $formData->{'password'}; // Get password from object
// Lets say everything is in order
echo "Username = ";
?>
index.js :
$(document).on('pagebeforeshow', '#login', function(){
$(document).on('click', '#submit', function() { // catch the form's submit event
if($('#username').val().length > 0 && $('#password').val().length > 0){
// Send data to server through ajax call
// action is functionality we want to call and outputJSON is our data
$.ajax({url: 'check.php',
data: {action : 'login', formData : $('#check-user').serialize()}, // Convert a form to a JSON string representation
type: 'post',
async: true,
beforeSend: function() {
// This callback function will trigger before data is sent
$.mobile.showPageLoadingMsg(true); // This will show ajax spinner
},
complete: function() {
// This callback function will trigger on data sent/received complete
$.mobile.hidePageLoadingMsg(); // This will hide ajax spinner
},
success: function (result) {
resultObject.formSubmitionResult = result;
$.mobile.changePage("#second");
},
error: function (request,error) {
// This callback function will trigger on unsuccessful action
alert('Network error has occurred please try again!');
}
});
} else {
alert('Please fill all nececery fields');
}
return false; // cancel original event to prevent form submitting
});
});
$(document).on('pagebeforeshow', '#second', function(){
$('#second [data-role="content"]').append('This is a result of form submition: ' + resultObject.formSubmitionResult);
});
var resultObject = {
formSubmitionResult : null
}

I have run into same issue where I am calling another .php page from my index.html.
The .php page was saving and retrieving data and drawing a piechart. However I found that when piechart drawing logic was added, the page will not load at all.
The culprit was the line that calls the .php page from my index.html:
<form action="store.php" method="post">
If I change this to:
<form action="store.php" method="post" data-ajax="false">
, it will work fine.

On using PHP and posting data
Use
data-ajax = "false" is the best option on <form> tag.

Problem is that JQuery Mobile uses ajax to submit the form. The simple solution to this is to disable the ajax and submit form as a normal form.
Simple solution: form action="" method="post" data-ajax="false"

Related

CORS not be changed in html or php file

I am using a free hosting site so that I can show my group the website I am currently working on. A problem I keep see occurring is that in the console there's the error:
XMLHttpRequest cannot load http://error.hostinger.eu/?. No
'Access-Control-Allow-Origin' header is present on the requested
resource. Origin 'http://sampleclickinggame.esy.es' is therefore not
allowed access.
The URL is: http://sampleclickinggame.esy.es/index.html
The URL is: http://sampleclickinggame.esy.es/index.php
Both of the files produce the error
I have tried to use the PHP method of it but that doesn't work, I have also added an ajax version but that doesn't do anything. I mainly want to keep the file format as html, but if I need to change it I will.
UPDATE
The code:
<?php
header("Access-Control-Allow-Origin: *");
?>
<!DOCTYPE html>
<html>
<head>
<title>IO Chat</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/1.7.3/socket.io.js"></script>
<script src="jquery.js"></script>
<script>
$.ajax({
url: "sampleclickinggame.esy.es",
type: method,
// This is the important part
xhrFields: {
withCredentials: true
},
// This is the important part
data: data,
success: function (response) {
// handle the response
},
error: function (xhr, status) {
// handle errors
}
});
</script>
<style>
body{
margin-top: 30px;
}
#messageArea{
display: none;
}
</style>
</head>
<body>
<div class="container">
<div id="userFormArea" class="row">
<div class="col-md-12">
<form id="userForm">
<div class="form-group">
<label>Enter UserName</label>
<input class="form-control" id="username" />
<br />
<input type="submit" class="btn btn-primary" value="Login" />
</div>
</form>
</div>
</div>
<div id="messageArea" class="row">
<div class="col-md-4">
<div class="well">
<h3>Online Users</h3>
<ul class="list-group" id="users"></ul>
</div>
</div>
<div class="col-md-8">
<div class="chat" id="chat"></div>
<form id="messageForm">
<div class="form-group">
<label>Enter Message</label>
<textarea class="form-control" id="message"></textarea>
<br />
<input type="submit" class="btn btn-primary" value="Send Message" />
</div>
</form>
</div>
</div>
</div>
<script>
$(function(){
var socket = io.connect();
var $messageForm = $('#messageForm');
var $message = $('#message');
var $chat = $('#chat');
var $messageArea = $('#messageArea');
var $userFormArea = $('#userFormArea');
var $userForm = $('#userForm');
var $users = $('#users');
var $username = $('#username');
$messageForm.submit(function(e){
e.preventDefault();
socket.emit('send message', $message.val());
$message.val('');
});
socket.on('new message', function(data){
$chat.append('<div class="well"><strong>'+data.user+'</strong>: '+data.msg+'</div>');
});
$userForm.submit(function(e){
e.preventDefault();
socket.emit('new user', $username.val(), function(data){
if(data){
$userFormArea.hide();
$messageArea.show();
}
});
$username.val('');
});
socket.on('get users', function(data){
var html = '';
for(var i = 0;i < data.length;i++){
html += '<li class="list-group-item">'+data[i]+'</li>';
}
$users.html(html);
});
});
</script>
</body>
</html>
For some reason it keeps redirecting to an error page for my hosting site and that's where the error is coming from. And as for the Uncaught SyntaxError: Unexpected token < error from the looks of it, it's from the error page aswell
Any thoughts on how to fix this?
Your problem is that you are trying to make a Cross Origin Request and the server you are calling is not configured to respond to CORS request from the domain you are sending.
Your html is located at http://sampleclickinggame.esy.es
but you are trying to make a server call to http://error.hostinger.eu/?
See how the domains are different? For security reasons the Browser does not allow this. When it sees a CORS request, it sends an OPTIONS request to the server first to see if the server will accept the request from the different domain. If it will, then the request will proceed as normal. In your case it looks like the server is not configured to receive a request from http://sampleclickinggame.esy.es
Your solution is to enable CORS on the server you are making the request to, or you must host everything on the same server/domain.
One last thought:
can I see the javascript that is being used to make this network call? I have seen the browser throw this CORS error a lot when it is actually a problem with the javascript request. The one thing that makes me think you might have javascript error is that the Console on your web page is saying this: "Uncaught SyntaxError: Unexpected token <"

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>

JQuery Page Refreshes

I working on a page with some JQuery and Kendo UI. This is my first JQuery project and I getting things along. However, my page refreshes for some reason. This is what I am trying to do: I have a text field where I can enter a search term and when I press a button, the query is sent to a php file and some json info will pop up. So far, I can get it to return something, but the page refreshs and all the data is gone.
code:
*<!DOCTYPE html>
<html>
<head>
<title>Search</title>
<link href="styles/kendo.common.min.css" rel="stylesheet" />
<link href="styles/kendo.default.min.css" rel="stylesheet" />
<script src="js/jquery.min.js"></script>
<script src="js/kendo.web.min.js"></script>
</head>
<body>
<div id="example">
<form id="search">
<label for="search">Search For:</label>
<input type="text" id="txtSearch" name="q">
<button type="submit" id="submit">Find</button>
</form>
<div id="grid">
</div>
</div>
<script>
$(function() {
$("#grid").kendoGrid({
dataSource: {
transport: {
read: "include/showsearch.php"
},
schema: {
data: "data"
}
},
columns: [{field: "id"},{field: "name"},{field: "season"}]
});
$("#submit").click(function(){
var textVal = $("#txtSearch").val();
var dynamicURL = "include/showsearch.php?show_name=" + textVal;
var grid = $("#grid").data("kendoGrid");
alert("sdf123");
grid.dataSource.transport.options.read.url = dynamicURL;
grid.dataSource.read();
alert("sdf");
});
});
</script>
</body>
</html>*
NOTE:
I used the alert functions to stop and see how the page reacts. How do I get the page from refreshing?
The reason this is happening is that the default action for your submit button is still occurring; submitting the form.
It's probably best to catch the form submission event rather than the button click as hitting Enter in a text field may also submit the form.
You will also need to prevent the default event action.
Change this
$("#submit").click(function(){
to this
$('#search').on('submit', function(e) {
e.preventDefault();
// and the rest of your code here

Send JSON to server side using Ajax

I have a html form and I am making the json object as:
var JSobObject=
'{"name":"'+personObject.GetPersonName()+
'","about":"'+personObject.GetAbout()+
'","contact":"'+personObject.GetPersonContact()+'"}';
(Here personObject holds the form data)
trying to post it to Server.php as:
if (window.XMLHttpRequest) {
xmlhttp=new XMLHttpRequest();
}
else {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
//var url = "organizePeople.php?people=" + escape(people.toJSONString());
xmlhttp.open("POST","ServerJSON.php?person="+JSobObject,true);
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send(JSobObject);
xmlhttp.onreadystatechange=function() {
if(xmlhttp.readyState==4) {
alert(xmlhttp.responseText);
}
}
I am not getting any response from the server.php In my server i am doing this
$person = $_POST['person'];
$objArray = json_decode($person);
print_r($objArray);
Can anyone help me that what I am doing wrong? I am in the learning stage. Just using JS/AJAX I want to prepare JSON and send it to server and get the response of the object datas.
Thanks in advance
I prefer that, you do this with jQuery. It is JavaScript based library to do things (like this) easier.
$.post({
url: "Server.php",
data: JSobObject,
dataType: "json"
}).done(function(msg) {
alert(msg);
});
You need to download jQuery - of course - to get code to working!
2 thoughts I'm having.
First of all, I'd sugest you move the xmlhttp.onreadystatechange assigment to above the send() call.
Secondly, have you checked with firebug if you're getting any reponse?
Have you tried calling your php page directly, rather than through ajax?
I'm not 100% sure, but probably you'll want something like
$data = json_decode($_POST, true);
$person = $data['person'];
The reason being you're post data is entirely a JSON encoded text string, so you'll need to decode the entire post before you can access the data separately.
You should check the rawpost from php first,
$_POST maybe fill slashes Automatedly
Use this code will help you
<!DOCTYPE html>
<html>
<head>
<title>Servlet Example</title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script src="js/jquery.serializeJSON.min.js"></script>
</head>
<body>
<div class="jumbotron text-center">
<h1>Submit form Data to Database in JSON</h1>
</div>
<div class="container">
<div class="row">
<div class="col-sm-3"></div>
<div class="col-sm-5">
<h3>Enter the Details : </h3>
<form name="myform" id="myform">
<div class="form-group">
<label for="fullName">Name:</label>
<input type="text" name="fullName" class="form-control">
</div>
<div class="form-group">
<label for="email">Email:</label>
<input type="email" name="email" class="form-control">
</div>
<div class="form-group">
<label for="subject">Subject:</label>
<input type="text" name="subject" class="form-control">
</div>
<div class="form-group">
<label for="mark">Mark:</label>
<input type="number" name="mark" class="form-control">
</form>
</div>
<button type="submit" class="btn btn-success " id="submitform">Submit</button>
</div>
<div class="col-sm-3"></div>
</div>
<script>
$(document).ready(function(){
$("#submitform").click(function(e)
{
var MyForm = JSON.stringify($("#myform").serializeJSON());
console.log(MyForm);
$.ajax(
{
url : "<your url>",
type: "POST",
data : MyForm,
});
e.preventDefault(); //STOP default action
});
});
</script>
</body>
</html>

hiding login form with Jquery

I created login from that when clicking submit button sends variables to login_success.php page.but I want to make that when I click submit button login form will be close. I can close form using Jquery
<script type="text/javascript">
$(document).ready(function(){
$("button").click(function(){
$(".loginform").hide();
});
});
</script>
But this time form does not sends request to .php file. I made it like addin script to .php file and then redirected to index.html site.It also good but I can see reflection.How can I combine them?
this is my form
<div class="loginform">
<form action="php/login.php" method="post" id="login">
<fieldset class="loginfield">
<div>
<label for="username">User Name</label> <input type="text" id="username" name="username">
</div>
<div>
<label for="password">Password</label> <input type="password" id="password" name="password">
</div>
</fieldset>
<button type="submit" id="submit-go" ></button>
</form>
</div>
Edit
I used function as NAVEED sad .I installed FireBug in firefox and I can see that my form validation works normal.It sends and request to login.php But I cant make any change on my form.It does not close or $arr values not shown on div tags.
You should use JSON/AJAX combination:
Downlod jQuery
If your form look like this:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="ajax.js"></script>
<div id='errors'></div>
<div class='loginform' id='loginform'>
<form action="php/login.php" method="post" id="login">
Username:<input type="text" id="username" name="username">
Password:<input type="password" id="password" name="password">
<button type="submit" id="submit-go" value='Login'></button>
</form>
</div>
Your jQuery Code in ajax.js file to submit the form and then get data from 'php/login.php' in JSON and fill the required DIVs. If login is id of the form.
jQuery('#login').live('submit',function(event) {
$.ajax({
url: 'php/login.php',
type: 'POST',
dataType: 'json',
data: $('#login').serialize(),
success: function( data ) {
for(var id in data) {
jQuery('#' + id).html(data[id]);
}
}
});
return false;
});
your login.php file as described in form action attribute:
$username = $_POST['username'];
$password = $_POST['password'];
if( $username and $password found in database ) {
// It will replace only id='loginform' DIV content
// and login form will disappear
$arr = array ( "loginform" => "you are logged in" );
} else {
// It will replace only id='errors' DIV content
$arr = array ( "errors" => "You are not authenticated. Please try again" );
}
echo json_encode( $arr );
More Detail:
How to submit a form in ajax/json:
General jquery function for all forms
Try submit method
$("button").click(function(){
$("form.loginform").submit().hide();
});
PS You do know that applying onclick handler to all <button> elements on the page is bad idea, right?
$(document).ready(function(){
$("button").click(function(){
$(".loginform").hide();
return false;
});
});

Categories