Can't see the expected result in a jQuery lab - php

The html code:
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript"
src="js/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(msg) {
alert(msg);
$("#info1").html(data.msg);
}, "json");
});
});
</script>
</head>
<body>
<div id="info1">
Put the textbox input value into this block.
</div>
<br />
<form id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit"
id="submit" value="Submit Form" />
</form>
</body>
</html>
The php code:
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo json_encode($result);;
When I entered the text, it cannot display the same text above the input box. Maybe there have some wrong code, but I cannot find it, please help><

Reframed your code. Checkout,
<html>
<head>
<title>jQuery Ajax POST</title>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script>
$(function(){
$("form[id='form1']").on('submit', function(ev){
ev.preventDefault();
var th = $(this);
var data = th.serialize();
var action = th.attr('action');
$.post(action, data).done(function(response){
$("#info1").html(response.msg);
});
});
});
</script>
</head>
<body>
<div id="info1">
<!--Put the textbox input value into this block.-->
</div>
<br />
<form action="ex2_5.php" id="form1">
<input type="text" name="field1" id="field1" />
<input type="submit" name="submit" id="submit" value="Submit Form" />
</form>
</body>
</html>
ex2_5.php
<?php
$result = array();
if (!empty($_POST['form1']))
$result['msg'] = "<h1>".$_POST['form1']."</h1> is added";
else
$result['msg'] = "<h1>Field is empty!!</h1>";
header('Content-type: application/json');
echo json_encode($result);
Bugs:
1) ;; double semicolon
2) $_POST['form1'] in your PHP file
3) Wrong index using in JS while returning
Debugging:
Open console (Right click -> Inspect element -> Console tab) and checkout for errors

Solution 1:
Specify content type for ajax response as application/json. Otherwise the response will be a string not as json.
// Specify content type header as application/json
header('Content-type: application/json');
//Establish values that will be returned via ajax
$result = array();
//Begin form validation functionality
if ( !empty($form1))
$result[0] = "<h1>$field1</h1>";
else
$result[0] = "<h1>Field is empty!!</h1>";
//return json encoded string
echo #json_encode($result);
Solution 2:
If header is not application/json then parse string into object using JSON.parse function.
<script>
$(document).ready(function() {
$('#form1').submit(function(event) {
event.preventDefault(); //disable from default action
$.post("ex2_5.php", $(this).serialize(), function(data) {
var data = JSON.parse(data);
$("#info1").html(data.msg);
}, "json");
});
});
</script>

Related

PHP submit form without refreshing

When the user submits the form, the result should be displayed without page refreshing. The PHP script is also in the same HTML page.
What is wrong withe $.post jQuery?
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript" language="javascript">
$(document).ready(function() {
$("#btn").click(function(event) {
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $("#testform").serialize()
);
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform">
<!-- $_SERVER['PHP_SELF'] array -->
Name:
<input type="text" name="name" id="name" />Age:
<input type="text" name="age" id="age" />
<input type="submit" name="submit" id="btn" />
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { // was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>
You need to use event.preventDefault in your javascript
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
$.post(
"23.php", $( "#testform" ).serialize()
);
});
Yes, you need e.preventDefault. Also, I think these var myname and myage variables are unnecessary since you're serializing the entire form in $.post.
Try this:
$(document).ready(function() {
$("#btn").click(function(e) {
e.preventDefault();
$.post(
"23.php", $("#testform").serialize()
);
});
});
Hope this helps.
Peace! xD
This is my finalized complete code after following your all suggestions. But it is still refreshing when getting results. Let's see if I have made any further error in the code. Thanks for your all helps.
UPDATE! - All these HTML and PHP scripts resides in the same file called 23.php
<!--
Submit form without refreshing
-->
<html>
<head>
<title>My first PHP page</title>
<script type = "text/javascript" src = "http://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type = "text/javascript" language = "javascript">
$(document).ready(function() {
$("#btn").click(function(event){
event.preventDefault();
var myname = $("#name").val();
var myage = $("#age").val();
yourData ='myname='+myname+'&myage='+myage;
$.ajax({
type:'POST',
data:yourData,//Without serialized
url: '23.php',
success:function(data) {
if(data){
$('#testform')[0].reset();//reset the form
alert('Submitted');
}else{
return false;
}
};
});
});
});
</script>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" id="testform"> <!-- $_SERVER['PHP_SELF'] array -->
Name: <input type="text" name="name" id="name"/>
Age: <input type="text" name="age" id="age"/>
<input type="submit" name="submit" id="btn"/>
</form>
</body>
</html>
<?php
if ( isset($_POST['submit']) ) { //was the form submitted?
echo "Welcome ". $_POST["name"] . "<br>";
echo "You are ". $_POST["age"] . "years old<br>";
}
?>

why i cannot pass json data to another PHP file?

i have two php files home.php and ajax.php. i have two buttons on home.php. when they are clicked the according php functions in ajax.php should get called.
home.php
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
alert("action performed successfully");
});
});
});
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
</html>
ajax.php
<?php
echo 'this was called';
echo $_POST['action']; //THROWS AN ERROR undefined index 'action'
if ( isset( $_POST['action'] ) ) {
switch ($_POST['action']) {
case 'insert':
insert();
break;
case 'select':
select();
break;
}
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
the problem is the json data i assign to data property in jquery code will not get passed to the ajax.php. Is there any reason why it doesn't not pass it?
here is my youtube video on the error video
There are two possibilities, depending of what you want to achieve afterwards.
Eighter you stick on doing a backgroud ajax-call to ajax.php and then do with the response whatever you want (that's what I'd suggest):
<html>
<head>
<script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script>
<script type='text/javascript'>
$(document).ready(function(){
$('.button').click(function(){
var clickBtnValue = $(this).id(); // changed to id here!
var ajaxurl = 'ajax.php';
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
// Response div goes here.
console.log(response); // log what the response is
alert("action performed successfully and the resonse is: \n"+response);
// do with that data whatever you need
});
});
});
</script>
</head>
<body>
<!-- changed to buttons, removed the form -->
<button class="button" id="insert">insert</button>
<button class="button" id="select">select</button>
</body>
</html>
or you submit the form and output on screen the response from ajax.php:
<html>
<head>
<!--script src="https://code.jquery.com/jquery-2.1.4.min.js" type="text/javascript"></script-->
<script type='text/javascript'>
// no need for any javascript then
</script>
</head>
<body>
<form action='ajax.php' method="POST">
<input type="submit" class="button" name="insert" value="insert" />
<input type="submit" class="button" name="select" value="select" />
</form>
</body>
and in ajax.php:
<?php
echo 'this was called';
if ( isset( $_POST['insert'] ) ) {
insert();
}
if ( isset( $_POST['select'] ) ) {
select();
}
function select() {
echo "The select function is called.";
exit;
}
function insert() {
echo "The insert function is called.";
exit;
}
?>
try
$.post(ajaxurl, data)
.done(function( r ) {
alert("action performed successfully");
});
I like to use the jQuery on() and to be sure post has worked, I moved in your variables as such. Also you can try to do console.log(clickBtnValue) after the click to be sure you are able to see the value itself. After confirming, the post() should send that value into action post param.
<script type='text/javascript'>
$(document).ready(function(){
$('.button').on('click',function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'ajax.php';
$.post(ajaxurl, {action:clickBtnValue}, function (response) {
alert("action performed successfully");
});
});
});
</script>
If you need to do a ajax call, remove the following part from the home.php
<form action='ajax.php' method="POST">
</form>
I think you are messed up with Ajax technology and the form post mechanism.

how to send data onClick() to another php for processing using post or get?

I want to send data using GET or POST to another php file on a button's(NOT Submit button) onClick() Event.
Please help me.
Let I give you simple HTML with post method using AJAX
Test.php
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
</head>
<body>
<form id="myform_new">
<input type="text" name="abc" value="abc" id="txt"/>
<input type="text" name="abc1" value="abc1" id="txt1"/>
<input type="button" name="Submit" id="Submit" value="Submit" />
</form>
</body>
</html>
Test1.php(ajax calling file)
<?php
echo "<pre>";print_r($_POST);
?>
Let i give you some of the ajax posting method
(1)
<script>
$(function() {
$("#Submit").click(function() {
var value = jQuery("#txt").val();
var data=jQuery('#myform_new').serializeArray();
$.post('test1.php', { myform: data});
return false;
});
});
</script>
(2)
<script type="text/javascript"> $(function() { $("#Submit").click(function()
{
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { txt: txt,txt1:txt1 }); return false; }); });
</script>
(3)
<script type="text/javascript"> $(function() { $("#Submit").click(function() {
var txt = jQuery("#txt").val();
var txt1 = jQuery("#txt").val();
$.post('test1.php', { data: "txt="+txt+"&txt1="+txt1}); return false; }); });
</script>
Hello in there i have explain both ajax and get/post method, Please have look below link for get/post method for submit a form in php.
http://www.tutorialspoint.com/php/php_get_post.htm
This below code is used for submit form using ajax
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
</head>
<body>
<form id="formoid" action="studentFormInsert.php" title="" method="post">
<div>
<label class="title">First Name</label>
<input type="text" id="name" name="name" >
</div>
<div>
<label class="title">Name</label>
<input type="text" id="name2" name="name2" >
</div>
<div>
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</div>
</form>
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
/* stop form from submitting normally */
event.preventDefault();
/* get some values from elements on the page: */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post */
var posting = $.post( url, { name: $('#name').val(), name2: $('#name2').val() } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
</body>
</html>

Changes to text file with php and ajax-driven form

i have created a simple html form with one field and it post to the server side php and the value of the field is saved to a text file.
This is the parts of the code:
Html:
<form action="videorefresh.php" method="POST">
<input name="videolink" type="text" size="70" />
<input type="submit" name="submit" value="Save Data">
</form>
php:
<?php
$open = fopen("video.txt","w+");
$txt = "video.txt";
if (isset($_POST['videolink'])) { // check if both fields are set
$fh = fopen($txt, 'a');
$txt=$_POST['videolink'];
fwrite($fh,$txt); // Write information to the file
fclose($fh); // Close the file
}
?>
here everythink works fine!
I want to drive all this through Ajax so the main html form wont refresh.
so here is the html:
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="./JS/videolink.js"></script>
</head>
<body>
<div id="mainform">
<div id="form">
<div>
<input name="videolink" type="text" id="videolink" size="70">
<input id="submit" type="button" value="Submit">
</div>
</div>
</div>
</body>
</html>
And here is the js:
$(document).ready(function(){
$("#submit").click(function(){
var name = $("#videolink").val();
// Returns successful data submission message when the entered information is stored in database.
var dataString = 'videolink1='+ videolink ;
if(videolink=='')
{
alert("Please Fill All Fields");
}
else
{
// AJAX Code To Submit Form.
$.ajax({
type: "POST",
url: "./videorefresh.php",
data: dataString,
cache: false,
success: function(result){
alert(result);
}
});
}
return false;
});
});
What i do wrong here and it doesnt work?
Please help
I think you want to do is:
var dataString = '?videolink='+ name;//typo videolink
// or better put an id on the form and use serialize()
// var dataString = $('#myform).serialize();
NOT
var dataString = 'videolink1='+ videolink ;
You have the value of the input in name, videolink is undefined

form fields not getting posted to php file when using jquery

I have an HTML file that has a form with two fields. These fields' value should be posted to a PHP and this PHP should be fetched from the HTML using JQuery. This is what I implemented.
My HTML file:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("#first").load("result_jquery.php");
});
});
</script>
</head>
<body>
<div id="first"></div>
<div>
<form method="POST" id="myForm">
Name: <input type="text" name="name"/><br/>
Number: <input type="text" name="number"/><br/>
<button>submit</button>
</form>
</div>
</body>
This is my result_jquery.php
<?php
$n = $_POST["name"];
echo "hello ".$n;
?>
When I click the submit button, the hello is getting printed. But the name is not getting printed. Can you please help me with this. I don't know where I am going wrong.
I think that the use of the button element is the worry and the code that i will put now it is working properly as you need so try this and tell me the result :)
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="//ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js"></script>
<script>
$(document).ready(function(){
$("#button").click(function(){
var n = $('[name="namee"]').val();
var nb = $('[name="number"]').val();
$("#first").load("result_jquery.php",{'namee':n,'number':nb},function(data){});
});
});
</script>
</head>
<body>
<div id="first"></div>
<div>
<form method="POST" id="myForm">
Name: <input type="text" name="namee"/><br/>
Number: <input type="text" name="number"/><br/>
<input type="button" value="Submit" id="button" />
</form>
</div>
</body>
</html>
copy this code:
<script type="text/javascript">
$(document).ready(function() {
$("#send").click(function() {
$.ajax({
type: "POST",
data : "name="+$( '#name' ).val(),
url: "result_jquery.php",
success: function(msg) {
$('#first').html(msg);
}
});
});
});
</script>
change this in form
<form method="POST" id="myForm">
Name: <input type="text" id="name" name="name"/><br/>
Number: <input type="text" id="number" name="number"/><br/>
<input type="button" id="send" value="Submit">
</form>
just try that and tell me the result :)
var n = $('[name="name"]').val();
var nb = $('[name="number"]').val();
$('#error').load("result_jquery.php", {'name':n,'number':nb},function(data){});
Note try to change the element name for the name field from "name" to "namee" and apply changes as needed look like this :
var n = $('[name="namee"]').val();
var nb = $('[name="number"]').val();
$('#error').load("result_jquery.php", {'namee':n,'number':nb},function(data){});
and the result_jquery.php file :
<?php
$n = $_POST["name"];
echo "hello ".$n;
?>
From the jQuery documentation on load:
This method is the simplest way to fetch data from the server. It is
roughly equivalent to $.get(url, data, success) except that it is a
method rather than global function and it has an implicit callback
function. When a successful response is detected (i.e. when textStatus
is "success" or "notmodified"), .load() sets the HTML contents of the
matched element to the returned data. This means that most uses of the
method can be quite simple:
You are performing a HTTP GET with that method, and not a POST.
My suggestion would be if you want to send an AJAX request to your server with information in it, get used to using the long form jQuery AJAX:
$.ajax({
data: 'url=encoded&query=string&of=data&or=object',
url: 'path/to/server/script.php',
success: function( output ) {
// Handle response here
}
});
For more info, see jQuery documentation: http://api.jquery.com/jQuery.ajax/

Categories