PHP Jquery Ajax POST call, not work - php

As the title says, i have try many times to get it working, but without success... the alert window show always the entire source of html part.
Where am i wrong? Please, help me.
Thanks.
PHP:
<?php
if (isset($_POST['send'])) {
$file = $_POST['fblink'];
$contents = file_get_contents($file);
echo $_POST['fblink'];
exit;
}
?>
HTML:
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
</head>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</html>

Your Problem is that you think, that your form fields are automatic send with ajax. But you must define each one into it.
Try this code:
<script>
$(document).ready(function() {
$("input#invia").click(function(e) {
if( !confirm('Are you sure?')) {
return false;
}
var fbvideo = $("#videolink").val();
$.ajax({
type: 'POST',
data: {
send: 1,
fblink: fbvideo
},
cache: false,
//dataType: "html",
success: function(test){
alert(test);
}
});
e.preventDefault();
});
});
</script>
Instead of define each input for itself, jQuery has the method .serialize(), with this method you can easily read all input of your form.
Look at the docs.
And maybe You use .submit() instead of click the submit button. Because the user have multiple ways the submit the form.
$("input#invia").closest('form').submit(function(e) {

You must specify the url to where you're going to send the data.
It can be manual or you can get the action attribute of your form tag.
If you need some additional as the send value, that's not as input in the form you can add it to the serialized form values with formSerializedValues += "&item" + value;' where formSerializedValues is already defined previously as formSerializedValues = <form>.serialize() (<form> is your current form).
<html>
<head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.8.3.min.js"></script>
<script>
$(document).ready(function() {
$("#invia").click(function(e) {
e.preventDefault();
if (!confirm('Are you sure?')) {
return false;
}
// Now you're getting the data in the form to send as object
let fbvideo = $("#videolink").parent().serialize();
// Better if you give it an id or a class to identify it
let formAction = $("#videolink").parent().attr('action');
// If you need any additional value that's not as input in the form
// fbvideo += '&item' + value;
$.ajax({
type: 'POST',
data: fbvideo ,
cache: false,
// dataType: "html",
// url optional in this case
// url: formAction,
success: function(test){
alert(test);
}
});
});
});
</script>
</head>
<body>
<div style="position:relative; margin-top:2000px;">
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input id="videolink" type="text" name="fblink" style="width:500px;">
<br>
<input id="invia" type="submit" name="send" value="Get Link!">
</form>
</div>
</body>

Related

ajax not working .No alert shown after submission

I am trying to insert a name into my database. There is a form asking to enter name.There is also a submit button.on clicking the submit button no alert is show.I am new to ajax.
this is index.php.
<html>
<head>
<title>Untitled Document</title>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.6.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function() {
alert("sucess");
}
});
});
});
</script>
</head>
<body>
<form action="" method="post">
Name:
<input type="text" name="name" id="name" />
<br />
<input type="submit" name="submit" id="submit" />
</form>
</body>
</html>
This is ajax.php
<html>
<body>
<?php
$query=mysql_connect("localhost","root","root");
mysql_select_db("freeze",$query);
$name='l';//$_POST['name'];
mysql_query("insert into tt values('','$name')");
?>
</body>
</html>
Be careful with url's in ajax. Your url is 'ajax.php', this is a relative url, so, if your page is at url http://localhost.com/index.html (for example), ajax will fire a post to http://localhost.com/index.html/ajax.php (and that's probably wrong). Try use absolute url, for that, add '/' at begin of url, then ajax will be fired against http://localhost.com/ajax.php.
Your ajax code should look like code below:
$(document).ready(function() {
$("#submit").submit(function() {
var name = $('#name').val();
$.ajax({
type: "POST",
url: "/ajax.php",
data: "name=" + name,
success: function() {
alert("sucess");
}
});
});
});
The submit event is triggered on the form, not the submit button. So
$("#submit").submit(function() {
will not ever be triggered, because #submit selects the button, not the form. You need to give an ID to the form:
<form id="myform">
then use
$("#myform").submit(function() {
You also need to use event.preventDefault() or return null in the event handler, to prevent the form from being submitted normally when the function returns.

jQuery AJAX POST to current page with attribute

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>

Not able to display ajax response in already created div tag

Hi all i am trying to show ajax response in already created div but i am not able to show. Can you please help me where i am doing wrong.
<form id="coupon" action="">
<label>Have a Coupon?</label>
<input name="couponcode" id="couponcode" value="" />
<input type="submit" value="Apply" />
</form>
<div id="result"></div>
Now my Jquery function is below one.
$("#coupon").submit(function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "coupon.php",
type: "post",
data: values,
success: function (response) {
$('#result').html(response);
}
});
});
My coupon.php file code is below one.
<?php
if (!empty($_POST)) {
$coupon = $_POST['couponcode'];
//json_encode(array('coupon' => $coupon));
echo $coupon;
}
?>
The code needs to concatenate the response in the markup written to the div.
$.ajax({
url: "coupon.php",
type: "post",
data: values,
success: function (response) {
$('#result').html("<div id='message'>"+ response+"</div>");
}
});
try to use
$.ajax({
url: "coupon.php",
type: "post",
data: values,
success: function (response) {
$('#result').text(response);
}
});
default method for form submit is GET but you are sending values through post. Add method=post to form tag
<form id="coupon" action="">
<label>Have a Coupon?</label>
<input name="couponcode" id="couponcode" value="" />
<input type="submit" value="Apply" />
</form>
<div id="result"></div>
<script language="javascript" type="text/javascript" src="jquery-1.8.3.min.js"></script>
<script>
jQuery(document).ready(function($) {
$("#coupon").submit(function (event) {
/* Stop form from submitting normally */
event.preventDefault();
/* Clear result div*/
$("#result").html('');
/* Get some values from elements on the page: */
var values = $(this).serialize();
/* Send the data using post and put the results in a div */
$.ajax({
url: "coupon.php",
type: "post",
data: values,
success: function (response) {
$('#result').html(response);
}
});
});
});
</script>
Its working fine when i tried this

Sending form value using ajax, jquery,php

I am new to ajax and jQuery. I am trying get html form value using ajax and jQuery. I am getting the value but i can not pass that value to another php file. I don't know what i am missing.. can someone help me please..
Here is my form.php file code:
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>Form</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
});
});
});
</script>
</head>
<body>
<form id="input" method="post" action="">
First Name:<input type="text" name="firstName" id="firstName">
Last Name: <input type="text" name="lastName" id="lastName">
<input type="submit" id="submit" value="submit " name="submit">
</form>
<div id="someElement"></div>
</body>
</html>
Here is my database.php file code:
<?php
if(isset($_POST['submit']))
{
$firstName = $_POST['firstName'];
$lastName = $_POST['lastName'];
echo $firstName;
echo $lastName;
}
You need to add:
return false;
to the end of your click handler. Otherwise, the default submit button action takes place, and the page is refreshed.
Also, remove the line:
if (isset($_POST['submit']))
Submit buttons aren't included when you call .serialize() on a form, they're only sent when the submit button is performing normal browser submission (in case there are multiple submit buttons, this allows the server to know which was used).
You need to do the following
$('#submit').click(function(){
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
return false;
});
Form default event will fire if you dont use return false.
You can use as below
$("#input").submit(function(event) {
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
})
return false;
});
You need to prevent the default action of click event or the form will be processed using the default form action and your ajax call will never be complete.
$("#input").submit(function(event) {
event.preventDefault(); // prevent default action
var srt = $("#input").serialize();
// alert is working perfect
alert(srt);
$.ajax({
type: 'POST',
url: 'database.php',
data: srt,
success: function(d) {
$("#someElement").html(d);
}
});
});

Jquery Post + run php file > hide the form > give message

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.

Categories