Forms/PHP/Ajax load? - php

I'm currently learning PHP. I've made a simple script # http://hash.techho.me, only thing is, I want the form to submit then load the results via AJAX, without the user leaving the page. Possible?

post the form using ajax
$.ajax({
url:'yoururl',
data:$("form").serialize(),
type:'POST',
success:function(data){
alert("success");
},
error:function(jxhr){
alert(jxhr.responseText);
}
});
jQuery.ajax() – jQuery API

Posting to the same page should do the trick. No need to use ajax for that
> <?php
>
> //do stuff with $_POST
> ?>
>
> <html> <body> <form method="post">
>
> <?php echo $result ?>
>
> </form>
> </body>

Fike
use ajax for this, lets suppose try this one for your practice
var string = $("#string").val();
var dataString = 'string=' + string ;
if(string==''){
alert('enter any string');
}
else{
$.ajax({
type: "POST",
url: "path of php file",
data: dataString,
suceess: function(){
//do something
},
error: function(){
//do something
}
});
}

You can use jQuery or Prototype JS libraries to make an easy AJAX call. Example using jQuery would be:
$.ajax({
url:'hashed.php',
data:$("form").serialize(),
type:'POST',
success: function(data){
$('hashmd5').html(data.md5);
$('hashsha1').html(data.sha1);
},
error: function(jxhr){
alert(jxhr.responseText);
}
});
Don't use the same id value in HTML, never ever. They must be unique to correct perform JavaScript functions on elements.

yes it is possible. Write a javascript function that would trigger on submit, disable the submit button so user couldn't press it again, and finally request the server via ajax. on successful response update the content. Something like following in Jquery
$('.form-submit').click(function(event)) {
event.preventDefault();
if(form is valid and not empty) {
$.ajax({
type: "POST",
url: "path to script that will handle insetion",
data: "data from form", //like ({username : $('#username').val()}),
suceess: function(data){
//update the content or what. data is the response got from server. you can also do like this to show feedback etc...
$('.feedback').html("Data has been saved successfully");
},
error: function(){
$('.feedback').html("Data couldn't be saved");
}
});
}
}

Related

send data by Jquery ajax to same php

i need help because i'm stuck and don't know what's wrong ,i try to send user clicked button "id" to php to get related data from database in the same page
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
console.log(res, data);
},
error: function(err) {
alert(err);
}
});
});
the ajax print success in console log ,here is php code to get the value if clicked id
<?php
if(isset($_POST['ToEditId'])){
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
}
but nothing happen in php file !!
Which is the expected behaviour.
PHP is not dynamic. It doesn't "update".
PHP only runs once. This means that once your page is rendered, you cannot use PHP to change it again. You actually would have to use javascript to change the page, like so;
PHP side:
<?php
if(isset($_POST['ToEditId'])){
echo $_POST['ToEditId'];
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
die(); // prevent entire page from re-rendering again.
}
JS side:
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
//Add your PHP file's response to the body through javascript.
$('body').append(res);
},
error: function(err) {
alert(err);
}
});
});
As #IncredibleHat mentioned, you should make sure your page doesn't render any of its usual HTML, so it won't return the entire page back to your ajax call. So put the PHP all the way above your html!

Execute php using jquery post

I've tried to go to php file using jquery.
Here is my code.
This is index.php
$.post('test.php',data,function(json){},'json');
This is test.php
//set session variable from passed data
$_SESSION['data1'] = $_POST['data1'];
<script>
window.open('test1.php','_blank');
</script>
This is test1.php
echo $_SESSION['data1'];
But this code is not working.
I want to pass data from index.php to test1.php.
How can I do this? I don't want to use GET method because of too long url.
Anyhelp would be appreciate.
I am not quite clear from you explanation right now. But I am here trying to resolve you problem as you can use the jquery post method as follows :
$.post('test1.php',{param1:value1,param2=value2,...},function(data){
//Here you can take action as per data return from the page or can add simple action like redirecting or other
});
Here is a simple example of register :
$.post('', $("#register_form").serialize(), function(data) {
if (data === '1') {
bootbox.alert("You have registered successfully.", function() {
document.location.href = base_url + '';
});
} else if (data === '0') {
bootbox.alert("Error submitting records");
} else {
bootbox.alert(data);
}
$("#user_register_button").button("reset");
});
Try this:
$.ajax({
url: 'test.php',
type: 'POST',
data: {
myData : 'somevalue'
},
success: function(response){ // response from test.php
// do your stuff here
}
});
test.php
$myData = $_REQUEST['myData'];
// do your stuff here
I like use jQuery post a url like this.
$('form').on('submit', function(e) {
e.preventDefault();
var $this = $(this);
$.ajax({
url: $this.attr('action'),
method: $this.attr('method'),
data: $this.serializeArray(),
success: function(response) {
console.log(response);
}
})
});
I you a beginner, you can reference this project
php-and-jQuery-messageBoard

Send data of a form using serialize function

i want to send all the input fields of the form to process/do_submitattendance.php,
where i can use the to store in the database.
However i am having trouble doing this.
My jQuery code is-
<script type="text/javascript">
$("#submitattendance").submit(function(){
var_form_data=$(this).serialize();
$.ajax({
type: "POST",
url: "process/do_submitattendance.php",
data: var_form_data,
success: function(msg){
alert("data saved" + msg);
});
});
</script>
submitattendance is the ID of the form element.
I'm guessing the form is submitting, and you'll have to prevent the default submit action:
<script type="text/javascript">
$(function() {
$("#submitattendance").on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url : "process/do_submitattendance.php",
data: $(this).serialize()
}).done(function(msg) {
alert("data saved" + msg);
});
});
});
</script>
var var_form_data=$(this).serialize();
is all i can find, or there must be an error in your code somewhere else. you can look in your chrome console to see if there is an error (f12). also add return false; to stop the form submitting itself.
Why don't you try to pass values through session?
By using session you can pass the values from one page to anyother pages you want.
the typical code looks like this:
Mainpage.php
<?php
session_start(); // You should start session
$_SESSION['UserName']="YourTextfield";
?>
SecondPage.php
<?php
session_start();
$var = $_SESSION['UserName'];
?>
After you saved the data...then you need reset the session
$_SESSION['UserName']="";
That's what I usually use. and I hope it will help you...

Trouble POSTing form with AJAX

edit - the info appears to be posting, but on form_data.php it doesn't seem to be retrieving the posted values
Here's the AJAX
<head>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$("#submit_boxes").submit(function() { return false; });
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: function(data) {
$('#view_inputs').html(data); //view_inputs contains a PHP generated table with data that is processed from the post. Is this doable or does it have to be javascript?
});
return false;
});
};
</script>
</head>
Here is the form I'm trying to submit
<form action="#" id = "submit_boxes">
<input type= "submit" name="submit_value"/>
<input type="textbox" name="new_input">
</form>
Here is the form_data page that gets the info posted to
<?php
if($_POST['new_input']){
echo "submitted";
$value = $_POST['new_input'];
$add_to_box = new dynamic_box();
array_push($add_to_box->box_values,$value);
print_r($add_to_box->box_values);
}
?>
Your form is submitting because you have errors which prevents the code that stops the form from submiting from running. Specifically dataType: dataType and this.html(data) . Firstly dataType is undefined, if you don't know what to set the data type to then leave it out. Secondly this refers to the form element which has no html method, you probably meant $(this).html(data) although this is unlikely what you wanted, most likely its $(this).serialize() you want. So your code should look like
$('form#submit_boxes').submit(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: $(this).serialize(),
success: success
})
return false;
});
Additionally if you have to debug ajax in a form submit handler the first thing you do is prevent the form from submitting(returning false can only be done at the end) so you can see what errors occurred.
$('form#submit_boxes').submit(function(event) {
event.preventDefault();
...
});
You can use jQuery's .serialize() method to send form data
Some nice links below for you to understand that
jquery form.serialize and other parameters
http://www.tutorialspoint.com/jquery/ajax-serialize.htm
http://api.jquery.com/serialize/
One way to handle it...
Cancel the usual form submit:
$("#submit_boxes").submit(function() { return false; });
Then assign a click handler to your button:
$('input[type=submit]').click(function() {
$.ajax({
type: 'POST',
url: 'form_data.php',
data: this.html(data),
success: success,
dataType: dataType
})
return false;
});

Get div content with jQuery for PHP

UPDATE: Wow that was the fastest response ever and so many answers in minutes of each other. Amazing. Ok here is what I am trying to do. http://edvizenor.com/invoice33/
I want to edit this invoice on the fly but when I hit the BLUE BOX at the top I want to preview or see this content on the next page contained php var echoed out.
This blue box will change later to be a button at the bottom but for testing I am using it.
As you see it calls the ajax script but I need the edited content of the div to be sent a php var to I can echo it on the preview page. If I can put it in a php var I do what I will with it on the next page. Does that make sense? Thanks guys for your quick responses.
OLD POST
Is it possible to get the contents of a div using jQuery and then place them in a PHP var to send via GET OR POST?
I can get the contents of the div with jQuery like this:
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script>
$(document).ready(function()
{
$("#MyButton").click(function()
{
var htmlStr = $("#MyDiv").html();
});
});
</script>
But how do I put the jQuery var in a php var. I need to do this by a BUTTON press too. This is not included in the code above. I need because the div file is changeable and when I hit UPDATE and send via PHP it needs to have the latest content.
According to your situation,
You are trying to send JavaScript variable to PHP.
The only common way to do this is to exchange in JSON format,
for example, suppose we have basic text editor
Jquery:
$($document).ready(function(){
$("#submit-button").click(function(){
$.post('yourphpscript.php', {
//this will be PHP var: //this is JavaScript variable:
'text' : $("#some_text_area").text()
}, function(response){
//To avoid JS Fatal Error:
try {
var result = JSON.parse(response);
//get back from PHP
if ( result.success){ alert('successfully changed') }
} catch(e){
//response isn't JSON
}
});
});
});
PHP code
<?php
/**
*
* So we are processing that variable from JavaScript
*/
if ( isset($_POST['text']) ){
//do smth, like save to database
}
/**
* Well if you want to show "Success message"
* that div or textarea successfully changed
* you can send the result BACK to JavaScript via JSON
*/
$some_array = array();
$some_aray['success'] = true;
die( json_encode($some_array) );
You'll need to use ajax to send the value to your server.
var html = $('#myDiv').html();
$.ajax({
type: 'POST',
url: '/SomeUrl/MyResource.php',
data: JSON.stringify({ text: html }),
success: function(response)
{
alert('Ajax call successful!');
}
});
The thing you need is AJAX (see http://en.wikipedia.org/wiki/Ajax_(programming))
The basic idea is to send a http request with javascript by e.g. calling a php script and wait for the response.
With plain Javascript AJAX requests are a bit unhandy, but since you are already using jQuery you can make use of this library. See http://api.jquery.com/jQuery.ajax/ for a complete overview.
The code on client side would be something like this:
$.ajax({
url:'http://example.com/script.php',
data:'var=' + $('#myDiv').html(),
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
In your script.php you could do something like this:
$var = $_GET['var'];
// Do some processing...
echo 'response';
and in your javascript console the string response would occur.
In modern ajax based applications the best practise way to send and receive data is through JSON.
So to handle bigger datasets in your requests and responses you do something like this:
$.ajax({
url:'http://example.com/script.php',
data:{
var:$('#myDiv').html()
},
type:'GET'
success:function(response) {
console.log(response) // Your response
},
error:function(error) {
console.log(error) // No successful request
}
});
And in your PHP code you can use the $someArray = json_decode($_GET['var']) to decode JSONs for PHP (it will return an associative array) and $jsonString = json_encode($someArray) to encode an array to a JSON string which you can return and handle as a regular JSON in your javascript.
I hope that helps you out.
You can use hidden form fields and use jQuery to set the value of the hidden field to that, so when the button is clicked and form submitted, your PHP can pick it up as if it were any other form element (using $_POST). Alternatively, you can use AJAX to make an asynchronous request to your PHP page. This is probably simpler. Here's an example:
$("#myButton").click(function() {
var htmlStr = $('#myDiv').html();
$.post("mypage.php", { inputHTML : htmlStr },
function(data) {
alert("Data returned from mypage.php: " + data);
});
}
Yes, Its possible
<script type="text/javascript">
$(document).ready(function(){
$('#MyButton').click(function(){
$.post('sendinfo.php',
{
data: $('#data').html()
},
function(response){
alert('Successfully');
});
});
});
</script>
<div id="data">Here is some data</div>
Use ajax for sending value to php (server).. here's a good tutorial for ajax with jquery http://www.w3schools.com/jquery/jquery_ajax.asp
you should just use Ajax to send your variable.
$.ajax({
url:'whateverUrl.php',
type:'GET',
data:{
html : htmlStr
}
});
Using AJAX:
$("#MyButton").click(function() {
var htmlStr = $("#MyDiv").html();
$.ajax({
url: "script.php",
type: "POST",
data: {htmlStr : htmlStr},
success: function(returnedData) {
//do something
}
});
});
Something like below should work.
Read more: http://api.jquery.com/jQuery.post/
$("#YourButton").click(function(e){
e.preventDefault();
var htmlStr = $("#YourDiv").html();
$.post(
url: 'YourPHP.php',
data: '{"htmlStr" : "'+htmlStr+'"}',
success: function(){
alert("Success!");
}
);
});
Send the data via XmlHttpRequest ("ajax") to your php page either via POST or GET.

Categories