Send data via cURL without reloading page - php

In a facebook iframe page (not tab), I'd like to post data to an external API using cURL, but I would prefer if my form page didn't reload.
I'd like to have some jquery ajax happening ("submitting data" message on submission of the form and a success message on success of the curl_exec). I was thinking of creating a hidden iframe with a duplicate form and update values in that form on change events, but i don't know quite how I'd implement that exchange between PHP and jquery.
Is there a better way? Here's the code I'm working on:
UPDATED CODE TO RETURN FALSE --
Does not submit form data.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body class="fb_canvas-resizable <?php print $body_classes; ?>">
<?php echo $message; ?>
<div class="container">
<div class="header"></div>
<div class="wrapper">
<div class="content">
<div class="left">
<h1>Sign Up to Sign Off</h1>
<form name="signoff" action="curlsub.php" method="post">
<input id="api" type="hidden" name="API_KEY" value="key">
<div class="innerleft">
<input id="fname" type="text" name="fname" class="inputs" tabindex="1" /></br />
<label for="fname">First</label></br /></br /></br />
<input type="text" name="email" class="inputs" tabindex="3" /></br />
<label id="email" for="email">Email</label></br /></br /></br />
<label for="gender">Gender</label></br /></br />
<label for="gender">Age</label></br /></br /></br />
<label for="gender">Income</label></br /></br /></br />
</div>
<div class="innerright">
<input id="lname" type="text" name="lname" class="inputs" tabindex="2" /></br />
<label for="lname">Last</label></br /></br /></br />
<input id="password" type="password" name="password" class="inputs" tabindex="4" /></br />
<label for="email">Password</label></br /></br /></br />
<input type="radio" name="sex" value="male" selected="selected" tabindex="5" /> Male
<input type="radio" name="sex" value="female" tabindex="6" /> Female</br /></br />
<select name="age" tabindex="7" >
<option value=""></option>
<option value="baby">Baby</option>
<option value="teen">Teen</option>
<option value="young">Young</option>
<option value="old">Old</option>
</select><br /><br />
<select name="income" tabindex="8">
<option value=""></option>
<option value="none">None</option>
<option value="some">Some</option>
<option value="okay">Okay</option>
<option value="tons">Tons</option>
</select><br /><br />
<input id="zip" type="text" name="c5" class="zip" tabindex="9" /></br />
<label for="c5">Zip Code</label></br /></br />
<label for="mformat">Newsletter</label></br /></br />
<input type="checkbox" name="mformat" value="html" selected="selected" tabindex="10" /> HTML (iPhone, iPad, Droid)<br /><br />
<input type="checkbox" name="mformat" value="text" tabindex="11" /> TEXT (Best for Blackberry)
</div>
<div class="button"><input type="image" src="button.jpg" name="submit" value="yes"></div>
</form>
</div>
<div class="right">
<img src="logo.jpg" />
<p>Updating you on today and prepping you for tomorrow.</p>
www.url.com
</div>
<div class="clear">
</div>
<div class="logged clear">
<p>Logged in as Some Guy (not you?)</p>
</div>
</div></div>
<div class="footer"></div>
</div>
<script>
$(document).ready(function() {
//$('div.wrapper').fadeOut(0);
window.fbAsyncInit = function() {
FB.init({appId: 'app', status: true, cookie: true});
FB.Canvas.setSize();
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
});
$('#signoff').submit( function() {
var fname = $("input#fname").val();
var lname = $("input#fname").val();
var email = $("input#email").val();
var password = $("input#password").val();
var dataString = 'fname='+ fname + '&lame=' + lname + '&email=' + email + '&password=' + password;
// alert(dataString);
// return false;
$.ajax({
type: "POST",
url: "curlsub.php",
data: dataString,
success: function() {
//do some stuff
}
});
return false;
});
</script>
</body>
</html>
Currently this will successfully send the data to the external PHP API, but the iframe (or my whole file) reloads on submission (and displays "success" message).

What you want to do is issue an AJAX Post request on the submit event of your form. The success callback of that AJAX Post request should update your UI to alert the user that their post was sucessful.
$('#signoff').submit(
//Ajax post request here
//http://api.jquery.com/jQuery.post/
return false; //this stops your page from refreshing
);

Have you looked at http://api.jquery.com/jQuery.ajax/ or http://api.jquery.com/jQuery.post/
The following code should help you get started.
$.ajax({
type: 'POST',
url: url,
data: data,
success: success
dataType: dataType
});
Where
url is a string containing the URL to which the request is sent.
data is a map or string that is sent to the server with the request.
success is a callback function that is executed if the request succeeds. It should take three arguments: (data, textStatus, XMLHttpRequest)
dataType is the type of data expected from the server.

Related

No call to JavaScript function submitting form in Angular and PHP

There in nothing happen while I'm submitting the form, actually no call to the JavaScript function. Don't know why. I'm new to this.
My HTML page:
<html>
<head>
<title>Clear Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h3 align="center">Select Store</h3>
<br />
<div ng-app="myapp" ng-controller="usercontroller" ng-init="loadCountry()">
<select name="country" ng-model="country" class="form-control" ng-change="loadState()">
<option value="">Select Store</option>
<option ng-repeat="country in countries" value="Id">{{country.store_name}} (Store Id:{{country.id}})</option>
</select>
<br />
<div id="form" ng-if="country.includes('Id')">
<h4 align="center">Enter Date Range</h4> <br/>
<form ng-submit="submit_form()">
<input type="hidden" name="Storeid" value="{{country.id}}">
From Date:<input type="text" name="fromDate" placeholder="yyyy-mm-dd hh:mm:ss.ttt" required/>
To Date:<input type="text" name="toDate" placeholder="yyyy-mm-dd hh:mm:ss.ttt" required/><br>
<br><button type="submit" class="btn btn-primary">Submit</button>
</form> </div>
<br />
</div>
</div>
</div>
</body>
My JavaScript code is:
<script>
var app = angular.module("myapp",[]);
app.controller("usercontroller", function($scope, $http){
$scope.loadCountry = function(){
$http.get("loadStore.php")
.success(function(data){
$scope.countries = data;
})
}
$scope.submit_form = function (){
$http({
method : 'POST',
url : 'clearallData.php',
storeid : this.Storeid, //forms user object
fromdate : this.fromDate,
todate : this.toDate
})
.success(function(data) {
$scope.message = data.message;
});
}
});
</script>
There are a couple of things wrong with your code.
First, you're not actually sending any data with your POST request. Second, you ought to use $scope instead of this to access your data (well, at least as long as you're not using the recommended controllerAs-syntax). Third, success is deprecated. Use promises instead.
All of that comes down to the following changes:
$scope.submit_form = function (){
return $http({
method : 'POST',
url : 'clearallData.php',
data: {
storeid : $scope.Storeid, //forms user object
fromdate: $scope.fromDate,
todate : $scope.toDate
}
}).then(function(response) {
$scope.message = response.data.message;
});
}
and in the view change this:
From Date:<input type="text" name="fromDate" ng-model="fromDate" placeholder="yyyy-mm-dd hh:mm:ss.ttt" required/>
To Date:<input type="text" name="toDate" ng-model="toDate" placeholder="yyyy-mm-dd hh:mm:ss.ttt" required/><br>
Whether this will actually fix your issue, I cannot say, since you havn't provided any error messages or similar information that might suggest what actually goes wrong.
<html>
<head>
<title>Clear Data</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
</head>
<body>
<br /><br />
<div class="container" style="width:600px;">
<h3 align="center">Select Store</h3>
<br />
<div ng-app="myapp" ng-controller="usercontroller" ng-init="loadCountry()">
<!-- I change here, because select has ngOptions in angular , so you dont use ng-repeat-->
<select ng-change="loadState(name.id)" ng-model="name" name="name" id="name" class="form-control"
ng-options="country as country.name for country in countries track by country.id" >
<option disabled="disabled" value="">Select Country</option>
</select>
<br />
<div id="form" ng-show="country_status">
<h4 align="center">Enter Date Range</h4> <br/>
<!-- Pay Attention here -->
<form ng-submit="submit_form()">
<input type="hidden" name="Storeid" value="{{ countryId }}">
From Date:<input type="text" name="fromDate" ng-model="fromDate" placeholder="yyyy-mm-dd hh:mm:ss.ttt" required/>
To Date:<input type="text" name="toDate" ng-model="toDate" placeholder="yyyy-mm-dd hh:mm:ss.ttt" required/><br>
<br><button type="submit" class="btn btn-primary">Submit</button>
</form>
<!-- Pay Attention here stop -->
</div>
<br />
</div>
</div>
</div>
<script>
var app = angular.module("myapp",[]);
app.controller("usercontroller", function($scope, $http){
$scope.country_status = false;
$scope.loadCountry = function(){
$http.get("loadStore.php")
.success(function(data){
$scope.countries = data;
})
/* $scope.countries = [{
'id':1,
'name': 'india1'
},{
'id':2,
'name': 'india2'
}]*/
};
$scope.submit_form = function (){
console.log('Hello ', $scope.countryId,$scope.fromDate, $scope.toDate);
//My scope display here, if yours is not please copy and paste this code in your project directory and test it.
return $http({
method : 'POST',
url : 'clearallData.php',
data: {
storeid : $scope.countryId, //forms user object
fromdate: $scope.fromDate,
todate : $scope.toDate
}
}).then(function(response) {
$scope.message = response.data.message;
});
};
$scope.loadState = function (countrySelected) {
console.log('countrySelected', countrySelected);
$scope.country_status = true;
$scope.countryId = countrySelected;
console.log('$scope.countryId', $scope.countryId);
}
});
</script>
</body>
</html>

Multiple arrays to a JSON array to PHP via AJAX

I have a form
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div><label for="post[uname]">Username <em>*</em></label> <input id="post[uname]" type="text" name="uname" value="" /></div>
<p class='note' id='err[Name]'></p>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
I have two arrays post and err. I'm trying to send them to php and then in php it will json_encode the array and print it on the screen like so:
{
"err": {
"uname": "Please enter a user name"
}
"post": {
"uname": ""
}
}
or this is if the user did enter a name:
{
"post": {
"uname": "Bob Ross"
}
}
There could be multiple fields for post and err but it should still follow the same suite.
How do I send the data to php, I understand it's some sort of serializeArray but it doesn't format it properly when I do:
JSON.stringify($("#ajax-form").serializeArray())
A jsfiddle to full html:
https://jsfiddle.net/dzv8ttjn/1/
Your best bet is to call .serialize(); on the form which will give you something like: user-name=some%20name&email=some%20emale&gender=Female&interests=Software
Send that to the PHP script, and have the script create the format of the response while looping over the $_POST array. Something like the below would work:
(note that I've changed your id's to be more sensible and updated the jQuery version used)
<?php
if(count($_POST)>0){
$response = ['err'=>[], 'post'=>[]];
foreach($_POST as $key => $value)
{
$response['post'][$key]=$value;
if(trim($value) == '') $response['err'][$key]='Please enter a '.$key;
}
echo json_encode($response);
exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title> Lab4: Form Validation with AJAX,JQuery,JSON and PHP</title>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">
</script>
<script type="text/javascript">
$("#ajax-form").on('submit', function(event) {
event.preventDefault();
var dataString = $(this).serialize();
$.ajax({
type: "POST",
// url: "page.php", // add this line to send to some page other than the this one
data: dataString,
success: function(response) {
if (response) {
alert('test worked');
}
},
error: function(xhr, status, error) {
console.log(xhr);
}
});
});
</script>
</head>
<body>
<div id="wrapper">
<h2>Form Validation with AJAX,JQuery,JSON and PHP</h2>
<div class="form-container">
<span id="ajax-message"></span>
<form id="ajax-form" onsubmit="return false;">
<p class="legend">All fields marked with an asterisk are required.</p>
<fieldset>
<legend>User Details</legend>
<div>
<label for="uname">Username <em>*</em></label>
<input id="uname" type="text" name="user-name" value="" />
<p class='note' id='name-error'></p>
</div>
<div>
<label for="password">Email Address <em>*</em></label>
<input id="password" type="text" name="email" value="" />
<p class='note' id='password-error'></p>
</div>
<div>
<label for="post[gender]">Gender <em>*</em></label>
<input type="radio" name="gender" value="Male" class="form-check-input" id="Male" required> Male
<input type="radio" name="gender" value="Female" class="form-check-input" id="Female" required> Female
<p class='note' id='gender-error'></p>
</div>
<div>
<label for="interests">Interests<em>*</em></label>
<input type="checkbox" name="interests" value="Music" class="form-check-input" id="Music"> Music
<input type="checkbox" name="interests" value="Software" class="form-check-input" id="Software"> Software
<input type="checkbox" name="interests" value="Hardware" class="form-check-input" id="Hardware"> Hardware</div>
</fieldset>
<div class="buttonrow">
<input type="submit" value="Submit This Form via AJAX" class="button" />
<input type="button" value="Start Again" class="button" />
Refresh this Page
</div>
</form>
</div>
<h3>JSON Array</h3>
<pre id='debug'></pre>
</div>
</body>
</html>

form submit don't call ajax function phonegap

I'm developing a mobile app with phonegap and I have a form to register new users. In the broswer(chrome and firefox), the form works fine when correctly
filled, and show errors if something wrong. I have an alert('work!'); in the start of function to check if was called, in browsers the alert appears but in the app no. What can be?
Ps: I already have <access origin=""> to my website where's the php file of form is.
EDIT:
the form:
<form id="cadastro" method="post">
<input type="text" style="height:30px;margin-bottom:10px;margin-top:10px;font-size:18px" name="nome" id="textinput-2" placeholder="Nome" required>
<input type="text" style="height:30px;margin-bottom:10px;font-size:18px" name="email" id="textinput-1" placeholder="Email" required>
<div id="email_erro"></div>
<input type="password" style="height:30px;margin-bottom:10px;font-size:18px" name="senha" id="password" placeholder="Senha" autocomplete="off" required>
<input type="password" style="height:30px;margin-bottom:10px;font-size:18px" name="repetir_senha" id="re_password" placeholder="Repetir senha" autocomplete="off">
<div id="senha_erro"></div>
<fieldset data-role="controlgroup" style="margin-left:5%" data-type="horizontal" data-mini="true">
        <input type="radio" name="sexo" id="radio-choice-c" value="m" checked="checked" required>
        <label for="radio-choice-c">Masculino</label>
        <input type="radio" name="sexo" id="radio-choice-d" value="f" required>
        <label for="radio-choice-d">Feminino</label>
</fieldset>     
<div style="margin-left:3.5%;margin-right:4%;">
<input type="checkbox" name="newsletter" id="checkbox-mini-0" value="1" data-mini="true">
    <label for="checkbox-mini-0">Quero receber as ofertas e novidades</label>
<input type="checkbox" name="termo" id="checkbox-mini-1" data-mini="true" required>
    <label for="checkbox-mini-1">Aceito os Termos de Uso e Política de privacidade</label>
<button type="submit" class="ui-btn ui-shadow ui-corner-all" id="termo" style="float:none;margin-left:2%">Criar conta</button>
</div>
</form>
the function:
<script>
alert('entrou no script');
$('#cadastro').submit(function(){
var valor = $('#cadastro').serialize();
$.ajax({
type: 'POST',
url: 'cadastro',
dataType: "json",
data: valor
}).success(function(response){
alert('retornou função');
if (response.sucesso) {
window.localStorage["email"] = response.dados.email;
window.localStorage["nome"] = response.dados.nome;
window.localStorage["sexo"] = response.dados.sexo;
window.localStorage["id"] = response.dados.id;
//window.localStorage["UID"] = data.uid;
window.location = "logado.html";
} else {
alert("Verifique seus dados");
$('#email_erro').html(response.erro_email);
$('#senha_erro').html(response.erro_repetir_senha);
//window.location("main.html");
}
});
return false;
});
</script>
I believe that your problem is because you are running your javascript before the phonegap framework has loaded. Try using the event listener below, and then place your javascript in the corresponding function.
document.addEventListener("deviceReady", deviceReady, false);
function deviceReady() {
// PhoneGap has loaded - your code goes here
}

How to pass radio button value to php page using angularjs

I am showing radio button in html
<body ng-app="myApp" ng-controller="MainCtrl">
<form enctype="multipart/form-data" id="FileUploadForm" name="FileUpload" ng-submit="submitData(FileUpload)" novalidate>
<div style="text-align: left;font-size: 20px;padding: 10px;color: #487eaa;">
<font> Upload Resume</font>
</div>
<div class="file-upload">
<input type="text" id="name" name="name" ng-model="name" />
<br /><br />
<input type="text" id="place" name="place" ng-model="place" />
<br /><br />
<label class="control-label" for="Dilation" style="padding:3px 0;">Dilation</label>
<label>Yes <input type="radio" name="dilation" id="dilation" ng-model="dilation" value="Yes" ng-checked="false" /></label>
<label>No <input type="radio" name="dilation" id="dilation" ng-model="dilation" value="No" ng-checked="false" /></label>
<br /><br />
<label class="control-label" for="NCT" style="padding:3px 0;">NCT</label>
<label>Right <input type="radio" name="nct" id="nct" ng-model="nct" value="Right" ng-checked="false" /></label>
<label>Left <input type="radio" name="nct" id="nct" ng-model="nct" value="Left" ng-checked="false" /></label>
<br /><br />
<input type="file" id="i_file" name="file" ng-file-select="onFileSelect($files)" multiple />
<br /><br />
<input type="submit" id="submit" name="submit" value="submit" ng-disabled="FileUploadForm.$invalid" />
<br /><br />
<div ng-bind="dilation" ng-hide="dilation"></div>
<div ng-bind="nct" ng-hide="nct"></div>
</div>
</form>
</body>
And here is my angular controller
angular.module('myApp', ['angularFileUpload'])
.controller('MainCtrl', function($scope, $http, $upload) {
$scope.onFileSelect = function($files) {
$scope.message = "";
for (var i = 0; i < $files.length; i++) {
var file = $files[i];
console.log(file);
$scope.upload = $upload.upload({
url: 'upload.php',
method: 'POST',
data: {name: $scope.name,place: $scope.place, dilation: dilation, nct: nct },
file: file
}).success(function(data, status, headers, config) {
$scope.message = data;
}).error(function(data, status) {
$scope.message = data;
});
}
};
});
And here is my php code(upload.php)
$result = array("filename" => $_FILES["file"],"name" => $_POST['name'],"place" => $_POST['place'],"dilation" => $_POST['dilation'],"nct" => $_POST['nct']);
echo json_encode($result);
Here is a fiddle : http://jsfiddle.net/aabyv4kx/
and getting response like this
name:qqq,place:eeee,dilation:{\"ng339\":8},nct:{\"ng339\":10}
I am new to angularjs please help me sort this.

Jquery redirect after submit to 1 page

I have a form. This form will submit data to 2 different pages. After submit data to hidd.php I will redirect user to index.php. At the same time after submit data to hidd.php, data will be submitted to ns.php. I don't want to wait for output from both page just quickly redirect user after submit data to hidd.php. So that was the question, how to redirect user without waiting for output after submit. Why I want to do this? It's a long story, I even thought about using curl >> Send php variable to two pages
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>Example</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
function submitForm() {
$.ajax({
type:'POST',
url: 'hidd.php',
data:$('#ContactForm').serialize(),
});
$.ajax({
type:'POST',
url: 'ns.php',
data:$('#ContactForm').serialize(),
});
return false;
}
</script>
</head>
<body>
<form id="ContactForm" onsubmit="return submitForm();">
Your subdomain: <input type="text" name="subdomain" value="" /><br />
Your ns1: <input type="text" name="ns1" value="" /><br />
Your ns2:<br /> <input type="text" name="ns2" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit" /><br />
<div class="form_result"> </div>
</form>
</body>
</html>
You can use the $.post method. I'm not sure the structure of your php files but you can handle the posted data however you like.
html change from:
<form id="ContactForm" onsubmit="return submitForm();">
Your subdomain: <input type="text" name="subdomain" value="" /><br />
Your ns1: <input type="text" name="ns1" value="" /><br />
Your ns2:<br /> <input type="text" name="ns2" value="" />
<br /><br />
<input type="submit" name="submit" value="Submit" /><br />
<div class="form_result"> </div>
</form>
to:
<form id="ContactForm">
Your subdomain: <input type="text" name="subdomain" value="" id="subDomain" /><br />
Your ns1: <input type="text" name="ns1" value="" id="ns1" /><br />
Your ns2:<br /> <input type="text" name="ns2" value="" id="ns2" />
<br /><br />
<input type="button" name="submit" value="Submit" id="submitButton" /><br />
<div class="form_result"> </div>
</form>
the javascript:
$(document).ready(function(){
$('#submitButton').click(function(){
var subDomain = $('#subDomain').val();
var ns1 = $('#ns1').val();
var ns2 = $('#ns2').val();
$.post('hidd.php', {
subDomain : subDomain,
ns1 : ns1,
ns2 : ns2
});
$.post('ns.php', {
subDomain : subDomain,
ns1 : ns1,
ns2 : ns2
}, function(){
location.href="index.php";
});
});
});
changing the button from a submit to a button will stop the automatic redirect so you don't have to return false. Then you are free to redirect when you want.
You could do this:
$.ajax({ /** params **/ });
$.ajax({ /** params **/ });
location.href='index.php';

Categories