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.
Related
I am using WAMP 3.0.8 PHP 7.0.10 Apache 2.4.23 and trying to build my first JSON API.
The ajax call does send the data to the server. I can see it stored in the text file.
My AJAX looks like this.
$(document).ready(function(){
$('#order').click(function(){
var send = {"name":"Jo Moe", "age":39, "city":"Meridian"};
var prescription = JSON.stringify(send);
$.ajax({
type: 'POST',
dataType: 'JSON',
url: 'https://apa.superserver.com/receive.php',
data: {"scripts": prescription},
success: function(data){
console.log(data);
alert(data);
$('#success').html('<p>Finished</p>');
}
});
});
});
Server side looks like this:
if(isset($_POST["scripts"]) && !empty($_POST["scripts"])){
$sent = filter_input(INPUT_POST, "scripts", FILTER_SANITIZE_SPECIAL_CHARS);
$scripts = html_entity_decode($sent);
file_put_contents("jsonScript.txt", $scripts);
$finish = "Message Received!";
echo json_encode($finish);
}
Now this all worked when it was on the same server. When I separated the receive.php and put it on the remote server. It no longer shows the response.
Thanks!
UPDATE:
Get json ajax php form to work remotely
The link above fixed my issue and gave me more information in the console to figure out what was happening. (I should not have been given a -1) The problem with searching the index here that if you don't use the exact terms in the post it is nearly impossible to find. (my two cents)
Adding the error function and changing from "data" to "response" made the difference along with the xhr. I can see everything.
This my return to the console:
Object {readyState: 4, responseText: "↵↵hello!"Message Received!"", status: 200, statusText: "OK"}
ajax.php:56 parsererror
ajax.php:57 SyntaxError: Unexpected token h in JSON at position 0
at JSON.parse (<anonymous>)
at parseJSON (jquery-1.6.4.min.js:2)
at b$ (jquery-1.6.4.min.js:2)
at w (jquery-1.6.4.min.js:4)
at XMLHttpRequest.d (jquery-1.6.4.min.js:4)
As you can see the response text is what the server is sending back.
I did have to modify my httpd.conf to turn on the mod_headers.c and added an .htaccess .
UPDATE 2:
Figured out what was causing the parse error. I had a print "hello!" line in my server side file that I had there for other troubleshooting. Once I removed it and had only the posted server side code. Everything is peachy now. Onward!!
If I understand correctly You want to make ajax request to another domain. It's blocked because of Same origin policy. To achieve your goal You can implement JSONP
The code/app/repository is on a Zend Server. I update it then use git to push it to github then use phonegap build to build the app. When I test the code in a browser pointed at the Zend Server it works correctly, I get the result "12345". After I have pushed the new code, build the app, update it on my Nexus 7 and run the app I get a crazy result of:
"12345","4746904837" =>"99999","047469048372" =>"88888");foreach ($data as $key => $value){if($key===$qs){$returnData = $value;}}echo $returnData;?>
Why is it giving me all of the script after the matched value?
The $.ajax call
$.ajax({
url: "php/test.php",
data: "qs=9114901075742714812669",
datatype: "text"
})
.done(function( returnData ) {
console.log(returnData);
$( "#info" ).append( returnData );
});
The php
<?php
$qs = $_GET['qs'];
$data = array(
"9114901075742714812669" =>"12345",
"4746904837" =>"99999",
"047469048372" =>"88888"
);
foreach ($data as $key => $value){
if($key===$qs){
$returnData = $value;
}
}
echo $returnData;
?>
AJAX calls are HTTP requests like any other. There's no practical different to the webserver if it was some JS issuing the call, or you typing the url into the browser's address bar. If you're getting code back instead of output, then there's something wrong with your server.
Most likely your browser is getting code back as well, but the <? is causing it to be interpreted as an unknown HTML tag:
<?php
^--- start of "html"
"9114901075742714812669" =>"12345",
^-- end of "html" tag
Hit the address in your browser again and do a "view source" - you'll likely see ALL of the php source code.
Sounds like your server isn't executing the php code but returning the text of the php file. If you replace
$( "#info" ).append( returnData );
with
$( "#info" ).text( returnData );
you'd see that all of the text of your php script is being returned.
Thank you for the responses. The problem was of the newb persuasion related to trying to learn to many things at the same time. The ajax call was pointing to a php script in my github repository...so that would never have worked. I fixed and it points to the server now.
I did learn 1 very important lesson while fixing it.
When using PhoneGap and doing an ajax request make sure to include http:// in the url or it will try to call file://php/test.php.
Thanks for the responses all.
I have found many threads regarding this issue, but unfortunately I couldn't get it running. Problem is I don't know much about JQuery.
I am trying to make an Ajax call using JQuery in order to fetch multiple records from a mysql database. I have the following function :
function updateWebpage ()
{
$.ajax({
url: './sale/api.php', //the script to call to get data
data: "", //you can insert url argumnets here to pass to api.php
//for example "id=5&parent=6"
dataType: 'json', //data format
success: function(rows) //on recieve of reply
{
for (var i in rows)
{
var row = rows[i];
var username = row[0];
var stateId = row[1];
$('#output').append("<b>id: </b>"+username+"<b> stateId: </b>"+stateId)
.append("<hr />");
}
}
});
};
My api.php is executing a mysql query with something like this:
$array = retrieveUsersInfo('%'); //fetch result
echo json_encode($array);
My main issue, is how to debug an issue like this? Since ajax is calling asynchronously another file, I cannot view any errors. From my firefox debugger, I can see that the $.ajax function is entered, but success is not.
Thanks in advance.
a couple things to try.
hit the api url directly in a browser (not through ajax) and make sure it returns the valid response.
add an error: function(err){} to your jquery ajax call. this method will get called if there is something other than a 200 response back from the server.
I use Chrome's developer tools more than firefox/firebug. It has a Network tab in it that shows me all the communication between the client and the server. You should see a call out to your api in that tab.
just off hand, i think you need to make sure the mime-type is set to text/json in your php file.
I am making an ajax call to a php file, But I dont want it to return anything.
My php file has HTML content or rather a JS code, which needs to be executed over there itself. Please help me with this. I dont Know why this is happening
This is my ajax code:
$.ajax({
type : "POST",
url : "<?php echo CALLBACKURL; ?>mobile_profile.php",
data : data,
success: function(response){
}
});
I am not giving any console.log but syill in the response its giving the whole of html
code.
I need to execute that js code there itself and I dont want anything as response Or if we cant do this atleast can i run the JS code return nothing
Where do you want your code to execute? In the browser or at the server?
If you do not want it to contact server and run there itself(inside browser), why are you using AJAX? You simply call a function which will do whatever you want.
on success what do you expect it to do? There is nothing inside the braces...
success: function(response){
}
Browsers cannot process php code. they can process only html and javascripts and some third party scripts with the help of add-ons.
Kindly be clear what you are expecting.
url: "<?php echo CALLBACKURL; ?>mobile_profile.php"
replace it with:
url: "mobile_profile.php"
and put those php tags inside that mobile_profile.php, if required.
If you wish, you can pass parameters to that php file by suffixing your? and a querystring so that the called php file understands what to do.
I think this helps.
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.