Ajax, JQuery, GET request with PHP error - php

I have a very basic webpage which contains of two files, phpcode.php.cgi and frontpage.php.cgi.
I have dropdowns that should be populated dynamically, however I can't get the request/reponse to work. The ID of the dropdown is "start".
I have an Ajax request in the frontpage file:
$(document).ready(function () {
$("#start").change(function(){
alert("dropdown changed");
var val = $('#start').val();
$.ajax({
type: "GET",
data: {Station_Nr : val},
url: "phpcode.php.cgi",
success: function(data){
alert(data);
}
});
});
});
and my phpfile looks like this:
<?php
if(isset($_GET['Station_Nr'])) {
echo "it works";
};
?>
It tries to request from url../phpcode.php.cgi?Station_Nr=27
When I try to enter the page I get a 500 error.
According to chrome, the error lies in the row which starts with $.ajax.
I have included:
<script src="//code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
Thanks!

In the top of the file is #!/usr/bin/php5 located.
Here was \r\n added because of Windows and the transfer method was binary. The Apache server responded with an error and when replacing \r\n with \n it works.

When you obtain a 500 error is because something is wrong in server not in client, use /phpcode.php.cgi in $.ajax to use an absolute path just in case.

Related

POST PHP error via Ajax on unsuccessful login

I'm trying to get a Bootstrap Alert to be shown when a user could not be logged in.
To do this, I am using Ajax (jQuery) and POSTing the error upon redirect, to the script on my index.php
Here is the PHP on login.php:
$message = "Your Email or Password combination were incorrect. Please try again.";
echo json_encode($message);
header('Location: /');
and my jQuery:
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: $(this).attr('action'),
data: "message",
success: function (response) {
var message = jQuery.parseJSON(message);
$('#alert').text(message);
}
})
});
</script>
What I'm trying to achieve is:
User tries to log in (and fails)
Redirected to home page (as my login form is in the header)
Error alert is shown, with the $message content as the error text.
When I make an incorrect login (to trigger the error) I get
JSON.parse: unexpected character at line 1 column 1 of the JSON data
I'm still a beginner with jQuery, and have tried to follow other examples which is why my code probably doesn't make sense (and why it isn't working).
I'm using firebug on Firefox to debug the jQuery.
Thanks for your time
I believe your error lies in a misunderstanding of what the line: $(this).attr('action') is doing in your $.ajax call.
When I run your code the function works perfectly... except that it loads the current page! Which is exactly what you told it to do. Sending $(this).attr('action') in the url: parameter just told your ajax function to load the current page. As the current page has javascript and presumably HTML defined in it the response is not valid JSON.
What you want to do is change:
url: $(this).attr('action'),
To:
url: 'path/to/login.php',
i change type and remove comma
make a json request and chage success to done
try this
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function () {
$.ajax({
method: "POST",
url: $(this).attr('action'),
data: "message",
dataType: "json"}).done(function () {
var message = jQuery.parseJSON(message);
$('#alert').text(message);
})
}

Page not loading with AJAX

I am new to AJAX & trying to load a page (test.html) through ajax in to a DIV. I just want to know that is it possible to use AJAX without PHP server (which I am not using at present) or is there any error in the code:
My index.html file is as under:
<! doctype html>
<html lang="en">
<head>
<link rel="stylesheet" href="css/hwcb.css">
</head>
<body>
<input type="button" value="Load" class=”loadpage1”/>
<div id="loadpagea1"></div>
<script src="jquery.js"></script>
<script src="css.js"></script>
<script src="main.js"></script>
</body>
</html>
my test.html file:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
We belongs to a great nation
</body>
</html>
main.js page:
$('.loadpage1').click(function(){
$.ajax({
url:'test.html',
success:function(data){
$('#loadpagea1').html(data);
}
});
});
I just want to know that is it possible to use AJAX without PHP server
Assuming by this you mean without any server in general, then no it is not. You cannot make an AJAX request to the local file system as it will be blocked by the browsers' security settings.
You need to make the request to a server, either local or remote. I would suggest setting up an XAMP server for PHP, or IIS for ASP.Net.
Try this,
var jqXHR = $.ajax({
url: "/test.html",
type: "get",
contentType: "text/html; charset=utf-8",
async: false,
success: function (result) {
}
});
$('#loadpagea1').html(jqXHR.responseText);
$(document).ready(function(){
$('.loadpage1').click(function(){
$.ajax({
url:'test.html',
success:function(data){
var data = $(data);
$('#loadpagea1').html(data.find('body').html());
}
});
});
})
Try this
you have html syntax error, see quotes class=”loadpage1” change with class="loadpage1"

change php variable with ajax

I have an php variable like this:
PHP Code:
$php_value = 'Am from PHP';
And I want to be able to change this variable with jQuery and the jQuery is on the same page?
You can't.
By the time the page has been delivered to the browser and the JavaScript has run, the PHP program that generated the page will have finished running and the variable will no longer exist.
JavaScript will allow you to send new data to the server (Ajax), where the server could store the data somewhere (a database is usual), and read the response.
JavaScript will also allow you to modify the page in in the browser (DOM) (including with the data included in the response for an Ajax request).
PHP code is run server-side, and jQuery runs on the client. The way to update a PHP variable from jQuery is to have a jQuery call which submits to the PHP page, and have the PHP look for it:
$php_value = 'Am from PHP';
if exists($_POST['php_value_from_jquery']) {
$php_value = $_POST['php_value_from_jquery'];
}
If I understand your question correctly, AJAX cannot post data to PHP code on the same page. I've been told that it can, but it is not trivial - still, I cannot imagine how that is possible. At any rate, AJAX is easy if a secondary PHP file is used.
Here is an example of what I mean. If you try this:
<?php
echo 'Hello';
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: '',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body>
</body>
</html>
The popup will contain the HTML for the page.
However, if you use two files:
file1.php
<?php
echo 'Hello';
?>
file2.php
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
type: 'POST',
url: 'file1.php',
success: function(data) {
alert(data);
}
});
}); //END $(document).ready()
</script>
</head>
<body></body>
</html>
The popup will contain only the word "Hello".
To use ajax, you must call an external PHP file.
After considering the above, note that Quentin's answer is important -- even if you use AJAX to set a PHP variable on the server, that variable disappears after the AJAX completes -- just like the PHP variables all disappear after your index.php has finished rendering the DOM and presenting it to the visitor's browser.
So, what's to be done? Two options.
(1) As Quentin points out, you can store values permanently in a database, or
(2) You can use a PHP superglobal, such as a $_SESSION variable. For example:
Client side: file2.php
var storeme = "Hello there";
$.ajax({
type: 'POST',
url: 'file1.php',
data: 'stored_on_server=' +storeme,
success: function(data) {
alert(data);
}
});
file1.php
<?php
session_start();
$SESSION['a_variable_name'] = $_POST['stored_on_server'];
You can later retrieve that variable value thus:
$.ajax({
type: 'POST',
url: 'file3.php',
success: function(data) {
alert(data); //a popup will display Hello There
}
});
file3.php
<?php
session_start();
echo $SESSION['a_variable_name'];
You can't able to change the php value using javascript. i.e Server scripts runs first after that client side script will take effect in that case you cant able to modify the same, since they already rendered in browsers
If jQuery is going to be processing the data, then you can assign the PHP variable to a jQuery variable like this:
<script>
var jquery_value = <?php echo $php_value; ?>
</script>
As far as I know, because jQuery is client-side and php is server side, it's not possible to assign a jQuery variable back to PHP.

dynamic loading of html via php javascript not executing

i have a simple setup, with php pulling html content from a database. if i go to my template page, it loads the data and returns it to the browser via a simple php echo ... not rocket science.
now, i've written an html file using jquery and an ajax call. i load the html file in my browser and the javascript / ajax query works.
when i load the html into the database and print it out via the php / echo, the content is the exact same when i view the source, but the ajax query doesn't execute.
<html>
<head>
<title>random query - api - get</title>
<script src="http://code.jquery.com/jquery-1.5.min.js"></script>
</head>
<body>
<pre>
executing the GET method
<script language="javascript" type="text/javascript">
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){
alert( msg );
}
});
</script>
</pre>
</body>
</html>
Any comments / suggestions would be great. What I find bizarre, is i have no problem copying the source of http://jquery.com/ and pasting it into the db and doing the php / echo. this works fine. maybe an onLoad() would help...hm.
The issue is outlined in the following url:
XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin
When I load the javascript console in chrome I get this:
XMLHttpRequest cannot load http://some-rand.om.api.com/user?011b38b8-011f-4b03-bb21-4c5bb26600b3. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
To resolve the problem, on the api vhost, in the code that serves the content accessed by the ajax query, i added this (it is also php):
header('Access-Control-Allow-Origin: http://some-rand.om.client.com');
Now when I access it, it's all good and loads as expected. So, infact, it wasn't related to it being stored in the database, php or javascript. It was related to cross site scripting.
Or, to be super lazy (probably not a great idea...):
header('Access-Control-Allow-Origin: ' . $_SERVER["HTTP_ORIGIN"]);
If in your description of the problem you are listing the whole of the code, then the JavaScript should be wrapped in a $(document).ready(function(){ ... });.
i.e.
$(document).ready(function(){
$.ajax({
type: "GET",
url: "http://some-rand.om.api.com",
data: "011b38b8-011f-4b03-bb21-4c5bb26600b3",
success: function(msg){alert( msg );}
});
});

Unable to get JQuery to return AJAX data

I'm relatively new to JQuery, so before I try to build the actual app, I'm trying to build a simple Ajax script that'll simply return the data.
However, despite more or less copying and pasting the code, I still can't get it to work.
<html>
<head>
<title>This is a title!</title>
<script src="scripts/jquery-1.4.2.min.js" type="text/javascript" charset="utf-8"></script>
<script type="text/javascript">
$(document).ready(function(){
alert ('1');
$.ajax({
url: 'process.php',
dataType: "html",
success: function(data) {
$('#testsite').html(data);
alert('Load was performed.');
}
});
alert ('2');
});
</script>
</head>
<body>
<div id='login'>
<div id='testsite'>
</div>
<input type='button' id='lsubmit' value='Submit' />
</div>
</body>
</html>
The JQuery script is definitely loaded, process.php is definitely called up (it creates a text file just to prove that it has in fact been run) but anything echo'd in the process.php doesn't get sent through as data.
It's probably something simple, but I've run out of ideas.
Thanks in advance
Okay, this was major stupidity on my part. I messed up the process.php file so it didn't have any data to return
I have no memory of doing this and no idea why I did. Sorry for wasting your time and thanks to all those that helped =]
You will want to add an error handler, see if that gets fired, and inspect the error that is happening.... Add a callback to error.
HTH.
Try using these
$.get('ajax/test.html', function(data) {
$('.result').html(data);
alert('Load was performed.');
});
$.post('ajax/test.html', function(data) {
$('.result').html(data);
});
even you solve yur problem , you can try these

Categories