jquery form plugin does not working - ajax

i am a newbie programmer.I am stuck for two days with a simple code.I try to use jquery form plugin for submitting a form to another page and get a feedback from that page.The problem is the plugin is not working.the form is submitted as normaly without feedback.Here is the code
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<div id='preview'></div>
<form action='ajaxcall.php' id='upload_pic' enctype='multipart/form-data' method='post'>
<input type='file' id='pic' name='picture'>
<input type='submit' id='sub'>
</form>
var options=
{
target:'#preview',
url:'ajaxcall.php'
};
$(document).ready(function(){
$("#sub").click(function(){
$('#preview').html("<img src='images/loader.gif' alt='Loading.....'/>");
$('#upload_pic').ajaxForm(options).submit();
});
});
Here is my ajaxcall.php page code
if(!empty($_FILES['picture']['size']))
{
echo "<img src='images/197.jpg'>";
}
Expectation was the echoed image would feddback but the page is simply redirected to ajaxcall.php page.ajaxForm() function is not working.But why?please help.Thanks in advance.

Just replace your submit button for a normal one, because you are already submiting the form programatically from your click handler, so replace your following html:
<input type='submit' id='sub'>
for this one:
<input type='button' id='sub'>

use these codes instead of your script codes. sorry for the late answer
$(document).ready(function(){
$("#sub").click(function(){
var options=
{
target:'#preview',
url:'ajaxcall.php'
};
$('#preview').html("<img src='images/loader.gif' alt='Loading.....'/>");
$('#upload_pic').ajaxForm(options).submit();
});
});

Related

Play framework write Action with Ok(...) that doesn't load new page

Play framework 2.4.x. A button is pressed on my home page that executes some code via Ajax, and returns its results beneath the button without loading a new page. The results wait for a user to input some text in a field and press "submit". Those results Look like this:
<li class="item">
<div>
<h3>Email: </h3>
<a>#email.tail.init</a>
<h3>Name: </h3>
<a>#name</a>
</div>
<div>
<h3>Linkedin: </h3>
<form class="linkedinForm" action="#routes.Application.createLinkedin" method="POST">
<input type="number" class="id" name="id" value="#id" readonly>
<input type="text" class="email" name="email" value="#email" />
<input type="text" class="emailsecondary" name="emailsecondary" value="" />
<input type="text" class="name" name="email" value="#name" />
<input type="text" class="linkedin" name="linkedin" value="" />
<input type="submit" value="submit" class="hideme"/>
</form>
</div>
<div>
<form action="#routes.Application.delete(id)" method="POST">
<input type="submit" value="delete" />
</form>
</div>
</li>
Along with some jquery that slides up a li after submission:
$(document).ready(function(){
$(".hideme").click(function(){
$(this).closest('li.item').slideUp();
});
});
However, since a form POST goes inside an Action that must a return an Ok(...) or Redirect(...) I can't get the page to not reload or redirect. Right now my Action looks like this (which doesn't compile):
newLinkedinForm.bindFromRequest.fold(
errors => {
Ok("didnt work" +errors)
},
linkedin => {
addLinkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
if (checkURL(linkedin.url)) {
linkedinParse ! Linkedin(linkedin.id, linkedin.url, linkedin.email, linkedin.emailsecondary, linkedin.name)
Ok(views.html.index)
}else{
Ok(views.html.index)
}
}
)
Is it possible to return Ok(...) without redirecting or reloading? If not how would you do a form POST while staying on the same page?
EDIT: Here is my attempt at handling form submission with jquery so far:
$(document).ready(function(){
$(".linkedinForm").submit(function( event ) {
var formData = {
'id' : $('input[name=id]').val(),
'name' : $('input[name=name]').val(),
'email' : $('input[name=email']).val(),
'emailsecondary' : $('input[name=emailsecondary]').val(),
'url' : $('input[name=url]').val()
};
jsRoutes.controllers.Application.createLinkedin.ajax({
type :'POST',
data : formData
})
.done(function(data) {
console.log(data);
});
.fail(function(data) {
console.log(data);
});
event.preventDefault();
};
});
This is an issue with the browser's behavior on form submission, not any of Play's doing. You can get around it by changing the behavior of the form when the user clicks submit.
You will first want to attach a listener to the form's submission. You can use jQuery for this. Then, in that handler, post the data yourself and call .preventDefault() on the event. Since your javascript is now in charge of the POST, you can process the data yourself and update your page's HTML rather than reloading the page.
What you need is use ajax to submit a form, check this: Submitting HTML form using Jquery AJAX
In your case, you can get the form object via var form = $(this), and then start a ajax with data from the form by form.serialize()
$.ajax({
type: form.attr('method'),
url: form.attr('action'),
data: form.serialize(),
success: function (data) {
alert('ok');
}
});
In order to accomplish this task, i had to use play's javascriptRouting
This question's answer helped a lot.
I'm not experienced with jquery so writing that correctly was difficult. For those that find this, here is my final jquery that worked:
$(document).ready(function(){
$("div#results").on("click", ".hideme", function(event) {
var $form = $(this).closest("form");
var id = $form.find("input[name='id']").val();
var name = $form.find("input[name='name']").val();
var email = $form.find("input[name='email']").val();
var emailsecondary = $form.find("input[name='emailsecondary']").val();
var url = $form.find("input[name='url']").val();
$.ajax(jsRoutes.controllers.Application.createLinkedin(id, name, email, emailsecondary, url))
.done(function(data) {
console.log(data);
$form.closest('li.item').slideUp()
})
.fail(function(data) {
console.log(data);
});
});
});
Note that my submit button was class="hideme", the div that gets filled with results from the DB was div#results and the forms were contained within li's that were class="item". So what this jquery is doing is attaching a listener to the static div that is always there:
<div id="results">
It waits for an element with class="hideme" to get clicked. When it gets clicked it grabs the data from the closest form element then sends that data to my controller via ajax. If the send is successful, it takes that form, looks for the closest li and does a .slideUp()
Hope this helps

Input Button as Input image will not work

On my website i have a button which when clicked takes you to one of two random youtube videos. However i would like to change this to a image in stead of a button.I have tried to change it to a INPUT type="image" but this doesn't work. Here is the code i am using.
<SCRIPT language="JavaScript">
<!--
function get_random()
{
var ranNum= Math.floor(Math.random()*2);
return ranNum;
}
function getaGame()
{
var whichGame=get_random();
var game=new Array(2)
game[0]= "https://www.youtube.com/watch?feature=player_detailpage&v=NcFQF3PZFRk#t=722s";
game[1]= "https://www.youtube.com/watch?v=klBAW4MQffU";
location.href = game[whichGame];
}
//-->
</SCRIPT>
<FORM name="form1">
<center>
<INPUT type="button" onClick="getaGame()" >
</center>
</FORM>
Thanks for any help
An onclick event can be fired from any element. Here are some examples!

document.getElementById("id").value = ""; Not working

The code for example document.getElementById("id").value="value"; is not working. I have assigned it on a function to replace the current value of the textbox once the page is loaded.
here is my code
<script type="text/javascript">
function rplace(){
document.getElementById('idtext').value="New Value";
}
onload=rplace
</script>
<form>
<input type="text" id="idtext" name="idtext" value="">
</form>
use jquery insteat of javascript.
$(document).ready(function(){ $("#idtext").val("New Value")});
Refer this

Ajax form perfect until inside another page

I have a page which uses ajax to submit a comment form, add it to a db, then redisplay the page, hopefully without reloading the page its on.
If I access the script on it's own it works great, yet when I load it into another page it doesn't add the data and also refreshes the page on submit, which I want to avoid, which is the whole point of doing things this way.
Anyway, here's how I load the page:
<div id="wall_comments" class="msgs_holder"></div>
<script type="text/javascript">
$('#wall_comments').load('/pages/comment.php', { wl_id:"<?=$wl_id?>" });
</script>
and then the page itself with jquery code:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js" type="text/javascript"></script>
<div style="width:100%; overflow:auto;">
<form method=post>
<input type="text" class="inp" name="comment" id="comment">
<input type=submit value="do it" name="action" onclick="update()">
<input type=hidden name="wl_id" value="<?=$_REQUEST[wl_id]?>" id="wl_id">
<input type=hidden name="user_id" value="<?=$userfromcookie?>" id="user_id">
</form>
</div>
<script type="text/javascript">
function update(){
var wl_idVal = $("#wl_id").val();
var commentVal = $("#comment").val();
var user_idVal = $("#user_id").val();
$.ajax({
type: "POST",
url: "/pages/comment.php",
cache: false,
data: { submit: "", wl_id: wi_idVal, comment: commentVal, user_id: user_idVal }
});
}
</script>
And finally enter info into db (I know this should be mysqli and it will be)
if(isset($_POST['action'])){
$wl_id = mysql_real_escape_string($_POST['wl_id']);
$comment = mysql_real_escape_string($_POST['comment']);
$user_id = mysql_real_escape_string($_POST['user_id']);
$addcomment = mysql_query("insert into list_wall (
event_id,
user_id,
comment
) VALUES (
'$wl_id',
'$user_id',
'$comment'
) ",$db);
if(!$addcomment) { echo 'result error add comment'; echo mysql_error(); exit; } // debug
}
The problem is when you click the submit button, the page is submitted and the function update couldn't work. You have to cancel the default submit mechanism by using return false;
<input type=submit value="do it" name="action" onclick="update() return false;">
Another thing.
The onclick on the submitbutton will not work as excpected if the submit is caused without clicking the button.
For example mobile safari on iPhone can submit forms directly without triggering the button.
If you add UmairP's version of the onclick to the form element as an onsubmit method you should get the same result on every platform as far as I know.
You can see more details on iPhone forms in my own question on another issue.
How can I prevent the Go button on iPad/iPhone from posting the form

Submitting form into a div

Can anyone tell me why this is not working or give me another way into doing what I want.
I have a form on a page when click submit I want it to process into add.php and for it to open up in a DIV called right.
Form page
<script>
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
</script>
</head>
<body>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload">
</form>
</body>
Now if I add action to form to direct it to add.php all works fine so other script is ok yet when i do it this way,nothing happens it does not load add.php into the 'right' div like I want it to.
Anyone got any suggestions?
Your $("#Submit") selector does not match anything (the submit button has no id and is defined after that bind attempt), so the function is not bound to any event, thus never executed.
Instead the form acts the way it should: upon submit it posts its content to the url specified in the 'action' attribute. This is what happens, that div is never touched.
you have to go back to understand how jquery selectors work. How to bind a function to an event.
Is this your exact code? There are a few issues:
$("#Submit").click should be wrapped in a document ready
handler so it doesnt run before the page has actually loaded.
There is no button that matches #Submit
There is no div that matches #right
Try
<script type="text/javascript">
jQuery(document).ready(function($) {
$("#Submit").click(function() {
var url = "add.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(html){ $("#right").html(html); }
});
return false; // avoid to execute the actual submit of the form.
});
});
</script>
</head>
<body>
<div id="right">
</div>
<form action="add.php" method="post" enctype="multipart/form-data" id ="myForm">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name = "email"><br>
Phone: <input type="text" name = "phone"><br>
Photo: <input type="file" name="photo"><br>
<input type="submit" value="Upload" id="Submit">
</form>
you have to create on div in body tag which id will be right and
<input id="submit" type="submit" name="upload" >
add new div in body tag like this
<div id="right"></div>

Resources