Getting no results when using jQuery to call php - 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.

Related

SyntaxError: JSON.parse?

So i'm making a simple web application to test out Ajax and for some reason i'm getting JSON.parse error although i'm returning my results as JSON using json_encode($results).
The application lets me pick a client and it pulls out that client's orders
JS file :
function getOrders(clientId) {
$.ajax(
{
type: 'POST',
url: "AjaxRequests.php",
data : {
action: 'showOrders',
clientId: clientId
},
dataType : 'json',
success: function(results){
alert(results);
},
error: function(request, status, error){
console.log(clientId);
console.log(request.responseText);
console.log('error : ' + error);
console.log('status' + status);
},
}
)
};
AjaxRequests.php file
<?php
header('Content-Type: application/json; charset=UTF-8');
require_once './GestionClients.php';
if (isset($_POST['action'])) {
if ($_POST['action'] == 'showOrders') {
$clientId = $_POST['clientId'];
$gc = new GestionClients();
$results = $gc->getCmdsByClient($clientId);
echo json_encode($results);
}
}
?>
and this is the results i get in the console after i pick a client (first client in this example with an ID = 1 in the DB) from the selection list:
1 script.js:16:25
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}] script.js:17:25
error : SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data script.js:18:25
statusparsererror
I tried putting that JSON result on an online JSON parser and it looks just fine.
Thank you for your time.
As I so often advise, this problem could have been avoided, or at least quickly identified, by breaking the problem down: you were trying to debug the JS, but that wasn't the part that was broken.
In this case, you have two key pieces:
A PHP script that, when requested with the right parameters, outputs something. You can open this in your browser, and see it for yourself.
Some JS code which requests that PHP script, and parses its content as JSON. You can test this with a PHP script that just echoes {"hello": "world"}, or even a text file uploaded to your server.
Once you know that the JS code works if the JSON is valid, you can basically ignore #2, and look for problems in #1.
If you open the PHP script you wrote in a browser, it will show:
Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]
Now, we know that the JS is going to try to parse this as JSON, so we can do a quick test in our browser's console:
JSON.parse('Connection successfull![{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');
We get a syntax error! Well, of course we do: that "Connection successfull!" wasn't supposed to be part of the JSON.
So we dig into the PHP code, work out where that's coming from, and stop it happening. Now we run the PHP again, and it looks like this:
[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]
Now we can do our JS test again:
JSON.parse('[{"id":"2","date":"2021-02-17","type":"1","payee":"1","idClient":"1"},{"id":"4","date":null,"type":null,"payee":null,"idClient":"1"}]');
Now the error's gone away, and it gives us an array. While we're here, we can look at the structure of the array in the console and make sure it looks right.
Only now do we go back and run the original AJAX call, and see if it's all working. If it's not, we look for other steps we can break out, and repeat the process.

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.

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.

Running a PHP file using AJAX and sending parameters

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.

How can I detect an error in AJAX?

I have a jQuery function, which is using AJAX to send the necessary information to run the respective script properly:
$("#changeUseridForm").submit(function(){
$.ajax({
type: "GET",
url: "API/root/users/changeUsername.php",
data: {
newUsername: ("#newUserid", this).val(),
password: ("#retypePass", this).val(),
xml: 1,
},
dataType: 'xml',
success: function(xml){
if($(xml).find("success").length > 0){
alert("Username changed successfully!");
$("#changeUserid").hide();
$("#BackToMainMenu").hide();
$("#MainPage").show();
$("#AddLinkButton").show();
$("#ChangeUserOptions").show();
$("#ChangeUserDataButton").show();
$("#ShowPosts").show();
}
else if($(xml).find("error").length > 0){
alert("You have to fill all the fields!");
}
}
});
return false;
});
I have several functions like this one, running perfectly; this one isn't. I verified all my variables and scripts. They're spelled correctly. It doesn't reach to the script referenced. I think the AJAX code might have a problem, but I can't detect which error is. I tried to search it on my browser's web inspector, but I can't figure it out since the page is reloading for some reason that I don't know why. (Because this function doesn't have window.location.reload() in it anywhere.)
try to set up a proxy or use firefox plugin to catch the get request(you can also use wireshark)
then you can see if there's a request to this page API/root/users/changeUsername.php
it is possible that this page API/root/users/changeUsername.php returns 302 redirect,
Check the http response of the GET Request and post it please
Look in the docs on .ajax(), you can specify an error handler function that gets details about what went wrong. That would be the first step.
You can also use Firebug's or Chrome's "Net" tab to monitor the request, and see what was returned.
You can detect (debug) a lot of errors using firebug. In this case you can use the net tab and check persists to see what request is causing reloaded page.

Categories