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.
Related
I'm pretty sure it has to do with my core.js file with the ajax hashing url. But I'm trying to submit a form, but it's not submitting like I want it to. This is the core.js file:
// call init
$(init);
function init() {
ajax_page_handler();
page_load($(window.location).attr("hash")); // goto first page if #! is available
}
function page_load($href) {
if($href != undefined && $href.substring(0, 2) == '#/') {
// replace body the #content with loaded html
$('#content').load($href.substring(2), function () {
$('#content').hide().fadeIn('slow');
});
}
}
function ajax_page_handler() {
$(window).bind('hashchange', function () {
$href = $(window.location).attr("hash");
page_load($href);
});
// this allow you to reload by clicking the same link
$('a[href^="#/"]').live('click', function() {
$curhref = $(window.location).attr("hash");
$href = $(this).attr('href');
if($curhref == $href) {
page_load($href);
}
});
}
The live viewing is over at www.krissales.com. The form is here: http://www.krissales.com/#/media/5.Testing-1
Hit the link "Post Comment", then you'll type info in, then hit comment, but it just refreshes, but doesn't submit it.
The steps I've taken to solve it was in the comment file, in the form action field, I inserted the tag name="#content" simply because that's the name of my div that I'm submitting to.
The original stuff is on http://blog.krissales.com/article/7.Testing-3-man ( where you can actually post a comment, and it'll work)
But apparently it's not working. Do you guys have a clue as to what it is that I'm doing wrong? thanks for your help in advance!
<script type="text/javascript">
tinyMCE.init({
mode : "textareas",
theme : "simple"
});
</script>
<form action="#/media/article.php" name="#content" method="POST">
Name:
<br />
<input type="text" name="name" class="userpass"/>
<br /><br />
Comment:
<br />
<textarea id="elm1" name="comment" rows="7" cols="30" style="width: 500px;">
</textarea>
<br />
<input type="submit" name="submit" value="Comment" class="button" />
<input type="reset" name="submit" value="Reset" class="button" />
</form>
I noticed that you are not setting the ajax type on the file 'comment.php'.
you need...
$.ajax({
type: 'POST',
url: 'comment_ajax.php',
data: { form_name: name, form_comment: comment },
success: function(data) {
$('#new_comment').prepend(data);
// close modal box
// do other shit
// kthnxbai
}
});
If type is not specified, it defaults to a GET request which will not post data. :)
Your current core.js handles changes in the URL hash, and it reroutes any links with a hash to load that relative path into #content. What's missing is code to redirect form submits to do the same thing (add this to ajax_page_handler):
$('form').live('submit', function(e) {
var $action = $(this).attr('action');
if($action.substring(0, 2) == '#/') {
// replace the #content with result of the form post
$.ajax({
url: $action.substring(2),
type: $(this).attr('method'),
data: $(this).serialize(),
success: function(data) {
$('#content').html(data);
$('#content').hide().fadeIn('slow');
}
});
// stop the real form submit from happening
e.preventDefault();
}
});
You should change the action attribute of your form like this :
<form action="script-handling-comment-data.php#/media/article.php" name="#content" method="POST">
For the moment, you're sending the comment data to http://www.krissales.com/ and i think the main page doesn't handle the comment posting.
You seem to be handling links properly, but form submission isn't a link, you probably want to handle submission using $(form).submit(function(){ ... })
In your case, if you gave your form the id form1
$('#form1').submit(function(){
var keyValues = $(this).serializeArray();
var map = {};
for(i in keyValues)
{
var value = keyValues.value;
var name = keyValues.name;
map[name] = value;
}
$.post($(this).attr('action'),map,function(){
alert("Submitted values: " + $(this).serialize());
});
return false;
})
See serializeArray, $.post and .submit for more information
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/
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.
Good evening guys,
I'm trying to pass multiple checkbox values through AJAX and process them with a external .php script. Goal: delete multiple rows using checkboxes without refreshing the page.
Please assist me with passing the selected checkboxes into the datastring and putting them in the mysql command in the external .php file. This is the code so far:
The checkboxes:
<form name="frmMain" id="myForm" method="post" OnSubmit="return onDelete();">
<input class="checkbox_button_del" type="submit" id="buttondel" value="Delete" /> // submit to ajax
<input type="checkbox" class="cb-element" name="chkDel[]" id="chkDel<?=$i;?>" value="' .($id). '">
<input type="hidden" name="hdnCount" value="<?=$i;?>">
</form>
The AJAX:
$(function () {
$(".checkbox_button_del").click(function () {
var id = $(this).attr("id");
var dataString = 'id=' + id; //pass checkbox ids somehow
var parent = $(this).parents('tr:first');
$.ajax({
type: "POST",
url: "core/actions/delete_multiple.php",
data: dataString,
cache: false,
success: function () {
parent.fadeOut('300', function () {
$(this).remove();
});
$("#display").load("display.php")
}
});
return false;
});
});
The delete script:
// receive checkbox ids from ajax and delete rows
for($i=0;$i<count($_POST["chkDel"]);$i++)
{
if($_POST["chkDel"][$i] != "")
{
$strSQL = "DELETE FROM players ";
$strSQL .="WHERE id = '".$_POST["chkDel"][$i]."' ";
$objQuery = mysql_query($strSQL);
}
}
You can do this by putting all the checkboxes in a form. And then add the following line in your function:
datastring = $('#myform').serialize();
jQuery has this functionality built-in.
See: http://api.jquery.com/serialize/
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']