I am confused a little bit and I have no clues what am I looking for.
Although I will post here important parts so you may figureout and help me.
A part of PHP file:
if (empty($vid) || empty($entry)) {
$broken = TRUE;
}
if(!$broken) {
$video = parseVideoEntry($entry);
echo "
<div class=\"video_wrap\">
<div class=\"video_thumbnail\">
<a href=\"{$video->watchURL}\">
<img src=\"$video->thumbnailURL\">
</a>
</div>
</div>
<!-- More of structure parts here -->
";
}
A part of HTML structure:
<form action="" method="GET" style="margin: 5% 0;" id="youtube_fetch">
<input type="text" name="id" value="https://www.youtube.com/watch?v=VIDEO_ID_HERE" id="videoID_input" />
<input type="submit" id="fetch_submit" />
</form>
A part of jQuery / Ajax call:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else
console.log(state);
}
});
e.preventDefault();
});
Ok so when I put valid youtube ID into the input field, it will return the else from ajax call (echo the html structure in console log).
The part that I don't know how to deal with is: "How to get that echoed HTML content/structure and append it into the <div id="youtube_content"></div> for example or directly to the body.
Use the .html() method:
$('#youtube_content').html(state);
References:
.html() - jQuery API Documentation
If I understand your question correctly:
$('#fetch_submit').on('click', function (e) {
var videoID = $('#videoID_input').val();
$.ajax({
url: 'inc/YouTube_API_Fetch_ID.php',
type: 'GET',
data: { id: videoID },
success: function (state) {
var newState = $.trim(state);
if (newState == '')
alert('Return an Error later!');
else {
$('<div />', {
id: 'youtube_content'
}).appendTo('body');
$('#youtube_content').html(state);
}
}
});
e.preventDefault();
});
Related
Please help me how to submit form (comments) without page refresh for
HTML markup:
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="submit" id="comq"name="compost" class="butn2">post comment</button>
</form>
PHP code (pnf.php):
if(isset($_POST["compost"]))
{
$comment=$_POST['comments'];
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if($stmt)
{
echo "hello world";
}
}
jQuery and Ajax:
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
I have tried many times and don't know what mistake I made, Ajax and jQuery are not working, please anyone help - thanks in advance
You have made couple of mistakes.
First:: You should put button type="button" in your HTML form code
Second:: You have made a syntax error. $("#comment").vol(); should be replaced with $("#comment").val(); in your jQuery AJAX
As you mentioned that you have to send request without refreshing page I modified your JS-code with preventing default submitting form:
$(document).ready(function () {
$("#commentf").submit(function (e) {
e.preventDefault();
var comment = $("#comment").val();
$.ajax({
type: "POST",
url: "pnf.php",
data: {
"done": 1,
"comments": comment
},
success: function (data) {
}
})
});
});
Javascript
$('form').on('submit', function(event){
event.preventDefault();
event.stopPropagination();
var dataSet = {
comment: $('#comment').val();
}
$.ajax({
url: "link.to.your.api/action=compost",
data: dataSet,
method: 'post',
success: function(data){
console.log('request in success');
console.log(data);
},
error: function(jqXHR) {
console.error('request in error');
console.log(jqXHR.responseText');
}
});
});
PHP
$action = filter_input(INPUT_GET, 'action');
swicht($action){
case 'compost':
$comment = filter_input(INPUT_POST, 'comment');
{
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
}
if(!$stmt)
{
http_response_code(400);
echo 'internal error';
}
echo 'your data will be saved';
break;
default:
http_response_code(404);
echo 'unknown action';
}
you have to prevent the submit on the form (look in javascript).
after that you send the request to the server and wait for success or error.
in php try to do it with a switch case. and try to not touch super globals directly, use filter_input function.
hope this helps
Modified JQuery Code...
$( document ).ready(function() {
console.log( "ready!" );
$("#comq").click(function() {
var comment=$("#comment").val();
console.log('comment : '+comment);
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
HTML Code
<form id="commentf" method="post">
<textarea class="textinput" id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<input type="button" id="comq" name="compost" class="butn2" value="Post Comment">
</form> </div>
<form id="commentf" method="post">
<img width="40px" height="40px" src="uploads/<?php echo $row['photo']; ?>">
<textarea class="textinput"id="comment" rows="1" name="comments" placeholder="Comment Here......"></textarea>
<button type="button" id="comq"name="compost" class="butn2">post comment</button>
</form>
script
$(document).ready(function()
{
$("#comq").click(function() {
var comment=$("#comment").val();
$.ajax({
type: "POST",
url:"pnf.php",
data: {
"done":1,
"comments":comment
},
success: function(data){
}
})
});
});
PHP code (pnf.php):
comment=$_POST['comments'];
$reslt_user= mysqli_query($connection,"SELECT * FROM tbl_users,`queries` where id='".$_SESSION['id']."' AND qid= '".$qid."' ");
$row_lat_lng= mysqli_fetch_array($reslt_user);
$stmt = mysqli_query($connection,"INSERT INTO comments set uid='".$_SESSION['id']."',comments='".$comment."',reply='".$reply."' ,
qid= '".$qid."' ");
if($stmt)
{
echo "hello world";
}
if you are using jquery make sure to include jquery libraries before your script file.
latest jquery cdn minified version
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
example
<script src="https://code.jquery.com/jquery-3.2.1.min.js" type="text/javascript"></script>
<script src="yourjsfile.js" type="text/javascript"></script>
This is an example of my own page.
<?php
$do = $_GET['do'];
switch($do){
case 'finalTask':
if(isset($_POST['url'])){
echo "It's Ok!";
}else{
echo "Problem!";
}
}
This is also written in the same page.
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script>
$(document).ready(function(e){
$('#send').click(function(){
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url:"index.php?do=finalTask",
cache:false,
data:dataStr,
type:"POST",
success:function(data){
$('#info').html(data);
}
});
});
});
</script>
When I try to input and press the send button. Nothing happened..... What's wrong with the code?
Make sure file name is index.php
You need to make sure that you check in the php code when to output the form and when the
Format of ajax post request is incorrect in your case.
You forgot to import JQuery JS script, without that you can not use JQuery. (at least at this point of time)
-
<?php
if (!isset($_GET['do'])) { // Make sure that you don't get the form twice after submitting the data
?>
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
<div id='info'></div>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function (e) {
$('#send').click(function () {
var name = $('#siteName').val();
var dataStr = 'url=' + name;
$.ajax({
url: "index.php?do=finalTask",
cache: false,
data: {url: dataStr}, // you need to send as name:value format.
type: "POST",
success: function (data) {
$('#info').html(data);
}
});
});
});
</script>
<?php
} else {
error_reporting(E_ERROR); // Disable warning and enable only error reports.
$do = $_GET['do'];
switch ($do) {
case 'finalTask':
if (isset($_POST['url'])) {
echo "It's Ok!";
} else {
echo "Problem!";
}
}
}
?>
There seems to be no form in your page, just form elements. Can you wrap them in a form:
<form method="POST" onSubmit="return false;">
<input type='text' id='siteName'>
<button type='submit' id='send'>Send</button>
</form>
i am building one form with fancy box, form work fine but i could not get value from text box.
my java script is
$(function () {
$("#button").click(function () {
var yourName = $("input#yourName").val();
alert(yourName);
if (yourName == "") {
$('input#yourName').css({
backgroundColor: "#F90"
});
$("input#yourName").focus();
return false;
}
$.ajax({
type: "POST",
url: "bin/form1.php",
data: $("#login_form").serialize(),
context: document.body,
success: function (res) {
var success = '<?php echo sprintf(_m('Success name % s '), "" ); ?>';
success = success.replace(/^\s*|\s*$/g, "");
var RegularExpression = new RegExp(success);
if (RegularExpression.test(res)) {
alert('Message Sent');
$.fancybox.close();
} else {
alert('Error While processing');
}
},
});
return false;
});
});
now my html is
<div style="display:none; height:450px">
<form id="login_form" action="">
<p id="login_error">
Please, enter data
</p>
<input type="hidden" name="action" value="send_friend_post" />
<label for="yourName" style="margin-right:110px;">
<?php _e( 'Your name', 'newcorp') ; ?>
</label>
<input id="yourName" type="text" name="yourName" value="" class="text_new " />
<br/>
<input type="submit" value="Submit" id="button" class="text_new" style="background:#930; color:#FFF; width:250px; margin-left:170px" />
</form>
</div>
i am opening this fancy box popup from
<a id="tip5" title="" href="#login_form"><?php echo "Login" ; ?></a>
every thing work fine but i can't get value of yourName even alert is showing blank.
Thanks
instead of this
var yourName = $("input#yourName").val();
try
var yourName = $("input[name='yourName']:text").val();
this will make ur function read the value of text box .
Firstly, with your form, it should be better to use
$(document).on('submit', 'form', function () { ... })
instead of
$(document).on('click', '#myButton', function () { ... })
Secondly, you should encapsulate your code into $(document).ready(function () { .. });
Here is a working example ;) http://jsfiddle.net/aANmv/1/
Check that the ID of Your input is not changed by fancybox at the time of opening the popup.
Instead of directly catching up the click event try to live the event if using jQuery 1.7 > or on when using jQuery 1.7 <.
live:
$("#button").live('click', function() { ... });
on:
$("#button").on('click', function() { ... });
Also try to load the javascript after the DOM is loaded:
$(document).ready(function(){
$("#button").live('click', function() { ... });
...
});
Instead of that
$(function() {
try
$(document).ready() {
this way you are sure that code is executed only after the document has loaded completely. Oh, and you could use #yourName instead of input#yourName, if i'm not wrong it should be faster.
I have a form that I wish to submit which is posting to a php script to deal with the form data.
What I need to do is after hitting submit have a colorbox popup with the php results in it.
Can this be done?
This is what i've been trying:
$("#buildForm").click(function () { // #buildForm is button ID
var data = $('#test-buildForm'); // #test-buildForm is form ID
$("#buildForm").colorbox({
href:"build_action.php",
iframe:true,
innerWidth:640,
innerHeight:360,
data: data
});
return false;
});
UPDATE: This would need to be returned in an iframe as the
build_action.php has specific included css and js for those results.
This is simple, untested code but it'll give you a good jumping off point so you can elaborate however much you please:
<form action="/path/to/script.php" id="formID" method="post">
<!-- form stuff goes here -->
<input type="submit" name="do" value="Submit" />
</form>
<script type="text/javascript">
$(function() {
$("#formID").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), function(data) {
$.colorbox({html:data});
},
'html');
return false;
});
});
</script>
this article will help you with the problem
http://www.php4every1.com/tutorials/jquery-ajax-tutorial/
$(document).ready(function(){
$('#submit').click(function() {
$('#waiting').show(500);
$('#demoForm').hide(0);
$('#message').hide(0);
$.ajax({
type : 'POST',
url : 'post.php',
dataType : 'json',
data: {
email : $('#email').val()
},
success : function(data){
$('#waiting').hide(500);
$('#message').removeClass().addClass((data.error === true) ? 'error' : 'success')
.text(data.msg).show(500);
if (data.error === true)
$('#demoForm').show(500);
},
error : function(XMLHttpRequest, textStatus, errorThrown) {
$('#waiting').hide(500);
$('#message').removeClass().addClass('error')
.text('There was an error.').show(500);
$('#demoForm').show(500);
}
});
return false;
});
});
< ?php
sleep(3);
if (empty($_POST['email'])) {
$return['error'] = true;
$return['msg'] = 'You did not enter you email.';
}
else {
$return['error'] = false;
$return['msg'] = 'You\'ve entered: ' . $_POST['email'] . '.';
}
echo json_encode($return);
You will need to see the exact way to use your colorbox jQuery plugin. But here is a basic (untested) code example that I've just written to hopefully get you on your way.
If you wish to submit a form using jQuery, assuming you have the following form and div to hold dialog data:
<form id="myForm">
<input type="text" name="num1" />
<input type="text" name="num2" />
<input type="submit" name="formSubmit" />
</form>
<div style="display: hidden" id="dialogData"></div>
You can have a PHP code (doAddition.php), which might do the addition of the two numbers
<?php
// Do the addition
$addition = $_POST['num1'] + $_POST['num2'];
$result = array("result" => $addition);
// Output as json
echo json_encode($result);
?>
You can use jQuery to detect the submitting of the code, then send the data to the PHP page and get the result back as JSON:
$('form#myForm').submit( function() {
// Form has been submitted, send data from form and get result
// Get data from form
var formData = $('form#myForm').serialize();
$.getJSON( 'doAddition.php', formData, function(resultJSON) {
// Put the result inside the dialog case
$("#dialogData").html(resultJSON.result);
// Show the dialog
$("#dialogData").dialog();
});
});
This is how I ended up getting it to work:
<div id="formwrapper">
<form method="post" action="http://wherever" target="response">
# form stuff
</form>
<iframe id="response" name="response" style="display: none;"></iframe>
</div>
<script>
function hideresponseiframe() {
$('#formwrapper #response').hide();
}
$('form').submit(
function (event) {
$('#formwrapper #response').show();
$.colorbox(
{
inline: true,
href: "#response",
open: true,
onComplete: function() {
hideresponseiframe()
},
onClosed: function() {
hideresponseiframe()
}
}
);
return true;
}
);
</script>
here is my code about jquery post. I can't make it work somehow. I spent hours :( what I miss here?! when I run the code, It loads same page :(
I want it to run the php code under
query.php and hide the contact form
and give "thanks!" message at send
submit button click. (with no page
loading)
appreciate helps!
PHP Form
<form id="commentForm" name="contact" method="post" action="">
<ul id="contact-form">
<li><label>Full Name: *</label><input type="text" name="full_name" class="txt_input required" /></li>
<li><input type="submit" value="Send" id="btnsend" name="btnsend" class="btn_submit" /></li>
</ul>
</form>
SCRIPT
$(function() {
$("#btnsend").click(function() {
var dataString = 'fullname='+ escape(full_name);
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
return false;
});
});
Your problem lies in: var dataString = 'fullname='+ escape(full_name);
Try: var dataString = 'fullname='+ escape(document.contact.full_name.value);
Eg:
<!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() {
$("#btnsend").click(function() {
var dataString = 'fullname='+ escape(document.contact.full_name.value);
$.ajax( {
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>").fadeIn(1500, function() {
$('#contact-form').append("");
});
}
});
return false;
});
});
</script>
</head>
<body>
<form id="commentForm" name="contact" method="post" action="">
<ul id="contact-form">
<li><label>Full Name: *</label><input type="text" name="full_name" class="txt_input required" /></li>
<li><input type="submit" value="Send" id="btnsend" name="btnsend" class="btn_submit" /></li>
</ul>
</form>
</body>
Make sure query.php exists though else it won't execute the call back function at success.
Also make sure you click the button and not press the ENTER key as that will submit the form normally (you have only defined an event handler for click not keypress)
You can preventDefault on the button click or return false on the form's submit event:
$(function() {
$("#btnsend").click(function(e) {
e.preventDefault();
var full_name = $('input["name=full_name"]').val();
var dataString = 'fullname='+ full_name;
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: dataString,
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
});
});
or:
$('#commentForm').submit(function() {
return false;
});
Try:
$(function() {
$("#btnsend").click(function() {
$.ajax({
type: "POST",
url: "query.php?act=contact",
data: { fullname: $('input[name=full_name]').val() },
success: function() {
$('#contact-form').hide();
$('#contact-form').html("<p>thanks!</p>")
.fadeIn(1500, function() {$('#contact-form').append("");});
}
});
return false;
});
});
I think that you have at least 3 problems here. First, you are referencing full_name as if it were a variable. I believe this is causing a javascript error which aborts the function and allows the default action (post) to proceed. Second, you probably need to encode ALL of the form parameters, including act. This is may be causing an invalid URL to be sent and thus the action appears not to have been invoked -- you can check this by looking at the request that is sent with Firefox/Firebug. Third, you are attempting to replace the contents of a list with a paragraph element. This is invalid HTML. I'd replace the entire list with the paragraph (and I don't get what appending an empty string does at the end so I've omitted it).
Note I've changed this to work on the submit event of the form -- so it won't matter how it's submitted. Also allows me a little jQuery niceness in not having to look up the form again.
$('#commentform').submit(function() {
var $this = $(this);
$.ajax({
url: "query.php",
data: { 'act': 'contact', 'full_name', $('input[name="full_name"]').val() },
success: function() {
$('#contact-form').remove();
$this.hide().html("<p>thanks!</p>").fadeIn(1500);
}
});
return false;
}
This is my way to call PHP function directly via jQuery
// in html file
<script language="javascript">
$.post("thisisphp.php",{ func:"true", varbl: 'valu2' },function(data) {
$('.thisdiv #subdiv').html(data);
});
</script>
PHP file thisisphp.php
<?php
// include connection creating file.
require_once("database.php");
$db = & new Database();
function getDateAppointments($varible1, $varible2, $db) {
$q_appointment = "SELECT * FROM `tbl_apoint` WHERE ap_date = '".$varible1."'";
$s_appointment = $db->SelectQuery($q_appointment);
while($r_appointment = mysql_fetch_array($s_appointment))
{
echo '<div id="appoinment">'.$r_appointment['ap_title'].'</div>';
}
}
/* This function for set positions of the day */
switch($_POST['func']) {
case 'true':
getFunc1($_POST['varbl'], 'S0001', $db);
break;
default:
getFunc2($_POST['varbl'], 'S0001', $db);
}
?>
Can this help you?
PS: you can put your hidding and showing form script inside onSucces and onError functions.