Update Twitter with AJAX-powered form - php

I'm trying to make an AJAX form that will update a twitter status when updated. I have the form working currently with php, but am not sure how to add AJAX functionality.
Here's the form:
<form id = "yourwhisper" method = "post" >
<label for="whisper">Enter your status update</label>
<textarea id="whisper" name="whisper" rows="2" cols="50" required></textarea>
<label class="error" for="whisper" id="whisper_error">Must be no more than 140 characters.</label>
<input id="lat" name="lat" style = "display:none"></input>
<input id="lon" name="lon" style = "display:none"></input>
<button type="submit" id = "submit">Pass it on</button>
</form>
This is the php which I had as the form action (it calls a php function from a twitter api library). I've now moved it to form-manager.php:
$t->update($_POST["whisper"], false, $_POST["lat"], $_POST["lon"]);
Finally, this is the jQuery code that adds the AJAX functionality. It takes the text for the update, along with the geolocation data, and passes it to the form-manager.php file in the form of the 'dataString'.
<script type="text/javascript" charset="utf-8">
$(function() {
$('.error').hide();
$(".submit").click(function() {
// validate and process form here
$('.error').hide();
var whisper = $("textarea#whisper").val();
var lat= $("input#lat").val();
var lon = $("input#lon").val();
if (whisper == "") {
$("label#whisper_error").show();
$("textarea#whisper").focus();
return false;
}
var dataString = 'whisper='+ whisper + '&lat=' + lat + '&lon=' + lon;
//alert (dataString);return false;
$.ajax({
type: "POST",
url: "form-manager.php",
data: dataString,
success: function() {
// alert ("form sent");
});
}
});
return false;
});
});
</script>
My problem is, how do I then get form-manager.php to take that info and put it into the 3 variables it needs to update twitter?

the dataString should be available to PHP as $_POST['dataString']. It is only a single var that contains a string. You should explode it.
Or if you want you can set the data property of the ajax method like { whisper: "Foo", lat: "fooLat" } so they will show up like $_POST['whisper'] and $_POST['lat']

Related

I need to save the state of the toggle in database

I am using jquery to get the state of the toggle, I want to send that variable to my controller using twig, this is what I had done
<form method="post" enctype="multipart/form-data">
Sync: <br><div class="toggle-switch toggle-switch--green">
<input type="checkbox" class="toggle-switch__checkbox" id="togBtn" value='{{switchstatus}}' name = "sync">
<i class="toggle-switch__helper"></i></div><br>
<input type="submit" value="Update">
In Jquery
var switchStatus = false;
$("#togBtn").on('change', function() {
if ($(this).is(':checked')) {
switchStatus = $(this).is(':checked');
}
else {
switchStatus = $(this).is(':checked');
}
console.log(switchStatus);
$.ajax({
type: "POST",
url: 'name.html.twig',
data: switchStatus
});
});
I am getting value as empty
How do I pass my value of switchStatus in jquery to value option in twig HTML?
You need to send information to the PHP script via jQuery AJAX, the PHP script to sanitize user input/ do user check ups and then save the information into the database.

PHP AJAX MySQL Insert Date from form is entering as: 12/31/1969

I have read several of the posts regarding the PHP date inserting into MySQL as 12/31/1969, but not seeing how to do that with AJAX.
My data/form flow:
- Use a datepicker to select date (Y-m-d)
- Submit form
- Passes through AJAX form in Header
- Is passed to a Processing page to INSERT into db.
*****MY AJAX FORM IN THE HEADER:*****
<script><!--BEGIN: AJAX PROCESS FORM-->
$(document).ready(function() {
$("#subformgeneral").click(function() {
// IF VISIBLE CHECKBOX IS CHECKED THEN = Y ELSE = N
if ($('#usersalevisible').is(":checked"))
{
var user_salevisible = 'Y';
} else {
var user_salevisible = 'N';
}
// END CHECKBOX CONDITIONAL
var user_title = $("#title").val();
var user_startdate = $("#startdate").val();
var user_enddate = $("#enddate").val();
var user_restrictions = $("#salerestrictions").val();
var user_numsellers = $("#numsellers").val();
var user_form = $("#formid").val();
var user_saleid = $("#saleID").val();
$.post("usr-update-sale-process-2.php",{title:user_title,startdate:user_startdate,enddate:user_enddate,salerestrictions:user_restrictions,numsellers:user_numsellers,salevisible:user_salevisible,formid:user_form,saleID:user_saleid},function(data){
$("#result").html(data);
});
});
});
</script>
My DATE INPUT field from my form:
<!-- Start Date -->
<label class="control-label" for="username">Start Date</label>
<div class="controls">
<input type="text" id="datepicker" name="startdate" placeholder="Start Date" class="input-xlarge form-control" value="12/31/1969">
</div>
<input type="hidden" value="formgeneral" id="formid">
<input name="saleID" type="hidden" id="saleID" value="3262" />
<input class="btn btn-primary" type="submit" name="subformgeneral" id="subformgeneral" value="Update General" />
I read an article from here regarding how to do StrToTime conversion, and that worked... on a regular form, but somehow it gets lost when passing through the AJAX form.
I do not have my Processing page code here, where I am at the moment, but it just receives my AJAX POST for STARTDATE, and INSERTS into MySQL.
I assume some sort of conversion has to take place on the Processing page (and I have tried, all I know to do), but not sure how, exactly.
You should handle the success error outcomes.
var user_title = $("#title").val();
var user_startdate = $("#startdate").val();
var user_enddate = $("#enddate").val();
var user_restrictions = $("#salerestrictions").val();
var user_numsellers = $("#numsellers").val();
$.ajax({
url: "usr-update-sale-process-2.php",
type: "POST",
data: {
user_title: user_title,
user_startdate: user_startdate,
user_enddate: user_enddate,
user_restrictions: user_restrictions,
user_numsellers: user_numsellers
},
cache: false,
success: function(data) {
// Success message
},
error: function(data) {
// Fail message
},
});
Things to note: data the key is what the server will look for. Example:
$_POST['user_title'] will be equal to the var user_title = $("#title").val();
Also you can return true and false from the server which will be success and error respectively.

Ajax call only if the jquery validation is valid

I have a form and ajax call.data are filled in form and goes to remote at the same time user is created in my database using ajax call.but the problem is with validation,which validation should apply here
for example i apply any jquery validation i need to test if the form is valid and then i can call ajax if the form is valid other wise the database will be filled with blank data
i tried with bvalidator but i don't know how to detect the form is valid or invalid using any jquery validator library
<form id="inform" action="http://site.com">
<input type="text" id="name" />
<input type="text" id="email" />
<input type="button" name="subaction" id="infuse" />
</form>
<script language ="javascript" type = "text/javascript" >
$na= jQuery.noConflict();
$na(document).ready(function(){
$na('#infuse').click(function(){
var name= $na('#name').val();
var email = $na('#email').val();
$na.ajax({
type: "POST",
url: '<?php bloginfo('template_url')?>/user_create.php',
data: 'name='+name+'&email='+email,
cache: false,
success: function(result){
jQuery('.err_msg').html(result);
jQuery("#inform").submit();
}
});
});
});
</script>
You could do something like this
<script language ="javascript" type = "text/javascript" >
$na= jQuery.noConflict();
var name;
var email;
var options10 = {
// shows or hides error all messages container after validation completes
onAfterAllValidations: function(elements, formIsValid){
// if validation failed
if(!formIsValid)
callAjax();
else{
//do something
}
}
};
function callAjax(){
$na.ajax({
type: "POST",
url: '<?php bloginfo('template_url')?>/user_create.php',
data: 'name='+name+'&email='+email,
cache: false,
success: function(result){
jQuery('.err_msg').html(result);
jQuery("#inform").submit();
}
});
}
$na(document).ready(function(){
$('#inform').bValidator(options10);
$na('#infuse').click(function(){
name= $na('#name').val();
email = $na('#email').val();
});
});
</script>
I haven't checked this, but hopefully , this works. The important point is, you could use the callbacks : onAfterAllValidations.

JQuery's ajax post request does not work as it's supposed to be

The page's link is: localhost/mysite/create-user
This is the code:
<form class="form-horizontal" name = "signUp1F" id = "signUp1F">
<input class="input-xlarge focused" name="pskil" id ="pskil" type="text" placeholder = "Doctor, Trainer, Human Resource etc.">
<input type="hidden" name="neoid" id="neoid" value="<?php echo $neoid; ?>" />
<span><button id = "plus" class="btn btn-success">Plus</button></span>
<div id="skillsAdded"></div>
</form>
The jquery code:
<script type="text/javascript">
$('#plus').click( function(event){
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
The purpose is this: user enters a skill value to the input, clicks the Plus button, an ajax request is sent to add the skill to the database. And the code that handles this request is on localhost/mysite/add-skill.
But things go wrong. When I click the "plus" button, it goes to the page localhost/mysite/create-user?pskil=php&neoid=53. What can possibly make this direction? I've been working on this issue for almost 2 hours and I cannot manage to handle it.
The issue is that your button tag submit your form. Here is a updated JavaScript source that you can use. jQuery got a built in preventDefault() method for events. This will for an example prevent the button to submit the form.
<script type="text/javascript">
$('#plus').click( function(event){
event.preventDefault();
var pskil = $('#pskil').val();
var neoid = $('#neoid').val();
if( !pskil){
alert( "Please write a skill.");
return false;
}
$.ajax({
type: 'post',
url: "localhost/mysite/add-skill",
data: { pskil: pskil, neoid: neoid},
success: function( response){
$('#skillsAdded').append( pskil + "<br>");
return false;
}
});
});
</script>
Tryout: http://jsfiddle.net/3A7Mg/1/

Uploading image via AJAX along with username and email address

I am having some trouble with my file upload script. The HTML is as follows:
<form method="post" name="imgsubmit" id="contact_form" action="PHP/imgupload.php" enctype="multipart/form-data">
<label id="namelabel" for="username">Your name:</label><input id="username" type="text" name="username" rel="req">
<label id="labelemail" for="imgemail">E-mail:</label><input id="imgemail" type="email" name="imgemail" rel="req">
<label id="filelabel" for="file">Your photo:</label><input id="file" type="file" name="file">
<input id="imgsubmit" type="submit" name="submit" value="SUBMIT"></form>
I have a jquery validation script as which checks the username and email fields to see if they are valid, and returns a white border around them if they are not entered:
$(function () {
$('#contact_form').submit(function (e) {
e.preventDefault();
var form = $('#contact_form');
var post_url = form.attr('action');
var post_data = form.serialize();
var submit_form = false;
var req_fields = $('input[rel=req]');
var field, pcount = 0;
req_fields.each(function () {
field = $(this).val();
if (field == '' || field == 'Required') {
$(this).css('border', '1px solid white').val('');
pcount += 1;
} else {}
});
if (pcount == 0) {
submit_form = true;
}
if (submit_form) {
$.ajax({
type: 'POST',
url: post_url,
data: post_data,
success: function (msg) {
$(form).fadeOut;
form.html(msg).fadeIn();
}
});
}
});
});
The problem is that the username gets submitted to the php script, the email gets submitted to the php script, but the image doesn't get uploaded. I'm aware that AJAX now supports image uploading and that the form.serialize() is likely the root cause of the problem, but have not been able to edit this code correctly to support the image submission.
How can I adjust this code to include the image to be submitted to the php?
`if (window.FormData)`
check this and file must be `
file = $('#elemet').files.
and ajax option should be data: FormData,
where formdata = new FormData();
I like to use the jQuery Form Plugin for this kind of stuff, you just need to bind your form submittal when the DOM is ready for it to work. The example bellow is providing a success callback, but there are other events you could use, like error, beforeSubmit, and so forth:
$('#contact_form').ajaxForm(function() {
alert("Thank you for your data!");
});
It supports both regular input values and also file uploads (in older browsers it will fake an ajax file upload using iframes), and if your browser can handle it you can even display a progress bar.

Categories