Sending data with javascript to PHP - javascript

I want to send the data and the Text that is in one DIV tag with Javascript into php values.
I have problem with using this code :
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
<script>
$.post('http://localhost/test/index.php', {
name: $('.class').html()});
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.class').text();
$(this).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
});
});
</script>
<form action="" method="POST" id="my_form">
<div class="class" name="name">
this is my div
</div>
<input type="submit" value="submit" name="submit" />
</form>
<?php
if (isset($_POST['name'])) {
echo $_POST['name'];
}
It doesn't work . Nothing appear ! and NO php working !
How can i solve this problem ?

You have stated you would like to do the following:
I want to send the data and the Text that is in one DIV tag with
Javascript into php values.
And
It doesn't work . Nothing appear ! and NO php working !
First you need to decide on what "appear" means. Are you trying to take the results of the PHP script and embed them on the page?
First, let's focus on your first item, sending the data. Please do the following:
Remove the onReady statements from inside the post request you're making. This is confusing and could result in unexpected results:
$.post('http://localhost/test/index.php', {
name: $('.class').html()});
$(document).ready(function(){
$("#my_form").on("submit", function () {
var hvalue = $('.class').text();
$(this).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
});
});
Readability is key here. This is absolutely bizarre looking and I've never seen anyone do it this way.
Notice I changed your class from .html() to .text(). This is because you're only working with a text node and not html at this point given your example code. If it were actually html, then you could use the html() function.
Second, the PHP script you're trying to hit is embedded directly.
Try moving it to a new file, such as in my above example myPhpScript.php
Inside that file would be your PHP code that fields the post request:
<?php
if (isset($_POST['name'])) {
echo $_POST['name'];
You're missing an on success handler in your POST request, so when the request success, nothing is going to happen. Please add the following to your request setup object. AT this point you can do the following with your on ready as well
$(document).ready(function(){
$.post('http://localhost/test/myPhpScript.php', {
name: $('.class').html()}
,function(data){
$(".class").text(data).append("<input type='hidden' name='name' value=' " + hvalue + " '/>");
}
});
});
This should get you started, but keep in mind there could be other issues as well. I've got my own share of issues in here as well. I'm going to blame lack of caffeine and a toddler, plus not keeping the documentation open long enough to make sure I get it perfect :).
Someone was kind enough to edit my mistakes, so for that I thank you.

That is because you didn't specify a success handler for your $.post request. So all it does is return some HTML like you have in the background, but your JavaScript isn't doing anything with it.
Please read the API docs on http://api.jquery.com/jquery.post/ and check the success(data, textStatus, jqXHR) part of the arguments to $.post. That is where you define your success handler.
Try this and you'll see what I mean:
$.post('http://localhost/test/index.php', {
name: $('.class').html()
}, function(data) {
alert(data);
});
Within the function(data) { ... } you need to program some logic so it does something with your data.

Related

Update img with jquery and php

i'm trying to update img cover without refresh the page using ajax and php but it does not work at all
HTML
<div class="cover" >
<img id="b1" src="<?php echo $user->picture_path();>"class="cover"/>
<div id="modal-cover" class="cov-lo"> </div>
</div>
js
$('#b2').on({
'click': function(){
$('#b1').attr('src', <?php echo $user->picture_path();?> + '?' + new Date().getTime());}
});
the input and form
<form action="profile.php" method="POST" enctype="multipart/form-data" >
<div class="hio">
Upload <input type="file" onchange="this.form.submit()" name="cover" id="bla2"class="custom-file-input" />
</div>
</form>
Ajax would look more like this:
js/jQuery:
$(document).on({'click', '#b2', function(){
$.ajax({
type: 'post',
url: 'my_ajax_processor_file.php',
data: '',
success: function(data){
$('#b1').attr('src', data);
}
}); //END ajax
}); //END #b2.click
my_ajax_processor_file.php:
<?php
$dt = new Date().getTime();
$pp = 'get user picture path here';
echo $pp .' - '. $pp;
Note that you need to have an external PHP file, which I've called my_ajax_processor_file.php, that does some additional PHP processing and ECHOs back a value.
This value is received in the AJAX code block's success function, and called data (call it what you like - the name is set here: function(data).
Note that the contents of data variable are only available within that success function.
Here are some more basic examples of what AJAX looks like:
A simple example
More complicated example
Populate dropdown 2 based on selection in dropdown 1
I think you have a fundamental misunderstanding of where the PHP and HTML are interpreted:
PHP is a server-side scripting language designed for web development (see this Wikipedia article). That means that the PHP code is executed on the server before arriving in the browser.
HTML is interpreted as plain text by the browser. No PHP is executed in the browser.
Therefore, once the JS gets to the browser, echo $user->picture_path(); has already been executed and is interpreted as plain text by the browser.
Your JS will look like this once it hits the browser:
$('#b2').on({
'click': function() {
$('#b1').attr('src', '/the/path/to/the/picture' + '?' + new Date().getTime());
}
});

Getting Javascript/jQuery and PHP To work together

UPDATED:
Okay, Thanks to OneSneakyMofo's Help below, I have managed to use ajax to call a submit.php form and have it return for example an echo statement. My problem is that none of my $post values are being carried over, for example if my start my php script with if (isset($_POST['pizzacrustformid'])) { the javascript will return blank, also when I do a var_dump($_POST);, Nothing is being saved into it which means the data is not being carried over, the php script is just being called. Please let me know if there is something I need to do in order to get the POST information to get carried over from the form as it would with a
< Submit > Button traditionally.
I Have Updated my code on Github to reflect my progress. https://github.com/dhierholzer/Basiconlineordering Thanks Again!
ORIGINAL POST:
I am new to using jquery and having forms be submitted without loading a newpage /refreshing the page.
In my Code I have multiple forms on one page that display one at a time via fade in and out effects by hitting the next button.
My problem is now that I do this, I cannot seem to get a PHP script to activate when hitting the next button to save those form options into sessions.
So here is an example:
<!--First Pizza Form, Pick Pizza Crust Type-->
<div id="pizzacrust">
<form method="post" name="pizzacrustform" id="pizzacrustformid">
<div id="main">
<div class="example">
<div>
<input id="freshpizza" type="radio" name="pizzacrust" value="1" checked="checked"><label style="color:black" for="freshpizza"><span><span></span></span>Fresh Dough</label>
</div>
<div>
<input id="originalpizza" type="radio" name="pizzacrust" value="2"><label style="color:black" for="originalpizza"><span><span></span></span>Original</label>
</div>
<div>
<input id="panpizza" type="radio" name="pizzacrust" value="3"><label style="color:black" for="panpizza"><span><span></span></span>Deep Dish Pan</label>
</div>
</div>
</div>
</form>
</div>
<div><button href="#" id="btn">Show Pizza Size</button></div>
So this Is my First Form, One thing to pay attention to is that instead of a < Submit > button, I am using a normal button and using javascript to do the submitting part.
Here is that Javascript:
<!--Controls All Button Fades-->
$('#btn').click(function(e){
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
$('#pizzacrustformid').submit();
});
});
and Then:
$(document).ready(function () {
$('#pizzacrustformid').on('submit', function(e) {
e.preventDefault();
});
});
Now Traditionally being a php programmer, I just had a button in my form and then my php activated by having something like:
if (isset($_POST['submitted'])) { //MY Code To save values into sessions}
I cant seem To Get a function like that working when the form is submitted via a javascript function as I have it.
Here is my full code in my GitHub which may make it easier to see more so how these forms are working together right now.
https://github.com/dhierholzer/Basiconlineordering
Please Let me know any solutions that might be possible
Thanks again.
Edit:
OP, it looks like you are wanting to do AJAX, but you don't have anywhere to submit your AJAX to. Firstly, you will need to create a file that accepts the form.
Let's call it submit.php.
With that in place, you can start working on the AJAX call. To begin, you will need to separate your code from index.php.
Take this out of index.php and put it in submit.php:
if (isset($_POST['pizzacrustformid'])) {
// use a foreach loop to read and display array elements
echo '<p>hello!<p>';
}
In your Javascript, you will need to do something like the following:
$('#btn').click(function(e){
$.ajax({
method: "POST",
url: "some.php",
data: $('#pizzacrustformid').serializeArray()
})
.done(function(data) {
alert(data); //should be "Hello world"
$('#pizzacrust, #btn').fadeOut('slow', function(){
$('#pizzasize, #btn2').fadeIn('slow');
});
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
});
What is happening here is is on submit, your form data will pass over to the submit.php page, and it will generate the PHP code. That code will hit the done function (if it's successful), call an alert, then fade out to the next section.
That should get you on the right path. I would create another branch and strip out all of the forms and work on getting this done before continuing.
Also, I would set this all up in one single form and show the first section, do some validation, and then move on to the next section before finally submitting eveyrthing you need.
Hope this helps.
I recommend you do requests via ajax, here a tutorial and examples:
http://www.w3schools.com/jquery/jquery_ajax_get_post.asp
delete all jquery functions about submit
create a file called blu.php with the php code
add the jquery code in index.php
with this you only do once request at the end. I hope this helps you.
<?php echo 'tus datos son: ';
echo ' '.$_POST["data1"];
echo ' '.$_POST["data2"];
echo ' '.$_POST["data3"]; ?>
<script>
$(document).ready(function(){
$("#btn5").click(function(){
var pizzacrust= $('input[name="pizzacrust"]:checked').val();
var pizzasize= $('input[name="pizzasize"]:checked').val();
var pizzatoppings= $('input[name="pizzatoppings"]:checked').val();
$.post("blu.php",
{
data1: pizzacrust,
data2: pizzasize,
data3: pizzatoppings
},
function(data,status){
alert("Data: " + data);
});
});
});
</script>
I think you need to using click() func call ajax, dont use on() submit. Submit action makes current page will refresh. I will review your code later, but you should to try this solution above.

need javascript or jquery function to wrap php code (window.setInterval bootstrap list group)

Thanks for all the answers, seems like AJAX is the solution, I'll give it a try. But what about JSON? Isn't JSON an even better solution? If it is, why is AJAX more preferable?
I'm looking for a way to update this part of php code every 5 seconds, which would regenerate this bootstrap list group. what would be a good way to do it? I figure I couldn't just wrap it in window.setInterval, and refreshing the entire page is not an option. Thanks in advance.
<?php
$i=0;
// Display all room
foreach ($rooms as $room) {
$room_num = $room['room_num'];
$room_type = $room['room_type'];
$note = $room['note'];
echo '
<a class="list-group-item" >
<h4 class="list-group-item-heading" id="room_num' .$i. '" ><p>'.$room_num." - " .$room_type.'</p></h4>
<p class="list-group-item-text" id="note' .$i. '" ><p>'.$note.'</p></p>
</a>
';
$i++;
}
$rooms = "";
getList();
?>
All on the same 'page.php'
php part:
<?
if ($_POST["whatever"])
{
echo 'your shizzle here'
exit;
}
?>
Javascript part: (with jquery)
<script>
setInterval(function()
{
$.post( "page.php", { whatever: 1}, function( data ) {
document.getElementById('someid').innerHTML = data;
});
},5000);
</script>
html part
<div id = "someid"></div>
Another way to do it could be using an iframe :) But iframes won't be used in the future I think.
Basically when you write php code inside javascript, it always run once, when the page is loaded. After this you just writing php code to the browser which is simply do not understand (Php is processed on the server, and the output is Html, Css, and Javascript, which the browser can interpret)
So, if you need to update data from the server without reloading the page, the only way to do this is with Ajax Requests, that basically connect to the server within the page and get data from it.
In your case, Save the PHP code which ever you want to execute in a file say php_temp.php
Now just do
setInterval(function(){
$.get("php_temp.php", function(data){
console.log(data) // data stores whatever php_temp.php echoes
});
},5000);
more on Ajax: Ajax Basics

Should I combine PHP with ajax to post data to the server?

Imagine the page always refreshes after submitting a comment form. That is annoying since the comments are at not at the top of the page and you always have to scroll to the bottom to see your comment and the other ones.
I thought it would be a lot better to use ajax to submit the form.
HTML
<form id="com-form" method="post">
<textarea type="text" name="text" required=""></textarea>
<input type="submit" value="Post"/>
</form>
<div id="com-refresh"></div>
jQuery
$("#com-form").on('submit', function(e) {
e.preventDefault();
var form = $(this),
form_data = form.serialize();
$.post('/php/comments/add.php', form_data, function(data) {
$("#com-refresh").append(data);
});
});
PHP
<?php
session_start();
require_once 'comment.class.php'; //require a class with methods
$text = $_POST['text'];
if($_SESSION['status'] == 'loggedin') {
if(isset($text)) {
$comment = new Comment(); //initialize the Comment object
echo $comment->add_comment($text); //safe the comment in the database and output it
} else echo "Your comment is empty.";
} else echo "Please log in to post comments.";
I hope the code is understandable.
Do you think it is smart or a bad practice to use ajax to not refresh the page after submitting a form?
How should it be done? Do you have a better idea, a cleaner solution?
You could simply do:
$(document).ajaxSuccess(function(e, xhr, settings) {
$(".mydiv").html(xhr.responseText);
});
having your php file print what ever html you want to replace.
further reading: ajaxSuccess
example of what might be your solution
form file:
<form method="post">
<textarea type="text" name="comment" id="com-area"></textarea>
<input type="submit" id="com-submit"/>
</form>
<div id="com-refresh">
<?php require_once "comments/build.php"; ?>
</div>
$(function() {
$(".cmtx_form").submit(function(e) {
e.preventDefault();
var form = $(this);
var text = $(".cmtx_textarea_field").val();
$.ajax({
type: 'POST',
url: 'comments/add.php?ajaxCall=true',
cache: false,
data: { comment: text }
});
});
});
$(document).ajaxSuccess(function(e, xhr, settings) {
$("#com-refresh").html(xhr.responseText);
});
your add.php file should look somewhat like so:
// ... code code code...
if (isset($_GET['ajaxCall']) && $_GET['ajaxCall']) {
include_once('/path/to/build.php');
}
simply you can redirect the file from add.php to build.php after complete the process using header('location:comments/build.php'); or some other else, so second ajax call was unnecessary.
The problem was the php code. I have rewritten the functions that generate the comments in OOP style which helped a lot. I edited the post know so it can be useful in the future.
To make it short:
Use ajax! Your website's user experience will be a lot better, because you are able to provide live updates, etc.
It is recommendable to use the built-in jQuery function .serialize() to safe data into a "text string in standard URL-encoded notation", that can make your work more simple.
I know there is a lot of discussions about OOP, but it really helps understanding, organizing and maintaining your code more easily

Ajax form not getting a reply from php file

This form is working perfectly fine, e.g. it stops the form submitting, there's no javascript errors in the console log. However, when I press submit, I get an alert with nothing in it. I have searched the internet for multiple solutions and they all give the same for me.
Here's my Javascript/Html
<script>
$(function(){
$("#submit").click(function(event){
event.preventDefault();
$.ajax({
type:"post",
url:"templates/process-token.php",
data:$("#form").serialize(),
success:function(response){
alert(response);
}
});
});
});
</script>
<form id="form" method = "post" action = "security_check">
<input type = "text" name = "fld1" id = "fld1" />
<input type = "text" name = "result1" id = "result1" value = "value_from_php_page" disabled />
<input type="submit" value="Submit" id="submit">
</form>
And here's the PHP, it's so simple but doesn't work:
<?php
echo $_POST["fld1"];
?>
Any help here would be appreciated. Thank you.
Change data from $('#form').serialize() to a one test variable so you can see if it is JS or PHP that is causing the issue.
On your PHP page:
<?php
isset($_POST["fld1"]) ? $myvar1 = $_POST["fld1"] : $myvar1 = 'No data passed...';
echo $myvar1;
?>
This confirms that there is infact an fld1 in the $_POST, and if not, says so, taking away the guess work...
You could do this with JSON both ways. Here's how I would implement this kind of thing in JavaScript and PHP.
There's a great function in jQuery that is a shortcut for getting JSON data. It's a shortcut for $.ajax specifically for simple calls.
$.getJSON( "templates/process-token.php?"+$("#form").serialize(), function( data ) { alert( data.reponse ) } );
PHP could return a json encoded string so it can be accessed from the JavaScript code more easily.
<?php echo json_encode( array('response'=>$_POST['fld1']) ); ?>
That can happen only if the text box #fld1 is empty. Type something in the text box and it will work.

Categories