Running a PHP file using AJAX and sending parameters - php

I am trying to edit a file on my server when a user clicks a button on my web page. I generate a table of buttons using php. STRING1, STRING2 and BOOL are variables I pass to my function. The editPlist() function I made is called and the test alert() shows. The problem is that the php file is to run. I am not getting any errors either. I can't seem to figure out what is wrong.
Sample HTML button:
1 : Round 1
The button click runs this script: (the PHP in the url line generates the address of the file I want to run.)
<script type='text/javascript'>
function editPlist(stage, dance, oldValue)
{
alert('test ' + stage + dance + oldValue);
$.ajax({
type: "POST",
url: <?php echo '"'.dirname(curPageURL()).'/PlistEditorFunction.php"' ?>,
data: {"var1" : stage , "var2" : dance , "var3" : oldValue},
success: function(msg){
alert( "Data Saved: " + msg ); //Anything you want
}
});
}
In the external php file PlistEditorFunction.php, I try to log a fake error and load the variables, but the error never shows. this is the beginning of the php file:
$msg = 'test error message';
error_log('['.date("F j, Y, g:i a e O").']'.$msg."<br /> \n", 3, $phperrorPath);
if (isset($_POST['data']) and trim($_POST['data']) != '' ) {
$stage = trim($_POST['var1']);
$dance = trim($_POST['var2'])
$oldValue = trim($_POST['var3']);
}
I know that the php script will only be run if the domain name matches file where the ajax is being run from. The two files are next to each other so I know that this isn't the problem.
What can I do to fix this?

change this line
url: <?php echo '"'.dirname(curPageURL()).'/PlistEditorFunction.php"' ?>
to
url: 'PlistEditorFunction.php'
and see if it works

Several things look strange.
Please verify that the url you call is in fact what you think it is. In order to do that, use a console / inspector. I recommend firebug. When you make the ajax call, it will display the url of the page you're requesting with ajax.
If it is correct, then your url param is not the problem. Next I would look at the php file itself. Try throwing an echo statement in the php file so that way your ajax response can verify that its being run. whatever you echo in the file PlistEditorFunction.php will be the response param in the success function
success: function( response ) {
console.log(response); //should be the echo'd statement of PlistEditorFunction.php
}

After mwotton's comment, I figured out that ajax was undefined. jQuery was imported, so that wan't the problem. I found the answer was I had to change $.ajax to jquery.ajax.
Some hosts don't use "$" to denote jQuery. My web host uses "jquery" instead.

Related

How do I display messages from PHP called from Ajax inside an Azure App

I am trying to do an HTML Contact form that will send an email via MailGun
I am following the instructions here to do this using Ajax and PHP
I have no experience in PHP and want a simple way of debugging.
Thus I want to add popup messages to my send.php
I can get wwwroot\hello.php to work, so I know PHP is available.
<?php
echo("hello php");
?>
I have tried the following in send.php but I do not see any messages
<?php
echo "Hello Send2";
if( isset($_POST) ){
echo "In post.";
phpAlert("in post2");
$postData = $_POST;
$mailgun = sendMailgun($postData);
if($mailgun) {
echo "Great success.";
} else {
echo "Mailgun did not connect properly.";
}
}
// etc
The Ajax call is
var dataString = '<p><strong>Name: </strong> '+ name + '</p><p><strong>Email: </strong> ' + email + '</p><p><strong>Message: </strong> ' + message + '</p>';
$.ajax({
type: "POST",
url: "script/send.php",
data: { data: dataString, senderAddress: email },
success: function() {
alert("Got success");
I do get the javascript "Got success" message but I am trying to troubleshoot why send.php does not work.
I am thinking the first step would be to be able to add calls to echo but nothing shows.
send.php does contain calls to curl so I am guessing my next question may be about how to set that up in Azure, but first I would like to know why echo does not work from inside send.php
You said "I don't see any messages". Since you report that the ajax call completes successfully, then this is simply because your ajax call doesn't print them out. Unlike calling a script directly, when you request via ajax it doesn't automatically echo the response to your browser window - after all, your code doesn't know where within your existing page to put that output, until you tell it. (It can't just place it arbitrarily somewhere, that could potentially wreck your page layout or just look stupid.)
The "success" callback provides a parameter which will contain the response from the server. You need to take that and show it somehow. Here's a very simple example, just showing it an alert box:
success: function(response) {
alert(response);
}
response will contain anything which you echo in the send.php script.
See http://api.jquery.com/jquery.ajax/ to understand what parameters are provided by the various callbacks within $.ajax, and what they contain.
P.S. You can also always see the response to an ajax call, even if you don't use the response within your code, by simply opening your browser's developer tools, going to the Network tab, and looking for the ajax call and viewing the "Response" tab within that call.

Getting no results when using jQuery to call php

Below is the code I'm using to call my validate script. The purpose is to accept input from the user and send it to validate.php to check if what they have entered matches our records and return either a true or false value. I'm getting no response. I've tried <?php echo "Result" ?> just to see if a different value would work. Both are in the same domain so I don't believe it's an issue with origin of both files.
$.get(
"validate.php",
{AN : AccNo, SC : SortCode},
function(data) {
alert('page content: ' + data);
}
);
Update: I've had a look in the network tab as suggested in the debugger and nothing showed and the it said it was out of memory. I'm not too sure why as it isn't a large request.

PHP SCript Not Accepting AJAX Data

This is really bizarre. I am trying to submit data to the server and have a PHP script parse the data and then send back a response. A correctly formed URL is being sent:
http://localhost/ajax/test.html?row=rec_no_1
, but the server does not seem to respond with content from the PHP script despite a return code of 200. In fact, Developer Tools (in Google Chrome) doesn't say anything about the PHP file. The AJAX "data" statement must be formatted properly otherwise I wouldn't get the correct URL. POST (instead of GET) doesn't help.
If I change the AJAX data to a string, then it works fine. This implies there is something wrong with the AJAX data. But I can't understand what given that the URL is correctly formed and does change depending on which row I select.
Any ideas?
Here is the Javascript:
$(document).ready(function() {
$(".submit").click(function() {
$.ajax({
type: 'GET',
url: 'getTable.php',
dataType: 'html',
data: {row: $('input[type='checkbox']:checked').val()},
//data: {row: 'rec_no_2'},
success: function($result) {
$('.tableHolder').text($result);
}
});
return false;
});
});
Here is the PHP code:
<?php
if (isset($_GET['row'])) {
$tableRow = $_GET['row'];
echo $tableRow;
}
else
echo 'TEST';
?>
Your syntax is incorrect:
$('input[type='checkbox']:checked').val()
You should use double quotes around checkbox:
$('input[type="checkbox"]:checked').val()
Anyway do a console.log( $('input[type="checkbox"]:checked').val() ) before the ajax call just to find out which value is being sent.
Try moving your javascript file to server. Ajax don't work on cross domain. You are running the javascript file on localhost and trying to fetch information from live server. Keep both php and javascript file on same server, either live or localhost. It will work fine.
One more thing, try changing the url parameter of your ajax request. try complete url or try putting or not putting a slash / before your filename.

JQuery ajax error

Ok, so my Ajax call looks like this:
var poststring = "id_Client=" + id_client + "&id_File=" + id_file;
alert(poststring);
$.ajax({
type: "POST",
url: "addclpermission.php",
data: poststring,
error: function(xhr, textStatus, errorThrown){
alert("Error: " +textStatus)
}
});
Everything works fine until the $.ajax(). If I use alert(poststring) the output looks like this:
id_Client=7&id_File=32
Using firebug, I found out that the url "addclpermission.php" is actually requested, but then 'aborted'. The path is correct though, if I copy the url out of firebug and call it directly, no error is displayed.
The alert in the 'error' option returns "Error: error"
The file addclpermission.php:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = $_POST['id_File'];
$id_Client = $_POST['id_Client'];
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>
I'm pretty sure this code once worked and that I haven't changed that much.
Any ideas?
Thanks!
Edit: I don't think that the error is in the php script, I have multiple ajax calls to several php scripts, but all of them fail the same way.
Edit 2: Now it works! Well, at least half of it. The request is still aborted, but the data gets inserted in the database. But as I said, this isn't the only ajax call and the others still aren't working, and this one is aborted. So I'd really like to know what caused this error and how I can fix it for good. Thanks!
Does the data get inserted to mysql despite the error? If so, can you put echo on your addclpermission.php file to return 'success' and/or 'fail' for mysql_query()? How about stripping this php file to just echo "hello"???
First, I would try just requesting addclpermission.php in the browser and see what happens.
Then, if that works, what if you just make addclpermission.php contain some text, no PHP content at all. Then for each stage that works, gradually add content (so first the include, for example).
I think the error could be in dbonnect.php or addclpermission.php. Save this in addclpermission.php (make a backup of your current file) and browse to it directly:
<?php
require_once("../allgemein/includes/dbconnect.php");
$id_File = 1;
$id_Client = 1;
$sql = "INSERT INTO permission (id_File,id_Client) VALUES (".$id_File.",".$id_Client.")";
mysql_query($sql);
?>
Please let us know if it works or if you get an error.
When I do jQuery Ajax, I set the data as a Javascript object that jQuery then serializes. Do you have better luck if you provide data: property as an object like this:
data: {
id_Client: id_client,
id_File: id_file
}
I am pretty sure your problem is that you are not returning an expected dataType to the .ajax call, if you explicity set the datatype (json or text for example):
$.ajax({
type: "POST",
url: "addclpermission.php",
data: poststring,
dataType: "json",
error: function(xhr, textStatus, errorThrown){
alert("Error: " +textStatus)
}
});
Then just echo out the expected datatype, just so the server responds, then ajax will know the request was successful.
<?php
// if your dataType is json
echo json_encode(true);
// if your dataType is text
echo ' ';
// exit so the server can return the request
exit;
problem is a --> require_once
require_once("../allgemein/includes/dbconnect.php");
remove this line in a php and write all code here
but I don't know why ?

How to return value using ajax

I have Ajax file in which code has written to accept values form user and then these values are taken in a Ajax function as follows:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(){
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
});
});
The function for passing values and getting values from other file:
function sendValue(str,name){
$.post(
"newsletter/subscribe.php", //Ajax file
{ sendValue: str,
sendVal: name
},
function(data2){
$('#display').html(data2.returnValue);
},
//How you want the data formated when it is returned from the server.
"json"
);
}
and these values are passed to another file called "subscribe.php" in which insertion code to database is written and again I return the value to my first ajax function as follows:
echo json_encode(array("returnValue"=>$msg));
The msg is ging to contain my message to be displayed.
But now, this works fine on localhost, I get the return values nad message properly but when I upload it on server this gives me an error as:
data2 is null
[Break on this error] $('#display').html(data2.returnValue);
This only gives error for return value but insertion, sending mail functionality works fine.
Please provide me with a good solution wherein I can be able to get back the return values without any error.
Thanks in advance.
If it works on your development site, I suspect the error to be in your PHP script.
Your host might run an ancient php version which does not have json_encode().
Simply call the script manually to check its output. If it requires POST you could write a form or check the result to your ajax call with FireBug
Without additional explanation why this is happening, try this:
$(document).ready(function(){
$("#newsletterform").validate();
$('#Submit').click(function(e){ // added the e paramenter
var name = $('#newsletter_name').val();
var email = $('#newsletter_email').val();
sendValue(email,name);
e.stop(); // dont submit the form normaly
});
});
If you have firebug, write data2 to its console and see what it is:
function(data2) {
console.log(data2);
$('#display').html(data2.returnValue);
}
In addition, you can use firebug net panel to see your php file raw response (if it has error - you will see it there).
Use that:
var response = $.ajax({
type : "POST",
url : "newsletter/subscribe.php",
dataType : "json",
async : false,
data : "sendValue="+str+"&sendVal="+name
}).responseText;

Categories