How to implement HTML content inside my PHP page - php

A PHP page opened in my browser.
I have an HTML file with a jQuery AJAX call in it. When I post the data using AJAX, the HTML page disappear and the PHP file open instead.
I want to see the HTML result in the PHP page that I initially opened instead of opening a new HTML page.
What I have to do in my phpfile?
Thanks for help.
My HTML code:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#button").click(function(){
$.post( "result.php",{ name : $('#text').val() },
function( data ) {
$('#bigdiv').html(data);
// alert(data);
});
}); //event handler
}); //document.ready
</script>
And my PHP code:
<?php
$name="";
if( $_REQUEST["name"] )
{
$name = $_REQUEST['name'];
}
echo "name = $name";
?>

I'm going to go ahead and assume that your button is tied to a form, so that it submits the form, and thus reloading the page, when you press it. Try adding this to your JavaScript:
$("#button").click(function(e) {
e.preventDefault();
//rest of your code...

Related

How to display ALERT massage AFTER redirecting to other page using php and jscript?

Question is simple ,
I have a form submission after successful submission of form , i want to print Alert massage on next page that "Form successfully submitted !" ?
using php and jscript
I learned this approach from Laravel, its called flash message.
Basically you set some variable in the session (your choice in naming)
//from your originating page
<?php
$_SESSION["flash"] = array();
$_SESSION["flash"]["message"] = "Your message";
$_SESSION["flash"]["status"] = "error";
?>
<?php
//to your destination page
if(isset($_SESSION["flash"])){
echo $_SESSION["flash"]["message"];
//or
echo "<script>alert('{$_SESSION["flash"]["message"]}');</script>";
unset($_SESSION["flash"]);
}
?>
After saving the form you can redirect user on a page with alert script using:
// PHP
header('Location: http://www.example.com/path_to_page');
Then on that page you can add js
// Js (include jquery before it)
<script>
$(document).ready(function(){
alert('Form successfully submitted!');
});
</script>
If you are not using jquery then use:
<body onload="alert_call()">
<!-- your page content -->
<script>
function alert_call(){
alert('Form successfully submitted!');
}
</script>
</body>

Resetting a PHP $_SESSION array with jquery function

I am trying to reset a session array in php with a function in jquery using a button. I would use a submit but I don't want the page to refresh. I tried to send a $.post request leaving the variables and return blank, and then sending a variable so I could use $_session[''] = array() but none of it worked. I have searched and can't find much about it just a lot on sending strings.
OK this is very simple to stop the page from refreshing you need to tell js to disable the default event i use jquery for this here is my code
Html & js
<html>
<head>
<title>Reseting a PHP $_SESSIO array with jquery function</title>
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script src="http://code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
<script>
function sessRest(){
$.post("rest.php", {x: "9845621"}).done(function(data){
alert("States: " + data);
});
}
$(document).ready(function(){
$("#target").click(function(event){
event.preventDefault();
sessRest();
});
});
</script>
</head>
<body>
<div id="main">
Click to rest me
</div>
</body>
</html>
php code rest.php
<?php
session_start();
(string)$data = $_POST['x'];
if($data == "9845621"){
$_SESSION['gx'] = array();
return $_SESSION['gx']; //return the empty array to js
}else(
return "error";
)
?>
I hope this helps .
User below jquery to submit to php code
var requestData = { param: "value"};
$.ajax({
url: your_url/session_change.php,
type: "post",
dataType: "json" or what ever,
data: your_data,
success: function (data) {
}
});
You can end the session successfully on server side with an ajax call, but apart from reloading the page, you're not going to clear what information was loaded already on client side. The session information wont be there once you do reload, but there is no way around that.
You can, however, emulate what you want to do with javascript.
When you load your session information, echo it to the page as javascript variables, then you have full control on client side. Just beware of echoing sensitive information like passwords, obviously.
try this:
your html file should contain this jQuery file:
$('#button').click(function(e){
e.preventDefault();
jQuery.ajax({
url: 'http://yourwebsite.com/session.php'
}).done(function(data){
if(data=='reseted'){
//do anything...
}
else {
//do anything...
}
})
});
and in your session.php file:
<?php
session_start();
session_unset();
if($_SESSION == FALSE){
echo 'reseted';
}
else echo 'no';
?>
the answer was
jquery $.post('reset.php');
in reset.php
$_SESSION['products'] = array();
?>
this reset my session array when the reset button was clicked with no page refresh...
I had done this originally and forgot to include my core.php in the reset.php which contained my start session()..
Thank you all for the help though.... great suggestions

jquery form submit does not work after using a load function

I have an index.html page which, using jquery, calls somepage.php residing within the same site to load the contents of this index.html page.
So this is the intended page load sequence:
index.html -> somepage.php -> submit.php (if submit button is clicked)
The index.html has only the "main-div" and no contents as such. When the somepage.php is called, the "main-div" contents are loaded by running the php script. The main-div contains a sub div with a small form with a submit button. Using jQuery,I see if the submit button is clicked, and when clicked, the submit.php script is called.
This is the barebone code:
<!DOCTYPE html>
<html>
<head>
<script src="js/jquery.js"></script>
<script>
$('document').ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php");
$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);
});
function submit(jsURL){
$.get(
'http://www.someurl.com/submit.php',
{ item: jsURL },
function(data){
if(data=="success")
{
$('#submit-status').html(data);
}
else
{
$('#submit-status').html(data);
}
}
);
}
});
</script>
</head>
<body>
<div id="main-div"> </div>
</body>
</html>
Now the issue:
The index.html page loads with everything displayed correctly (the small form with the submit button, all other main-div contents, everything is displayed). However, the submit button does not call the submit.php script, meaning I believe that the jQuery code corresponding to the click event is not being registered.
I am fairly new to jQuery. Does this have something to do with how I have "ordered" the code in the jQuery .ready()? Something to do with the DOM not being ready before the function is called, or maybe an issue with the .load() in jQuery?
Try this :
<script>
$(document).ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php",function(){
$("#main-div").on('click', '#item-submit', function(e){
e.preventDefault();
var jsURL = $('#input').attr('value');
submit(jsURL);
});
});
});
function submit(jsURL){
$.ajax({
url:'http://www.someurl.com/submit.php',
type :'GET',
success: function(data){
$('#submit-status').html(data);
}
});
}
</script>
$(document).ready(function(){
$("#main-div").load("http://www.someurl.com/somepage.php");
$("#main-div").on('click', '#item-submit', function(e){
e.preventDefault();
var jsURL = $('#input').val();
submit(jsURL);
});
function submit(jsURL){
$.get('http://www.someurl.com/submit.php', {item: jsURL}, function(data){
$('#submit-status').html(data);
});
}
});
Do not quote the document
load() is a shortcut for $.ajax, and it's async, so #item-submit does'nt exist when you attach the event handler, you need a delegated event handler for that.
If it's really a submit button inside a form, make you sure you prevent the default action so the form does'nt get submitted.
The load function works asynchronously. With your code #item-submit is not yet there when you try to bind the event handler.
Bind the event handler on succes:
$("#main-div").load("http://www.someurl.com/somepage.php", function () {
$('#item-submit').click(function () {
jsURL = $('#input').val();
submit(jsURL);
});
});
load loads the data asynchronously, which means time by the time you are assigning a click handler on submit button the button itself might not be yet on the page. To overcome this you have two options:
Specify a success handler for load.
$("#main-div").load("http://www.someurl.com/somepage.php", function(){
$('#item-submit').click(function(){
jsURL = $('#input').val();
submit(jsURL);
});
});
Use on to indicate that the click handler should be assigned to elements that are or will be on the page.
$('#item-submit').on('click', function(){
jsURL = $('#input').val();
submit(jsURL);
});
As all pointed out, the load function works asynchronously so, your click handler is not working for the 'future' div.
You can bind handler to a future element like this:
$(document).on('click', '#item-submit', function(event){
jsURL = $('#input').val();
submit(jsURL);
});
This way you can bind your handler in the jQuery document ready function.

jquery ajax request within the joomla modal window

I am useing modal window of native joomla codes. I am displaying a form wihchi is used to send mail from one user to another. The php,css and js codes are in tmpl file (by using JDocument) of view and js is like that;
var $j = jQuery.noConflict();
$j(document).ready(function(){
$j("#sendMail").click(function(){
if(document.formvalidator.isValid(this.form)){
$j("#mailSending").css("display","inline-block");
$j.ajax({
type: \'POST\',
url: \'index.php?option=mycomponent&tmpl=component&view=members\',
data: $j("form#mailForm").serialize(),
success: function(data,xhr,status){
$j("#mailSending").css("display","none");
$j("#mailMsg").css("display","inline-block");
setTimeout(function(){window.parent.SqueezeBox.close()},1000);
alert(status);
}
});
}else{
$j("#mailMsg").text("'.JText::_('OFFER_EMPTY_FIELDS').'").css("display","inline-block").delay(1000).fadeOut("slow");
}
});
});';
I am tracing the xhr with firebug when I triger the click function to loading icon is shown and task within the controller file is executed. Php file ends like that;
$send =& $mailer->Send();
if ( $send !== true ) {
echo 'Error sending email: ' . $send->getMessage();
} else {
echo 'Mail sent';
}
exit();
While the php function process ends the content within the modal window is changes with Mail Sent. But I want to hide the loading .gif and show a message. But the code don't do that. Any idea ?
Code to send a form with ajax and insert its returned values into a div
jQuery(function($) {
$("form[name='srchForm']").submit(function(){
$.get($(this).action, $(this).serialize() + "&tmpl=component&limitstart=0", function(data){
$m =$('#main');
$m.html(data).delay(10);
});
return false;
});
});
It is funny I love Ricardo's use of jquery instead of this "$j(document).ready(function(){})" but the point is I figured that the button which is used to trigger the ajax is not to set a type of button it has button tag but doesn't have attribute. I think it tries both ajax and normal submit process and it conficts.
Thanks for your helps and sorry for my stupit mistake.

Easiest Way To Make A Form Submit Without Refresh

I have been trying to create a simple calculator. Using PHP I managed to get the values from input fields and jump menus from the POST, but of course the form refreshes upon submit.
Using Javascript i tried using
function changeText(){
document.getElementById('result').innerHTML = '<?php echo "$result";?>'
but this would keep giving an answer of "0" after clicking the button because it could not get values from POST as the form had not been submitted.
So I am trying to work out either the Easiest Way to do it via ajax or something similar
or to get the selected values on the jump menu's with JavaScript.
I have read some of the ajax examples online but they are quite confusing (not familiar with the language)
Use jQuery + JSON combination to submit a form something like this:
test.php:
<script type="text/javascript" src="jquery-1.4.2.js"></script>
<script type="text/javascript" src="jsFile.js"></script>
<form action='_test.php' method='post' class='ajaxform'>
<input type='text' name='txt' value='Test Text'>
<input type='submit' value='submit'>
</form>
<div id='testDiv'>Result comes here..</div>
_test.php:
<?php
$arr = array( 'testDiv' => $_POST['txt'] );
echo json_encode( $arr );
?>
jsFile.js
jQuery(document).ready(function(){
jQuery('.ajaxform').submit( function() {
$.ajax({
url : $(this).attr('action'),
type : $(this).attr('method'),
dataType: 'json',
data : $(this).serialize(),
success : function( data ) {
for(var id in data) {
jQuery('#' + id).html( data[id] );
}
}
});
return false;
});
});
The best way to do this is with Ajax and jQuery
after you have include your jQuery library in your head, use something like the following
$('#someForm').submit(function(){
var form = $(this);
var serialized = form.serialize();
$.post('ajax/register.php',{payload:serialized},function(response){
//response is the result from the server.
if(response)
{
//Place the response after the form and remove the form.
form.after(response).remove();
}
});
//Return false to prevent the page from changing.
return false;
});
Your php would be like so.
<?php
if($_POST)
{
/*
Process data...
*/
if($registration_ok)
{
echo '<div class="success">Thankyou</a>';
die();
}
}
?>
I use a new window. On saving I open a new window which handles the saving and closes onload.
window.open('save.php?value=' + document.editor.edit1.value, 'Saving...','status,width=200,height=200');
The php file would contain a bodytag with onload="window.close();" and before that, the PHP script to save the contents of my editor.
Its probably not very secure, but its simple as you requested. The editor gets to keep its undo-information etc.

Categories