JavaScript and PHP code not working - javascript

I have simple code with html, JavaScript and PHP. I am trying to pass a variable from HTML to PHP through ajax.
A text box appears on screen with button, user inputs in the text field and clicks the button. The field text should appear before the field. But in my case, nothing happens when clicking the button. I am posting my code below. These are the three files I have made:
index.html
<!doctype html>
<html lang="en">
<body>
<input id="name" type="text" /> <input id="button" type="button" value="Load" />
<div id="content"></div>
<script type="text/javascript" src="ajax.js"></script>
</body>
</html>
ajax.js
$('#button').click(function() {
document.write("this is javascript");
var name = $('#name').val();
$.ajax({
url: 'page.php',
data: name,
success: function(data) {
$('#content').html(data);
}
});
});
page.php
<?php
if(isset($_GET['name'])) {
echo "lllllllllllllllll";
echo $name=$_GET['name'];
}
?>

Add CDN as mentioned above. Also make sure you load the jquery CDN or jquery.lib.js before including external js file, ajax.js in index.html.
There is an issue in your $.ajax code:
$.ajax({
url: 'page.php',
data: name,
success: function(data) {
$('#content').html(data);
}
});
change this to:
$.ajax(
{
type:'GET',
url: 'page.php',
data:"name=test"
},
success: function(data) {
$('#content').html(data);
}
);

only add before axaj.js
<script type="text/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>

add this in your javascript ajax: type : 'GET'.
In your php code :
$name=$_GET['name'];
echo $name;

Related

Jquery array send by ajax to php

I viewed so many post aboit this but still cant get my code to work.
I want to get a php array of my checked checkboxes values.
heres my code:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script>
<title>Untitled Document</title>
</head>
<body>
<?php
echo'<form method="post">
<input type="checkbox" name="cim" value="valami">';
echo'<input type="checkbox" name="cim" value="valami2">';
echo'<input type="checkbox" name="cim" value="valami3">';
echo'<input type="checkbox" name="cim" value="valami4">
<input type="submit" value="Felvisz" name="feladat"></form>';
if (isset($_POST['feladat'])) {
?>
<script type="text/javascript">
var checkedValue = $('.messageCheckbox:checked').val();
var myJSON = JSON.stringify(checkedValue);
$.ajax({
type: "POST",
url: "proba.php",
data: { tomb : myJSON },
success: function(){
alert("OK");
}
});
</script>
<?php
var_dump($_POST);
$array = json_decode(stripslashes($_POST['tomb']));
foreach($array as $arr){
echo $arr;
}
}
?>
</body>
</html>
Massages i got:
Notice: Undefined index: tomb in D:\programok\xamp\htdocs\SZAKDOGA\Dropbox\proba.php on line 48
Warning: Invalid argument supplied for foreach() in D:\programok\xamp\htdocs\SZAKDOGA\Dropbox\proba.php on line 49
Please someone can help me to solve this?
To get an array , you must convert the name to accept multiple so change the input's :
name="cim"
to
name="cim[]"
Also your jquery ajax function should be this :
<script type="text/javascript">
$(function(){
$("form").on("submit",function(e){
e.preventDefault();
var checkedValue = $(this).serialize();
$.ajax({
type: "POST",
url: "proba.php",
data: checkedValue,
success: function(){
alert("OK");
}
});//end ajax
});//end form submit
});
</script>
in php the cim will be the array example
var_dump($_POST["cim"]);
hope it helps
currently, you are testing for checked boxes with class messageChecked. assign your checkboxes that class, give your form an id, then test for checked condition on each checkbox,
$('#yourForm').each(function() {
if($('.messageChecked').is(':checked')) {
checkedValue.push($('.messageChecked:checked').val());
}
}
now send it to your php script via ajax,
$.ajax({
type: "POST",
url: "proba.php",
data: { tomb : (checkedValue) },
success: function(){
alert("OK");
}
});
if done like this you can remove json_decode and stripslashes from your $_POST statement

How do I access variables from PHP file using Ajax and JSON? (data is not defined error)

I have this PHP file:
JSONtest.php
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
I want to alert this variable's value using Ajax and JSON, and for that I've written this script:
learningJSON.php
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
data: data,
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
But when I click the button, I get this error message:
learningJSON.php:14 Uncaught ReferenceError: data is not defined
What wrong I'm doing? How can I fix this?
<?php
$a=5;
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Nope, it doesn't. Whats the point in converting a simple number to JSON? It stays the number 5
Now the real problem. Yes your data variable is not defined anywhere in your JavaScript code. If you have no data to send, remove that parameter.
However if you still want to pass some data, define it accordingly then. For example
data: { fname: "John", lname: "Doe" }
Now let's say on your next exercise you want to post form data you can use this nice function named serialize(). This will take all the postable fields from your form and send them along with this request.
data : $("#formID").serialize()
Data variable is not defined, you can delete that
Php file
<?php
$a = $_REQUEST['number'];
echo json_encode($a);
//This converts PHP variable to JSON.
?>
Javascript file
$(document).ready(function(){
$("button").click(function(){
$.ajax({
url: 'JSONtest.php',
type: 'POST',
//data: {'number' : 10}, //this is when you need send parameters to the call, uncomment to send it parameters
dataType: 'json',
success: function(result){
alert(result);
},
error: function(){
alert("Error");
}
});
});
});
I think this one should be perfect for you.
We need 3 files
index.php
login.js
login.php
That mean when user submit [index.php] script js file [login.js] running ajax process script [json] in login.js by collect all data from form input [index.php] and send and run script login.php ... This is powerful script of ajax & json
check code below
index.php
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script src="login.js" type="text/javascript" charset="utf-8"> </script>
</head>
<body>
<form method="post" id="login" name="login">
Email: <input type="email" id="log-mail" name="log-mail" > <br />
Password: <input type="password" id="log-pass" name="log-pass" > <br />
<button type="submit" >Log in</button>
</form>
</body>
</html>
login.js
$(document).ready(function(){
// #login = login is the name of our login form
$('#login').submit(function(e) {
$.ajax({
type: "POST",
url: "login.php",
data: $('#login').serialize(),
dataType: "json",
success: function(msg){
if(parseInt(msg.status)==1)
{
window.location=msg.txt;
}
else if(parseInt(msg.status)==0)
{
window.location=msg.txt;
}
}
});
e.preventDefault();
});
});
login.php
<?php
if(isset($_POST['log-mail']) && $_POST['log-mail'] != '' && isset($_POST['log-pass']) && $_POST['log-pass'] != '' ) {
$_data_ = 'index.php?user_data='.$_POST['log-mail'];
echo msg_result(1,$_data_);
}else{
$msg_att = "index.php?login_attempt=1";
echo msg_result(0,$msg_att);
}
function msg_result($status,$txt) {
return '{"status":'.$status.',"txt":"'.$txt.'"}';
}
?>
you can see on your url if you
complete all field => ...index.php?user_data=user_data#gmail.com
uncomplete => ...index.php?login_attempt=1
Hope this solve your issue

What is wrong with my ajax call to php file in data section?

So I am able to get my php value into javascript variable but I don't think my script.js is finding it. There of course are alot of files missing for the sake of keeping this question clean but my problem is that script.js get schoolId as undefined instead of the actual value but when I console.log schoolId i get a value of "1"(first page has id 1 so that works).
Header.php :
<?php
//gets current page id
$schoolOfficialId = $specificSchool[0]["id"];
?>
<head>
<script type="text/javascript" src="js/script.js"></script>
</head>
<body>
<input type="hidden" id='schoolOfficialId' value="<?php echo $schoolOfficialId;?>"/>
<script type="text/javascript">
var schoolId = $('#schoolOfficialId').val();
</script>
</body>
script.js: ajax call here NOTE: in the ajax i know the data is having trouble finding schoolId from the header.php to send to php file.
// execute an ajax query to push id of page to load_more.php
$.ajax({
url: 'load_more.php',
type: 'POST',
data: {schoolId:schoolId},
success:function(data){
console.log("working");
}
});
my load_more.php:
if (isset($_POST['schoolId'])) {
echo "yes";
}else {
echo "nope";
}//keeps echoing nope because the schoolId is not received
The problem is that you have the script running before the declaration.
<script type="text/javascript" src="js/script.js"></script> is in head, but var schoolId = $('#schoolOfficialId').val(); is at the bottom of the page.
Include the script after declaring schoolId.
<head>
</head>
<body>
<input type="hidden" id='schoolOfficialId' value="<?php echo $schoolOfficialId;?>"/>
<script type="text/javascript">
var schoolId = $('#schoolOfficialId').val();
</script>
<script type="text/javascript" src="js/script.js"></script>
</body>
P.S. despite other answers, data: {schoolId:schoolId}, is perfectly fine unless the keyname conflicts with a reserved word.
Load ajax code after defining var schoolId and also check source code whether php printing value for schoolId correctly or not and also do not forget to use $(document).ready()
<script type="text/javascript">
$(document).ready(function(){
var schoolId = $('#schoolOfficialId').val();
$.ajax({
url: 'load_more.php',
type: 'POST',
data: {schoolId:schoolId},
success:function(data){
alert(data);
}
});
})
</script>
PHP:
if (isset($_POST['schoolId'])) {
echo $_POST['schoolId'];
}else {
echo "nope";
}
By running the following i can see yes in alert ...
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>stackoverflow</title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.js"></script>
<script>
$(document).ready(function () {
var schoolId = $("#schoolOfficialId").val();
$.ajax({
url: 'ajax.php',
type: 'POST',
data: {schoolId: schoolId},
success: function (data) {
alert(data);
}
});
});
</script>
</body>
</html>
Ajax file (ajax.php) :
if (isset($_POST['schoolId'])) {
echo "yes";
} else {
echo "nope";
}

file_put_contents with jquery reload?

I currently have a problem with php and javascript. Here is the thing : I'm trying to edit every few second a text file stored on the server, with the text the client wrote in a textarea (which id is 'area1')
The PHP :
<span id="write">
<?php
if(isset($_POST['text']))
{
file_put_contents('file.txt', $_POST['text']);
}
?>
</span>
The Javascript :
window.onload = function(){
t = setInterval(load, 2000);
function load()
{
$.ajax({
type: "POST",
url: "test.php",
data: {
text: $('#area1').val()
},
dataType: "text",
success: function(data) {
$('#write').load('test.php #write');
}
});
}
}
Nevertheless, nothing is ever written in file.txt, even if we enter the isset condition (that I tested).
Why isn't it working ? Can't we use jquery load with file_put_contents ? Or maybe it is a silly mistake that I can't see...
Thank you !
Have you tried using $.post? It is simpler and clearer.
Below is the full working code.
<html>
<head>
<script src="//code.jquery.com/jquery-2.1.4.min.js"></script>
</head>
<body>
<form>
<textarea id="area1"></textarea>
<textarea id="write"></textarea>
</form>
<script>
$(document).ready(function(){
t = setInterval(load, 2000);
function load()
{
$.post( "test.php", { text: $('#area1').val() })
.done(function( data ) {
$('#write').load('test.php #write');
});
}
});
</script>
</body>
</html>
And also make sure your php script has a privilege to add files.
Use (sudo) chown apache *folder* or similar.
Good luck!

Send HTML form post data to file with Jquery?

I am trying to send post data to my post data file handler called postinfo.php with jQuery but so far I can make it.
Here is my post.php code:
<HTML>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<script type="text/javscript">
$('#form_id').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "http://www.vemvo.com/test/postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
});
</script>
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="submit" id="submit" name="submit" value="Send">
</form>
You can see the page here: http://www.vemvo.com/test/post.php
Here is the code from my postinfo.php:
<?PHP
$ime = $_POST['ime'];
echo "Your name is $ime";
?>
Here is located postinfo.php - http://www.vemvo.com/test/postinfo.php
So where is my mistake and how I can make it work?
Now it's not sending the data and not giving me the success alert.
Your jQuery selector isn't going to find that form, since the selector is running before the form tag exists in the DOM. Try wrapping it in the jQuery function to wait for the document to be ready:
$(function () {
$('#form_id').on('submit', function(e){
// the rest of your code
});
});
It also might be a good idea to return false at the end, to further suppress the form's default post action:
e.preventDefault();
$.ajax({
type: "POST",
url: "./postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
return false;
Currently the form is posting as normal. Since the AJAX handler is never attached (because the element doesn't exist when the selector executes), it's just doing a normal document-level form post. And since there's no action attribute specified in the form tag, the page is posting to itself by default. Which just responds with the current page.
Edit: You also have a typo which may be preventing the browser from executing your JavaScript code at all:
<script type="text/javscript">
You're missing the second "a". This should be:
<script type="text/javascript">
You MUST spell text/javascript correctly
You need to assign the event handler on load
There should not be any need to return false as posted by some other people here
NEVER call anything submit in a form
Wrap your html in body tags
Use a correct DOCTYPE
For files you can have a look at uploadify or How can I upload files asynchronously?
Fixed code for point 1 to 6
<!DOCTYPE html>
<html>
<head>
<title>Test Ajax</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#form_id').on('submit', function(e){
e.preventDefault();
$.ajax({
type: "POST",
url: "./postinfo.php",
data: $(this).serialize(),
success: function() {
alert('success');
}
});
});
});
</script>
</head>
<body>
<form method="post" id="form_id">
<input type="text" name="ime">
<input type="submit" value="Send">
</form>
</body>
</html>

Categories