AJAX and 500 Internal Server Error - javascript

I'm building a web application in CodeIgniter and I'm using jQuery and AJAX. I created the whole app locally (using XAMPP) and everything worked fine. After I uploaded the app to my web hosting, one AJAX keeps failing. Here is the part of the code:
// Get all form inputs
var inputs = $('#app-options-existing-form :input[type="text"]');
// Put them in object as name=>value
var data = {};
for(i=0; i<inputs.length; i++) {
data[inputs[i]["name"]] = inputs[i]["value"];
}
// Put loader while AJAX is working
$(".app-content-container").html('<center><img class="loader" src="<?php echo base_url();?>/img/loader.gif" ></center>');
console.log(data);
// Generate POST request
$.post("<?php echo site_url("admin/ajax_app_options"); ?>",
{"add_existing_form_submited" : true, "data" : data2},
function (data) {
alert("test" + data);
});
Here's the console showing error and result of console.log(data)
First, I thought that the key ("d1d1d1") was the problem because I was first using "1-1-1" and after I manually changed it, it was working. But then I changed everything in "d1d1d1" and it doesn't work again. As I said, it works on XAMPP but not on server. Can be a problem in using full URL for AJAX, instead of relative one? But I'm using it in other AJAX requests as well and it works.

Pretty sure you problem is this guy '<center><img class="loader" src="<?php echo base_url();?>/img/loader.gif" ></center>'
Yours source is going to output literally to <?php echo base_url();?>/img/loader.gif which is of course not a real link. Therefore it is a resource that can not be loaded.
You might want to try instead using: '<center><img class="loader" src="/img/loader.gif" ></center>'
The base_url() function is just going to return '/' anyway.
Important! In general you can not write php in javascript. Or this would be a massive security hole that would give every user who visits your site unlimited access to your server.

Related

AJAX returning current page when trying to execute separate PHP query

Okay so, I'm a bit stuck... Here's my problem. So, what I'm trying to achieve is I have a JS calendar and what I want it to do is when I click on a date, it fetches the times available for that day and displays it and then changes depending on what day you click on WITHOUT refreshing the page. Now, looking around, the only way I can seem to do this is with AJAX (suggestions welcome) although I have never touched AJAX before so have no idea what I'm doing here.
So I've currently got my .HTACCESS files setup on my webserver to use dynamic subdomains.
It's sort of like a multi-step form, and I'm collecting data in the SESSION as I go. Now what I'm guessing the way to do is here, to send a AJAX query with a JS variable with the date and then that runs an SQL query and gets the times and displays them. Here's what I have so far.
Update Session
<div class="output"><?PHP echo $_SESSION["outputTimes"]; ?></div>
<script>
$("#clickme").click(function(e) {
e.preventDefault();
$.ajax({
type:'POST',
url:'data.php',
data: { date: '2020-07-04'},
success:function(response){
alert(response);
}
});
});
</script>
data.php
<?php
//Start Session
session_start();
//Include Database Config
include ("config.php");
//POST
$requestDate = $_POST["date"];
//Define SQL Query
$app_get_sql = "SELECT * FROM cc_av WHERE date=$requestDate";
//Run Query
if($result = mysqli_query($db_connect, $app_get_sql)){
while($row = mysqli_fetch_assoc($result)){
$_SESSION["outputTimes"] = '<li>'.$row["time"].'</li>';
}
}
?>
Currently, when I run this, I get the response in the alert() as the current code of the page I'm on. Hence why I noted about my HTACCESS although I can include() it just fine using the same root. Also, from the results of the data.php, how would I output the code sort of update what would be there at the moment.
Here's what I'm trying to create...
https://drive.google.com/file/d/1bgxSUxN6j2IOZcQBuAOo-PeCsuRgdmZ-/view?usp=sharing
Thanks in advance.
So, I've managed to work out what was going wrong. Because my HTACCESS file is creating SubDomains, it was also redirecting the Paths so in the AJAX code I used a URL to the code instead and then added a header to my PHP code on the file that needed to be requested.
header("Access-Control-Allow-Origin: (URL NEEDING TO BE REQUESTED)");
Final AJAX Code
var scriptString = 'THISISMYSTRING';
$('#clickMe').click(function(){
$.ajax({
method: 'get',
url: '(URL)/data.php',
data: {
'myString': scriptString,
'ajax': true
},
success: function(data) {
$('#data').text(data);
}
});
});

JQuery to submit PHP not executing

After hours of playing with this, it hit me that my JQuery simply isn't executing.
I have a page that I am trying to submit to a PHP script without refreshing/leaving the page. If I use a typical form action/method/submit, it inserts into my database just fine. But when I use JQuery, the JQuery will not run at all. The alert does not show. (I'm new to JQuery). I have tried to research this, but nothing is working.
Here is my main page:
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Untitled Document</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(document).ready(function(e) {
$('submitpicks').on('submit','#submitpicks',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
</script>
</head>
<body>
<form name="submitpicks" id="submitpicks" action="" method="post">
<script language="javascript">
var v=0;
function acceptpick(thepick,removepick){
var userPick = confirm("You picked " + thepick + ". Accept this pick?");
//var theid = "finalpick" + v;
var removebtn = "btn" + removepick;
//alert(theid);
if(userPick==1){
document.getElementById("finalpick").value=removepick;
document.getElementById(removebtn).disabled = true;
document.getElementById("submitpicks").submit();
v=v+1;
}
}
</script>
<?php
include "Connections/myconn.php";
//$setid = $_SESSION["gbsid"];
$setid = 11;
$setqry = "Select * from grabBagParticipants where gbsid = $setid order by rand()";
$setresult = mysqli_query($conn, $setqry);
$u=0;
if(mysqli_num_rows($setresult)>0){
while($setrow = mysqli_fetch_array($setresult)){
//shuffle($setrow);
echo '<input type="button" name="' . $setrow["gbpid"] . '" id="btn' . $setrow["gbpid"] . '" value="' . $u . '" onClick=\'acceptpick("' . $setrow["gbpname"] . '", ' . $setrow["gbpid"] . ');\' /><br />';
$u=$u+1;
}
}
?>
<input type="text" name="finalpick" id="finalpick" />
<input type="submit" value="Save" />
</form>
<div id="results"> </div>
</body>
</html>
Here is my PHP:
<?php
include "Connections/myconn.php";
$theGiver = 1;
$theReceiver = $_POST['finalpick'];
$insertsql = "insert into grabBagFinalList(gbflgid, gbflrid) values($theGiver, $theReceiver)";
mysqli_query($conn, $insertsql);
?>
you can use e.preventDefault(); or return false;
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault();
$.post('submitpick.php', $(this).serialize(), function(data) {
$('#results').html(data);
});
// return false;
});
});
</script>
Note: in your php you not echo out anything to get it back as a data .. so basic knowledge when you trying to use $.post or $.get or $.ajax .. to check the connection between js and php .. so in php
<?php
echo 'File connected';
?>
and then alert(data) in js .. if everything works fine .. go to next step
Explain each Step..
before everything you should check you install jquery if you use
<script type="text/javascript" src="jquery-1.11.3.min.js"></script>
from w3schools website.. its totally wrong .. you should looking for how to install jquery ... then
1st to submit form with js and prevent reloading.. and you used <script> in your main page
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
alert('Form submitted Without Reloading');
});
});
<script>
output : alert with Form submitted Without Reloading ... if this step is good and you get the alert .. go to next step
2nd add $.post to your code
<script>
$(document).ready(function(e) {
$('#submitpicks').on('submit',function(e){
e.preventDefault(); //this will prevent reloading page
$.post('submitpick.php', $(this).serialize(), function(data){
alert(data);
});
});
});
<script>
and in submitpick.php >>> be sure your mainpage.php and submitpick.php in the same directory
<?php
echo 'File connected';
?>
output: alert with File connected
Have you heard of AJAX(asynchronous javascript and XML). While it may not be something that is easy to learn for someone who is new to JQuery and javascript, it does pretty much what you need. Well, its a bit more complicated than that, but basically AJAX submits information by using HTTP requests (much like normal forms) but without refreshing the page.
Here's a link to a tutorial: http://www.w3schools.com/ajax/ with vanilla javascript.
Here's one with Jquery: http://www.w3schools.com/jquery/jquery_ajax_intro.asp
And here's an example of how you can set it up with Jquery:
$(document).ready(function() {
$.ajax({
method: "POST",
url: "/something.php"
dataType: "JSON",
data: {formData:{formfield1: $('formfield1').val(), formfield2: $('formfield2)'.val()}},
success: function(data){
if (data["somevalue"]) == something {
dosomething;
} else {
dosomethingelse
},
error: function() {
alert("Error message");
}
});
});
This is only a basic example, now what does all this stuff mean anyway. Well, there are several methods, some of them are POST and GET, these are HTTP request methods, which you can use to do several things. I'm no expert on this stuff, but here's what they do:
Method
POST
POST basically works, to submit information to a server, which is then usually inserted to a database to which that server is connected to. I believe most forms utilize POST requests, but don't quote me on that.
GET
GET on the other hand requests data from a server, which then fetches it into the database and sends it back to the client so it can perform an action. For instance, whenever you load a page, GET requests are made to load the various elements of a page. What's important to note here, is that this request is made specifically to retrieve data.
There are other types of HTTP requests you can use such as PUT and DELETE, which I'd say are the most common along with GET and POST. Anyway I'd recommend that you look them up, its useful information.
Url
The url represents the path to which you are making a request, I'm not exactly sure how it works with PHP, I think you just need to call the PHP page in question and it will work properly, but I'm not sure, I haven't used PHP since my last semester, been using Rails and it doesn't work quite the same. Anyway, lets say you have some PHP page called, "Something.php" and lets say that somethihng PHP has the following content:
<?php
$form_data = $_POST['data'];
$array = json_decode(form_data, true);
do something with your data;
$jsonToSendBack = "{status: 1}";
$response = json_encode($jsonToSendBack);
echo $response;
?>
So basically what that file received was a JSON, which was our specified datatype and in turn after we finish interpreting data in the server, we send back a response through echo our echo. Now since our datatype is a JSON, the client is expecting a response with JSON, but we'll get to that later. If you're not familiar with JSON, you should look it up, but in simple terms JSON is a data exchange format that different languages can utilize to pass data to each other, like in this example, where I sent data to PHP through Javascript and vice-versa.
DataType
Data type is basically, the type of information that you want to send to the server, you can specify it through ajax. There are many data types you can send and receive, for instance if you wanted to, you could send XML or Text to the server, and in turn it should return XML or text, depending on what you chose.
Success and Error
Finally, there's the success and error parameters, basically if a request was successful, it returns a status code of 200, though that doesn't mean that other status codes do not indicate success too, nonetheless 200 is probably the one you'd like to see when making HTTP requests. Anyway, success basically specifies that if the request succeeded it should execute that function code I wrote, otherwise if there is an error, it will execute the function within error. Finally, even if you do have a success on your request, that doesn't mean everything went right, it just means that the client was successful in contacting the server and that it received a response. A request might be successful but that doesn't generally mean that your server-side code executed everything perfectly.
Anyway, I hope my explanation is sufficient, and that you can take it from here.

Minor difficulties with Ajax and PHP interaction

I working in CodeIgniter and I am trying to spit out all of the items I have in a table and order them as they should be using the dropdown. I want it to happen without page reload and without submit buttons, so I am using this jQuery function to make immediately react, when it is changed:
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
Inside you can see the $.post method, with wich I am trying to send the data to php script (orderValue).
After that, I am getting an alert (not even sure, why do I need it (Maybe to check if everything is ok there))
In PHP, I am receiving the chosen select option and assigning a variable ($data['people']) to the results of MySQL query (that is placed in the model) to be able to access it withing the view. This - $_POST['val'] represents, how can I order the list (select * from people order by $theorder" ($theother is just a variable inside the query function. It recieves the value of $_POST['val'])).
if(isset($_POST['val'])) {
$data['people'] = $this->database->listPeople($_POST['val']);
exit;
}
After that I recieve this variable in the view and I am running foreach loop to take different parts of the array(name of the person, his age, etc..) and placing it in the way they should be.
The problem is - if I do that without ajax, when I have static order by value - everything works fine. I did not mean that was the problem :D, the problem basically is that is doesn't work with ajax... I was trying to recieve the array in the js callback and create a layout using
$.each(eval(data), function() {
$('#container').text('<div>' + eval(res).name + '</div>');
});
But that was also a failure...
How should I organize and create my code to make everything work properly?
I am kinda new to Ajax, so I hope I'll really learn how to do that from you guys. I already searched through the whole internet and have seen a lot of ajax tutorials and other kind of material (e. g. StackOverflow), but I still can't get, how can I do all of that in my particular situation. I have wasted already about 12 hours trying to solve the problem and couldn't do that, so I hope You will tell me if there is any useful salvation.
Thank you for your consideration.
Hi the skinny is you need 3 parts to make ajax work,
serverside code to generate the page
ajax ( clientside ) to make the call and respond
seperate serverside to receive it.
Also it will be easier to replace the table completely then to pick out elements. But that is up to you.
So say we have the page with our ajax call
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
alert(data);
});
});
</script>
Now you seem to have some json response I'll assume you get this from the alert above;
[{"id":"1","name":"Nick","age":"18"},{"id":"2","name":"John","age":"23"}]
I'll also assume that this comes from something like
echo json_encode( array( array('id'=>1, ...), array('id'=>2 ...) .. );
It's important before doing the echo that you tell the server that this is json, you do this using a header, but you cannot output anything before the header, and after the json header all output must be in the json format or it wont work, it's like telling the browser that this is html, or an image etc. what the content is.
Header("Content-Type: application/json");
echo json_encode( ....
You can get away without doing this sometimes, but often you'll need to use eval or something, by telling the browser its json you don't need that. Now doing an alert is great and all but if you see the string data [{"id": .. your header is wrong, you should get something like [object] when you do the alert.
No once we have a factual Json object we can make use of all that wonderful data
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
alert(v.id);
alert(v.name);
});
});
});
</script>
This should loop through all the data and do 2 alerts, first the id then the name, right. Next it's a simple matter of replacing the content using .text() or .append()
<script type="text/javascript" >
$(document).ready(function() {
$(".order-by-select").click(function() {var orderValue = this.value;
$.post("<?php echo base_url() ?>welcome/index", {val: orderValue}, function(data) {
$.each(data, function(i,v){
$('#test').append('<p>'+v.id+'</p>');
});
});
});
</script>
<p id="test" ></p>

Calling PHP script with Cordova

I'm working on an app that's supposed to contain the same information as an already existing website.
What I wanted to do was create a Cordova app that calls an external PHP script which in turn gets information from the database that the website is using.
Right now I'm working on calling the PHP script but it just doesn't seem to work.
Here is the script I'm trying to call:
<?php
$a = 1;
$b = json_encode($a);
return $b;
?>
Ofcourse this is just to test the connection. The URL for this file is http://localhost:8888/get_posts.php
Here is the code for the app:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
$(this).find('.homeText').html(data);
});
});
This fetches the file whenever the page is shown (handy) and then puts the new data into the page. The problem is that the page remains empty at all times, when it should be showing a "1". Can anyone see where it goes wrong?
Error message: XMLHttpRequest cannot load localhost:8888/get_posts.php. Cross origin requests are only supported for HTTP.
UPDATE: The error message dissapeared when adding http:// to the url, but the problem persists.
I've changed the code to:
$('#page1').bind('pageshow', function () {
$.get('localhost:8888/get_posts.php', function (data) {
alert(data);
});
});
and it shows me an empty alert box.
Solution: Had to use echo instead of return for the script to show me a result.
http:// was also required so the script is allowed to communicate.
You have to 'echo' your response not returning it like so
<?php
$a = 1;
$b = json_encode($a);
echo $b;
?>

Get Ajax to work for all Users on Wordpress

some Plugins that use Ajax in Wordpress only work when you are logged in as admin or added these hooks:
add_action('wp_ajax_my_action', 'my_action_callback');
add_action('wp_ajax_nopriv_my_action', 'my_action_callback');
But I'm really having a hard time with getting everything to work for non-admin users and I'm wondering if there is a easy way (for js/php noobs) to tell wordpress to globally activate all ajax functions for alls users, wether logged in or not.
I know this is probably a very stupid and risky way if that is possible somehow, but please let me know!?!!?
PHP wise, you've hit the nail on the head with your code above. This is required for each AJAX action, as each action will of course call a different function.
Now, I'm making the assumption that you are using the default Wordpress AJAX call -
jQuery.post(ajax_object.ajax_url, data, function(response) {
If that is indeed the case, for front end calls it is likely that ajax_object.ajax_url is not set. To set this, add the following to your functions.php file -
<?php
add_action('wp_head', 'plugin_set_ajax_url');
function plugin_set_ajax_url() {
?>
<script type="text/javascript">
var ajax_object = {};
ajax_object.ajax_url = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
?>

Categories