How do I pass data to a php file using jquery AJAX - php

I'm new to using AJAX methods and am completely stumped with what seems like a very simple procedure.
I'm trying to post data to a php file using AJAX in order to create a folder on my server. No matter what I try it seems as if it's not actually posting data to the php file. I can end up creating a folder directly into the 'users' folder if I remove the $_POST command from the php file... but the second I try to actually create a variable from the posted data so it creates the folder inside of a nested subfolder it fails.
please please please help. I'm losing it. haha.
Someone suggested another thread to solve the problem below... but it still doesn't seem to be working. I'm using the same approach that is suggested in that thread.
Here is my script:
JQuery
<script type="text/javascript>
$('#buildSave').click(function() {
$.ajax({
url: "../php/preparesave.php",
type: "POST",
data: { user : 'Tommy' }
});
});
</javascript>
PHP
<?php
$user = $_POST['user'];
if (!file_exists('../users/' . $user . '/Platoons/')) { mkdir('../users/' . $user . '/Platoons/'); }
?>

Here is the AJAX that I suggest using
$(document).ready(function(){
$('#save').click(function() {
$.ajax({
url: '../php/preparesave.php',
type: 'POST',
data: { user : 'Tommy' },
success: function(output){
alert(output);
}
});
});
});
And below is the PHP (I tried it on my machine and it works)
$user = $_POST['user'];
if(!file_exists('../users/' . $user . '/Platoons/')){
if(mkdir('../users/' . $user . '/Platoons/', 0777, true)){
die('Success');
}else{
die("Folder `../users/{$user}/Platoons/` failed to be created");
}
}
The way you have it, it will only try to create "/Platoon" in a folder $user (Tommy in your example) but that folder doesn't exist and so the script is failing. You need to set the recursive parameter to true so it would first create the folder that doesn't exist and then everything else inside it and then them.
Allows the creation of nested directories specified in the pathname. (Straight from the docs)

There were two errors in your code. Try to compare your lines with the one below.
$('#buildSave').click(function() {
$.ajax({
url: "../php/preparesave.php",
type: "POST",
data: { user : 'Tommy' }
});
});

Try to edit your action url. Use only preparesave.php if you are calling ajax in /php folder. try to use url:"preparesave.php", if this doesnt work then use
url: "preparesave.php?user=Tommy",
Hope it could solve your issue.

THE SIMPLEST POSSIBLE ANSWER
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js</script>
<script>
var cars = ["Saab", "Volvo", "BMW"];
$(document).ready(function(){
$("button").click(function(){
$.post("test2.php",
{
cars
},
function(data,status){
alert("Data: " + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<button>POST the cars array</button>
</body>
</html>
AND THE PHP.....
<?php
$myVar = $_POST['cars'];
$number = count($myVar);
for ($count = 0; $count < $number; $count++){
echo $myVar[$count];
}
?>
enter code here

Related

Call a php function in MVC using AJAX?

I am currently migrating an already built web application to MVC, and I'm figuring out that I'm too newbie to do some kind of changes. There are some ajax calls that are freaking me out. I'll try to be as clear as possible, but due to my inexperience I'm not sure if I won't let some important information by the way.
The point is in the old application, things go this way:
In the php code:
if ($action_user == 'show_alerts') {
$list = array();
$query = "SELECT alert_type FROM alert_contact WHERE NOT
deleted AND user_email=" . typeFormat($email);
$result = mysqli_query($db, $query) or die('Error in query "'.$query . '": ' . mysqli_error($db));
while ($db_field = mysqli_fetch_assoc($result)) {
$list[] = $db_field['alert_type'];
}
echo json_encode($list);
In the jquery code:
$.ajax({
type: 'POST',
url: 'userpost.php',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Here comes my problem, and since I don't have an userpost.php file anymore, I have to send it to the index.php and call my users component by a get petition, which I don't like, but I coudn't find another way to do it. And, what is even worse, I don't know at all how ajax is getting the variables that it needs. It must be a pretty basic mistake, but I recognize my skills at this point are't so good. That's what I'm doing in my version:
In the php code:
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
In the jquery code:
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json',
success: function(data) {
alert ('gotcha');
$.each(alertsarray, function(index, value) {
if ($.inArray(value, data) === -1) {
$("#sub" + value).prop("checked", false);
$('#alert' + value).removeClass("list_alert_sub");
}
else {
$("#sub" + value).prop("checked", true);
$('#alert' + value).addClass("list_alert_sub");
}
});
},
error: function(data) {
alert("¡Error (ajax)!");
}
});
Any help would be appreciated, and if there's some more information I've missed, please let me know. Thanks in advance.
UPDATE:
I've been making some progress but don't seem to find a real solution. Now I know that the url has to be the controller, so I'm using 'components/userpost/controller.php' as it, and it reaches the ajax call, cause the success alert is showing up. The problem is the MVC way, because I send ajax to the controller, but since I don't have a reload in the page, all the includes are failing so they are obviously not being loaded, and I'm getting errors like this:
PHP Warning: include(components/userpost/model.php): failed to open
stream: No such file or directory in
/var/www/html/viewer_mvc/components/userpost/controller.php on line 3,
referer: http://localhost/viewer_mvc/index.php
Really hope you guys can show me where am I failing, and if there's a special way to do these thing in MVC.
For the JQuery call it makes a POST request to index.php?option=users with JSON data. The form with the ID userForm is serialized using the Jquery serialize method.
The .serialize() method creates a text string in standard URL-encoded notation. It can act on a jQuery object that has selected individual form controls
$.ajax({
type: 'POST',
url: 'index.php?option=users',
data: $('#userForm').serialize(),
cache: false,
dataType: 'json'
Now for your PHP sample
if ($action_user == 'show_alerts') {
$list = ModelUser::getAlertContact($act_email);
echo json_encode($list);//I predict that ajax don't reach this line, but not sure
}
This code will be looking for variables that probably don't exist anymore if it is a different file i.e. is there an $action_user variable?
To start reimplementing it you will need to add the logic so that it checks the POST variable if your not using the framework code. So if you have a form element with the name 'name' then that will be available in your PHP script POST variable
$_POST['name']
[How to call a PHP function in MVC using AJAX]
$.ajax({
type: 'POST',
url: 'save-user.php',
data: { fname: "manish", email: "manishkp#com", role:"admin"},
success: function(data) {
console.log(data);
if(data == 'error')
{
$('#Register_error').text('Must Be filled...');
$('#Register_error').show();
}
else {
$('#Register_error').hide();
$('#Register_success').text('Successfully submit');
$('#Register_success').show();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<?php
$fname = $_POST['fname'];
$email = $_POST['email'];
$role = $_POST['role'];
if(!empty($fname) && !empty($email) && !empty($role))
{
#MYSQL CONNECTION QUERY #
echo"success";
}
else{
echo "error";
}
?>

Ajax with CodeIgniter - data not received on server side

I have the following AJAX:
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
})
.done(function(resp){
$('#plant-tree-inner').html(resp);
});
base is my base URL, tree is a controller and plant is a method in that controller.
The URL is correct, the controller and method are in place, with correct names. I've made sure of that by echoing a string in the plant method and it appeared correctly on the client after the AJAX response.
However, none of the post data seems to be arriving at the server.
Doing echo $this->input->post('name'); inside the plant method gives an empty string. Doing var_dump($_POST) gives an empty array. I even tried giving parameters to the plant method but that just throws a missing parameter error.
So where is the data getting lost and why?
EDIT: I see now that my question is wrong. It has nothing to do with CodeIgniter, since the data isn't being sent at all. The field values are undefined according to Javascript, but they certainly exist in HTML:
<input type="text" id="field_treename" placeholder="Tree name" value="" />
Seems like something is wrong with jQuery library.
For test' sake, try to send request avoiding it.
You may try this also..
$.ajax({
type: "POST",
url: base+"tree/plant/",
data:{
name: $('#field_treename').val(),
summary: $('#field_summary').val(),
description: $('#field_description').val(),
address: $('#field_url').val(),
category: $('#field_category').val()
}
success:function(resp){
$('#plant-tree-inner').html(resp);
}
});
Try to simulate the problem in the very basic method like creating another directory in your localhost or server like this and create files as describe below.
in the index.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>POST Sending Problem</title>
<script src="jquery-1.12.2.js"></script>
</head>
<body>
Link
<script src="custom_function.js"></script>
</body>
</html>
Create js file for example test.js and put this as test
function test (id, base) {
$.ajax({
type: "POST",
data: {
'id': id
},
url: base,
success: function(data) {
alert(data);
},
error: function(data) {
alert('no data');
}
});
}
Next create a php file your_phpfile.php
<?php
if (isset($_POST['id'])) {
echo $_POST['id'];
} else {
echo "no-result";
}
?>
This would help you determine the problem. If this works fine, try applying it using codeigniter.
Good Luck
User this one..
var request = "name="+$('#field_treename').val()+"&"
request += "summary="+$('#field_summary').val()+"&"
request += "description="+$('#field_description').val()+"&"
request += "address="+$('#field_url').val()+"&"
request += "category="+$('#field_category').val()
and in set as data=request. This should work.

how to get an array field value from a PHP file using jquery/Ajax in Symfony2?

I am developing a social network web site using Symfony2. In fact, I would like to know how I can get an array field value from a PHP file using jquery/Ajax in Symfony2. Among the files that I have in my project folder there are two files: test.html.twig and moslem1.php. The code of each of that two files is below:
The code of test.html.twig:
<html>
<head>
</head>
<body>
<script src="{{asset('bundles/moslemtest/src/jquery.min.js')}}" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: '{{asset('bundles/moslemtest/phptest/moslem1.php')}}',
type: 'POST',
dataType: 'JSON',
success: function(data1) {
var id=data1.id;
document.write(id);
}
});
});
</script>
</body>
</html>
The code of moslem1.php:
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)) {
$notification = array('id'=>$row['Id'],'subject'=>$row['Subject'],'location'=>$row['Location'],'description'=>$row['Description'],'starttime'=>$row['StartTime'],'endtime'=>$row['EndTime']);
}
echo json_encode($notification);
mysqli_close($con);
?>
The issue is whenever I run the file test.html.twig it displays the out below:
undefined
What is strange is that it works when I put the code of the file test.html.twig in a html file. in fact I created two other files (not in Symfony2) which are t1.html and moslem1.php. their codes are as below:
The code of t1.html:
<html>
<head>
</head>
<body>
<script src="jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'moslem1.php',
type: 'POST',
dataType: 'JSON',
success: function(data1) {
var id=data1.id;
document.write(id);
}
});
});
</script>
</body>
</html>
The code of moslem1.php:
<?php
$con=mysqli_connect("localhost","root","","test");
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM jqcalendar ORDER BY id DESC LIMIT 0, 1");
while($row = mysqli_fetch_array($result)) {
$notification = array('id'=>$row['Id'],'subject'=>$row['Subject'],'location'=>$row['Location'],'description'=>$row['Description'],'starttime'=>$row['StartTime'],'endtime'=>$row['EndTime']);
}
echo json_encode($notification);
mysqli_close($con);
?>
As I said above, it works when I deal with a HTML file, but as I work on Symfony2 I have to use files with "html.twig" extension for view(output). So my question is what shall I do to make it works correctly with my twig file?
Thanks in advance.
It's a very bad idea to put the php file into the bundles folder, it's a huge security issue. If you want an AJAX response then put it into the Controller.
Create a new action in the Controller as you normally do. Write the AJAX action and give back a JSONResponse as a response.
/**
* Return an ajax response
*/
public function ajaxAction(){
// do the controller logic
// $response is an array()
return new JSONResponse($response);
}
Then in jQuery ajax set the url like this:
$.ajax({
url: 'url/to/your/controller', // If you use the FOSJsRoutingBundle then it will be Routing.generate('route_name')
type: 'POST',
dataType: 'JSON',
success: function(data1) {
var id=data1.id;
document.write(id);
}
});
In the new action you can use the EntityManager to access your database.
Here is a good article about this issue: http://symfony2forum.org/threads/5-Using-Symfony2-jQuery-and-Ajax
You should also consider to use the FOSJsRoutingBundle for javascript routing.
It's a very great bundle that allows you to generate routes in javascript files as you can do it in twig with the path('path_name') command.
Here is the GitHub project for this bundle: https://github.com/FriendsOfSymfony/FOSJsRoutingBundle
Try to understand the Symfony Request -> Response process, because if you don't follow it, it will cause serious problems for you.
http://symfony.com/doc/current/book/http_fundamentals.html
http://symfony.com/doc/current/book/page_creation.html

I'm trying to make a PHP variable refresh

So I'm making a website for a client, and the client has tons of photos from tons of different bands they photographed in the 80s and 90s that they would like to try and sell.
Instead of making a page for each band (theres over 100) like the previous site did, I am trying to make one page that uses Javascript/PHP to change the image directory to that band when the text for that band is clicked.
So far, I am able to use a PHP function to find photos in the slideshow folder, but I have been unable to update this function to search through a sub directory in the slideshow folder. (For example, when 'Metallica' is clicked, I empty #imageGal, and then I would like to append all the new metallica images from the metallica folder to the gallery).
My PHP code is:
<?php
$imagesDir = '';
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
This PHP code seems to work great.
I get the images using this JQuery code:
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
When a user clicks on a band (ie Metallica), this code is executed.
$('.options').mousedown(function() {
var name = $(this).attr('id');
//$('#output').html(name);
$.ajax({
type: "POST",
url: "slideshow/getimages.php",
data: {
imageDir: name
}, success: function(msg){
alert( "Data Saved: " + msg );
}
});
$('#imageGal').empty();
$.ajax({
url: "slideshow/getimages.php",
dataType: 'json',
success: function(json){
for(var i=0;i<json.length;i++){
$('#imageGal').append('<img src="slideshow/' + json[i] + '">');
}
}, failure: function(json){
alert('Something went wrong. Please try again.');
}
});
});
I am unable to get the $imagesDir variable to change, but if I were to manually enter "Metallica" in $imagesDir = "Metallica" variable, it loads those images perfectly.
Can anyone offer any help/advice? I've been at this for a many hours now. Thanks for anything!
Unless you have register_globals on then you need to reference the variable through the global $_POST array. $_POST['imagesDir'] instead of $imagesDir.
However I would state in it's current form it would be a very bad idea to simply replace it as someone could attempt to exploit your code to list any directory on the server.
You should append the parent directory to prevent an exploit. Something like this:
EDIT you have to chdir() to the path before glob will work. I've updated my code below.
<?php
$imagesDir = $_SERVER['DOCUMENT_ROOT']; // this is the root of your web directory
$images = array();
// and this line ensures that the variable is set and no one can backtrack to some other
// directory
if( isset($_POST['imagesDir']) && strpos($_POST['imagesDir'], "..") === false) {
$imagesDir .= "/" . $_POST['imagesDir'];
chdir($imagesDir);
$images = glob('*.{jpg,jpeg,png,gif}', GLOB_BRACE);
}
echo json_encode($images);
?>
I'm not an ajax expert but you seem to be posting imageDir.
So your PHP code should be looking for $_POST['imageDir'].
<?php
$imagesDir = $_POST['imageDir'];
$images = glob($imagesDir . '*.{jpg,jpeg,png,gif}', GLOB_BRACE);
echo json_encode($images);
?>
Does this solve it?

update .text() using ajax auto refresh

When I set the session in a file called signin.php:
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'array.php',
type: 'post',
data: {'user': $user}
});
";
In another file (index.php), I want to get:
<?php
session_start();
echo "log in as <span id=\"user\"></span><br/>";
$user = $_POST['user']
echo "
<script>
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
</script>
";
?>
I know I completely messed up with the code. What I want is that when the session is set in the signin.php file, I want $user in the content in "log in as $user" automatically updated without refresh the page, any help will be greatly appreciated!
First, work on diligently formatting your code more effectively. That code you posted was all over the place. This is a bad practice to get in and leads to errors, bugs, and other effects which can be difficult find due to the formatting.
If I follow what you're doing, when someone logs in and then hits the index.php page, you want to be able to load a user's information from another file that will give back the user data asynchronously?
signin.php
Your code is confusing in what it appears to be doing; you simply have not told us enough both in code and explanation to understand what the workflow entails.
For instance, in signin.php, you're echoing a <script> tag that does an $.ajax() request, but who/what get's this code? Is this part of the signin.php content, if the user successfully logs in? Does this mean the signin.php will load the page to use the $.ajax() here, or is that meant to run from the $.ajax() on success?
If it's the latter, you need to return regular Javascript with no markup (like a <script> tag wrapped around it) and use dataType: 'script' in the options.
Also, I would at least use a more descriptive word than array.php; if you're getting user data from it, name that file something like userdata.php.
$user = 'john';
$_SESSION['user'] = $user;
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
dataType: 'script',
data: 'json=' + jQuery.serialize({user: '$user'})
});
";
Then in userdata.php, you can access it with $_POST['json'].
index.php
This honestly makes no sense:
$('#user').text(function() {
setInterval(function(){
$('#user').load($user).fadeIn(10);
}, 1000);
);
Why is the setInterval() in an anonymous function that's run while setting $.text()? This is one of those What? moments, where I'm not even sure what you're trying to accomplish.
Before that though, you have:
$user = $_POST['user'] <<< Note here, you need a ; at the end
Why is this a $_POST? Does the signin.php use $_POST to log a user in? Here, I believe you want $_SESSION (I think, hope, ??), since that's where you stored the username when the user logged in using signin.php.
This is my best guess as to what you're trying to do (assuming you're returning JSON-formatted data):
<?php
session_start();
$user = $_SESSION['user'];
echo "log in as <span id=\"user\"></span><br/>";
echo "
<script>
$.ajax({
url: 'userdata.php',
type: 'post',
data: 'json=' + jQuery.serialize({user:'$user'}),
dataType: 'json',
success: function(data){
$('#user').text(data.fullname);
}
});
</script>
";
?>
Try the following:
<?php
$user = 'john';
$_SESSION['user'] = $user;
?>
<script type="text/javascript">
$.ajax({
url: 'array.php',
type: 'post',
data: { 'user': <? echo json_encode($user) ?> }
});
</script>

Categories