Why doesn't jQuery code work in my php file? - php

I'm having difficulties in putting jquery plugin in my php file. I want to be able to prevent sending the form when the text field is empty, but it doesnt work.
PHP:
<html>
<head>
<script src="jquery.js"></script>
</head>
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["login"])) {
echo '<script type="text/javascript">
$("form").submit(function(event){
event.preventDefault();
alert("submit prevented");
});
</script>';
}else {
$login = test_input($_POST['login']);
}
}
?>
HTML:
<form action="form.php" method="post">
Login: <input type="text" name="login"><br>
<input type="submit">
</form>
The same script in my script file
$("form").submit(function(event){
event.preventDefault();
alert("submit prevented");
});
works just fine, the problem is just i can't put it into my php and i think its because of the absence of jQuery.

Simply start with $(document).ready(), very good practice in jquery:
$(document).ready(function() {
$("form").submit(function(event) {
event.preventDefault();
alert("submit prevented");
});
});

Your code:
echo '<script type="text/javascript">
$("form").submit(function(event){
event.preventDefault();
alert("submit prevented");
});
</script>';
That is not how you properly echo multi lines in PHP.
Check out heredoc . Example:
echo <<<EOD
Example of string
spanning multiple lines
using heredoc syntax.
EOD;
echo <<<"FOOBAR"
Hello World!
FOOBAR;
There is also nowdoc but no parsing is done inside the block.
echo <<<'EOD'
Example of string
spanning multiple lines
using nowdoc syntax.
EOD;

Instead of echoing it, just close the braces. Also $(document).ready
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if(empty($_POST["login"])) {;?>
<script type="text/javascript">
$(document).ready(function(){
$("form").submit(function(event){
event.preventDefault();
alert("submit prevented");
});
});
</script>
<?php }else {
$login = test_input($_POST['login']);
}
};?>

Related

$.post() possible race condition; issues with redirect

I have an index.php page that I want to receive information from a user in a textArea, and, upon hitting save, the variable should be posted to another page called changePage.inc.php. Once the post variable has been set onto the other page, the changePage.inc.php should redirect away from the original index.php to a page called secondPage.php.
variable in jquery on index.php -> same variable as a post on changePage.inc.php
-> user is redirected off of index.php to secondPage.php, as instructed by changePage.inc.php
File named index.php
<?php
session_start();
?>
<!DOCTYPE html>
<html>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message});
window.location.href = "includes/changePage.inc.php";
}
};
changeText();
send();
});
});
</script>
<body>
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>
File name changePage.inc.php
<?php
session_start();
if(isset($_POST['message'])){
header("Location: ../secondPage.php");
}
exit();
File named secondPage.php
<?php
echo 'Hello World';
?>
With the code as it is right now, it gets to changePage.inc.php, but not secondPage.php. I believe that the post variable is either not being set at all, or being set too late (maybe this is because of a race condition).
I have asked this question before and thought that an answer using function(data) within the $.post() method to create an object with $.parseJSON(data) was going to work. But upon running the code, errors were generated, so now I am asking it again. This is the previous attempt: POST variable from jquery redirecting but is not set
Redirect to secondPage.php in the Javascript, not PHP. And do it in the callback function of $.post so it waits for the script to complete.
var send = function(){
if(message !== ""){
$.post("includes/changePage.inc.php", {message: message}, function() {
window.location.href = "includes/secondPage.php";
});
}
};
But much simpler would be to just add message as an input in the form, and let the form submit normally.
$("#saveForm").submit(function() {
$("#message").val("You wrote: " + $("#text").val());
}
<textArea id="text"></textArea>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<input type="hidden" name="message" id="message">
<button type="submit" id="saveButton">Save!</button>
</form>
Don't leave the page just after triggering an AJAX request, wait for the result using the callback.
$.post("includes/changePage.inc.php", {message: message}, function (data) {
// here you see 'Hello World' in your browser console
console.log(data);
// here you don't see anything in your browser window because it is no POST
window.location.href = "includes/changePage.inc.php";
});
But why to trigger an ajax request and redirect to the same page afterwards...
Maybe this is what's intended (second try):
<html>
<head>
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous">
</script>
</head>
<body>
<script>
$(document).ready(function(){
$('#saveForm').submit(function(event){
// NO: event.preventDefault();
var message = "";
var changeText = function(){
message = "You wrote: " + $('#text').val();
};
changeText();
// Check for text as message can't be empty here
if (!$('#text').val()){
// preventDefault() here if text is empty
event.preventDefault();
}
});
});
</script>
<form id="saveForm" action="includes/changePage.inc.php" method="POST">
<!-- put textarea inside your form, and write tags in lowercase -->
<textarea id="text"></textarea>
<button type="submit" id="saveButton">Save!</button>
</form>
</body>
</html>

JSON does not work in ajaxForm

It is just impossible. I cannot find what is wrong!!Consider the following very simple testing code:
<head>
<script type="text/javascript" src="js/jquery-1.11.1.js"></script>
<script src="js/jquery.form.js"></script> <!--AJAX JQUERY FORM PLUGIN-->
</head>
<body>
<script>
$(document).ready(function() {
$('#form1').ajaxForm({
dataType: 'json',
success: function () {
alert(5);
}
});
});
</script>
<form action="proceed.php" method="post" name="form1" id="form1" >
<input type="submit" name="one_button" id="one_button" value="GO" />
</form>
</body>
and the code for proceed.php:
<?php
$message= 'success';
echo json_encode($message);
?>
The above code does not alert '5' on button click unless I subtract line dataType: 'json'. Is the problem in PHP which does not send correctly the json data? I cannot tell... The crazy about that is I have used exactly this code many times and everything was fine!!!
Please your $message as array. Your code must be look like this.
<?php
$message[]= 'success';
echo json_encode($message);
?>
http://php.net/manual/en/function.json-encode.php
$message= 'success';
must be an array;
$message[]= 'success';

Passing data using Jquery Post method to the same page

I'm a newbie to Jquery , my question is simple , I'm trying to pass data using Jquery Post method, I have read a lot , but I can't figure it out:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="TestAd" id="TestAd">
<iframe data-aa='58593' src='https://ad.a-ads.com/58593?size=468x60' scrolling='no' style='width:468px; height:60px; border:0px; padding:0;overflow:hidden' allowtransparency='true' frameborder='0'></iframe>
</div>
<button>Send request</button>
<br>
<?php
if(!empty($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
var height = $('.TestAd').height();
$("button").click(function()
{
if (height==0)
{
$.post("", {block:true});
}
}
</script>
</body>
</html>
The script is a simple AdBlocker checker, thanks for your help
<form method="post">
<input type="hidden" value="true" name="block">
<input type="submit" value="Send request">
</form>
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
if you want to redirect it to the same page why dont you use simple form tag to pass the block value.By default it will redirect it on the same page
Change your PHP to this:
<?php
if(isset($_POST["block"])) {
echo "Ads Are Blocked";
}
?>
And Change your jQuery to this:
<script>
var height = $('.TestAd').height();
$("button").click(function () {
if (height == 0) {
$.post("somepage.php",{block: true}, function (data) {
// data is the response
// do something with it here
alert(data);
});
}
}
</script>
Here are the docs for $.post(), essentially, the way you had it, ignores the response. You have to pass the anonymous function (function (data) {}) callback as the 3rd argument to be able to work with the response.
From the docs:
Examples:
Request the test.php page and send some additional data along (while still ignoring the return results).
$.post( "test.php", { name: "John", time: "2pm" } );

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.

php file not working from ajax call

I have the following ajax function that is called from a form button that gets the number used in the php loop below. The php file loads but code stops working after " Fields With Red Asterisks * Are Required"
Any Help would be great!
function loadMulti() {
var num_to_enter = $('#num_to_enter').val();
$.ajax({
type: "POST",
url: "myphpfile.php",
data: "num_to_enter=" + num_to_enter,
success: function(){
$("#multi").load('myphpfile.php')
}
});
return false;
}
and the php :
<?php
$num_to_enter = $_POST["num_to_enter"];
echo $num_to_enter;
$i=1;
?>
<form class="my_form" name="addReg" id="addReg" method="post" />
<span class="red">Fields With Red Asterisks * Are Required</span>
<?php
while($i <= $num_to_enter){
?>
The html form here repeated by $num_to_enter
<?php
$i++;
}
?>
For starters you can clean up your code a bit. See if this helps (tested and its working)
JS File
function loadMulti ()
{
var num_to_enter = 2;//$('#num_to_enter').val();
$.ajax({
type: "POST",
url: "temp.php",
data: "num_to_enter=" + num_to_enter,
}).done (function (data){ //success is deprecated
$("#test").html (data);
});
return false;
}
$(document).ready (function (){
loadMulti ();
});
Or maybe you want a js post??
function loadMulti ()
{
var num_to_enter = 2;//$('#num_to_enter').val();
$ ("#check").on ("click", function (){
$.ajax({
type: "POST",
url: "temp.php",
data: "num_to_enter=" + num_to_enter,
}).done (function (data){ //success is deprecated
$("#test").html (data);
});
});
return false;
}
$(document).ready (function (){
loadMulti ();
});
PHP File
<?php
$num_to_enter = $_POST["num_to_enter"];
$string = "";
echo $num_to_enter;
$i=1;
while ($i <= $num_to_enter)
{
$string .= "The html form here repeated by {$num_to_enter}<br/>";
$i++;
}
?>
<span class="red">Fields With Red Asterisks * Are Required</span>
<?php echo $string; ?>
PHP File that makes the call.
<!doctype html>
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src='test.js'></script>
</head>
<body>
<div id="test">test</div>
</body>
</html>
or with the post
<!doctype html>
<html>
<head>
<title></title>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script src='test.js'></script>
</head>
<body>
<div id="test">results will show here.</div>
<form class="my_form" name="addReg" id="addReg" method="post" />
<input id="check" type="button" name="sendpost" value="Get Data">
</form>
</body>
</html>
EDIT: Added the php file that makes the call, I changed the .load () to .html ()
with its respected selector.
Also I am not sure if you wanted the message to print out more then once, so if you need it printed that way just change $string to an array.
Your PHP script 'works' fine, but you end up in a while loop that has no end because you never update $i. You need to increment it in the while loop:
<?php
$num_to_enter = $_POST["num_to_enter"];
echo $num_to_enter;
$i = 1;
?>
<form class="my_form" name="addReg" id="addReg" method="post" />
<span class="red">Fields With Red Asterisks * Are Required</span>
<?php
while ($i <= $num_to_enter) {
?>The html form here repeated by $num_to_enter <?php
// You need to increment this so the while loop stops when $i hits
// the same amount as $num_to_enter.
$i++;
}
?>
Change this:
data: "num_to_enter=" + num_to_enter,
to this:
data: {num_to_enter: num_to_enter},
$.ajax() expects an object, not a string. The docs do say that it can accept a string, but you have to serialize it yourself in that scenario; it's easier just to let jQuery deal with that.
Regarding the PHP: make sure you increment $i in your while loop, or it will never end, as #putvande pointed out, and make sure you include a closing </form> tag.
Finally, change this: $num_to_enter = $_POST["num_to_enter"]; to this: $num_to_enter = intval($_POST["num_to_enter"]); to force PHP to treat it as an integer.

Categories