At the moment I have multiple forms, and am writing the JavaScript out very simply. I want to create a simple comment system using the following AJAX, but am running into troubles that I cannot sort out..
The AJAX call looks like this:
var dataString = 'commentauthor=' + commentauthor + '&parentid=' + parentid +'&linkid='+
linkid + '&comment=' + comment + '&location=' + location;
alert("check : " + dataString)
$.ajax({
type: "POST",
url: "comments/addcomment.php",
datatype: "html",
data: dataString,
success: function(){
alert('comment added!');
},
error: function(){
alert('failed adding comment!' +dataString);
}
The dataString at all times pulls out the correct information from the forms. Also, the PHP the AJAX is sending it to already works when it's set as the forms action, and all the $_POST[''] names match up.
I've been looking around but can't figure it out. Am I encoding the data wrong or something? The PHP side of things doesn't even get to the AJAX response, so it's got to be just failing to send right?
Also, is there a better way to check JavaScript errors? I've been using the google chrome console but half the time when something goes wrong it doesn't through up an error anyway (like this time)
Is addcomment.php printing anything out? I vaguely remember having a similar problem which was because the PHP file wasn't returning anything. If it isn't, try this before the end of the file:
echo 1;
Related
Please be patient. This is my first post as far as I remember.
This is a part of my calendar.js script. I'm trying to POST data that I fetch from modal window in index.php to sql.php.
function saveModal() { /*JQuery*/
var current_date_range = $(".modal-select#daterange").val();
var current_room_number = $("#mod-current-room-number").val();
var current_room_state = $("#mod-current-room-state").val();
var myData = {"post_date_range": current_date_range, "post_room_number": current_room_number, "post_room_state": current_room_state};
var myJSON = JSON.stringify(myData);
$.ajax({
type: "POST",
url: "sql.php",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
data: myJSON,
beforeSend: function() {
$("#ajax").html("<div class='loading'><img src='/images/loader.gif' alt='Loading...' /></div>");
},
success: function(result){
$("#ajax").empty();
$("#ajax").html(result);
$("#ajax").fadeIn("slow");
window.location.reload(true);
},
error: function(){
alert(myJSON);
$("#ajax").html("<p class='error'> <strong>Oops!</strong> Try that again in a few moments.</p>");
}
})
}
I get the data just fine (as you can see I have checked in the error: function() with alert(myJSON);). It looks like this: {"post_date_range":"12/19/2018 - 12/28/2018","post_room_number":"118","post_room_state":"3"}. Nevermind that the daterangepicker.js returns dates in the hideous MM/DD/YYYY format, which I would very much like to change to YYYY-MM-DD. The real problem is, the code never gets to success: function().
Now my sql.php is in the same folder as calendar.js and index.php.
In sql.php I try to retrieve those values with:
$currentDateRange = $_REQUEST['post_date_range'];
$currentRoomNumber = intval($_REQUEST['post_room_number']);
$currentRoomState = intval($_REQUEST['post_room_state']);
I have checked many other SO Q&As and none have helped me solve my problem. I don't see any spelling errors. It's not disobeying same origin policy rule. I don't want to use jQuery $.post function. Anyone sees the obvious solution?
You want to send array in post rather than the string so directly send myData to get array value in your PHP file rather converting to JSON string It would work with your current PHP file as you require.
You should specify a POST key for the JSON data string you are sending:
var myJSON = JSON.stringify(myData);
(...)
$.ajax({
(...)
data: 'data=' + myJSON,
You need to parse (decode) this string in your PHP file to be able to use it as an array/object again:
$data = json_decode($_REQUEST['data']);
$currentDateRange = $data['post_date_range'];
$currentRoomNumber = intval($data['post_room_number']);
$currentRoomState = intval($data['post_room_state']);
Also, dataType in jQuery.ajax function is specified as "The type of data that you're expecting back from the server." according to jQuery documentation. As far as I can tell from your code, you might rather expect something else as your response, so try excluding this line.
I am sorry to have burdened you all. It's my third week programming so my lack of knowledge is at fault.
I did not know how dataflow works between AJAX and PHP in the URL...
While I was searching for other errors, I printed or echoed out many different things. The PHP file should echo only 1 thing, although it can be an array with multiple values.
Like this for example:
$return_arr = array("sql"=>$sql1, "result"=>$result, "out"=>$out);
echo json_encode($return_arr);
I appologize again.
I am working inside of an Oracle package. I am trying to use an AJAX call to call a procedure from a button click. The ajax call is inside of a function. I am not getting any syntax errors from Oracle or when I'm using the browsers debug mode so I'm not sure what the problem is. Function is below.
htp.p('
function ApplyTest(_ht) {
var _inst = "";
var _pidm = '||v_web_pidm||';
var _inst = document.getElementById("Test").value;
alert("Heat Ticket value is: " + _ht);
alert("the instance is: " + _inst);
var resp = confirm("Are you sure you want patch applied to TEST8?");
if (resp == true) {
alert ("user pidm is: " + _pidm);
return $.ajax ({
type: "POST",
cache: false,
dataType: "json",
url: "gyapatch.p_update",
data: {"v_instance" : _inst, "v_ht" : _ht},
success : function(data) { alert("success"); }
});
alert("Got here");
alert("value: " + _inst);
window.location.reload;
alert("got to the end");
} else {
return;
}
}
');
code for the button is:
<button name="TestApply" id = "Test" onclick="ApplyTest('||val_patch.heat_ticket||')" type="button" value="T">Apply to TEST8</button>'
When I try to return the ajax call nothing is happening and I can't even reach the "Got Here" alert. When I remove the "return" keyword, I can reach the alerts but either way, nothing is happening. GYAPATCH.p_update is the package/procedure I wish to have executed when this is ran
I'm not sure what the problem is. Any help on this would be greatly appreciated. Thanks in advance.
So after a couple of hours, I had figured out the problem. This was more of a learning lesson as the issue was pretty simple. I needed to remember that I was working inside of an Oracle database AND also using WebTailor. The code posted above is correct. It turns out that the procedure I was trying to call (p_update) was not registered.
WebTailor allows you to build web applications utilizing Banner. In WebTailor, any pages that are used (usually stemming from a package.procedure), need to be registered or else they are not recognized.
I found this while debugging. Under the Network tab in my debugger, I noticed that when I click my button, I am getting a 404 error when my package.procedure is called. So I then realized it couldn't find my package and then proceeded to check if it was registered. This was a simple, silly error on my part. I am grateful for the feedback, but this will probably serve as a learning lesson or reminder to anyone trying to use ajax while working with Banner data.
Hello: I am working on a project where I am going to have divisions from a league listed as buttons on a page. And when you click on a button a different team list shows for each division. All divisions and teams are stored in a mysql database and are linked together by the "div_id". The plan was have the buttons use javascript or Jquery to send the 'div_id" to a function; which would then use ajax to access an external php file and then look up all the teams for that division using the div_id and print them on the page. I have been piecing this all together and getting the various pieces to work. But when I put it all together; it seems like the ajax part - does not pull in fresh data from the database if the data is changed. In fact, if I change the PHP file to echo some more data or something, it keeps using the original unaltered file. So, if the data is changed that is not updated, and if the file is changed that is not updated. I did find if I actually copied the file with a new name and then had my ajax call use that file instead; it would run it with new code and the new data at that time. But then everything is now locked in at that point and cannot get any changes.
So - I do not know much about ajax and trying to do this. I am not sure if this is totally normal for what I am using and for a dynamic changing team list, it cannot be done this way with ajax calling a PHP file.
OR - maybe there is something wrong with the ajax code and file I have which is making it behave this way? I will paste in the code of my ajax code and also the php fileā¦
here is the ajax call:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
and here is the script.php file that it calls (removed db credentials):
<?php
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH'])
&& strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest'
) {
// AJAX request
$answer = $_GET['answer'];
$div_id=$answer;
echo "div id is: " . $div_id . "<br/>";
mysql_connect($hostname,$username, $password) OR DIE ('Unable to connect to database! Please try again later.');
mysql_select_db($dbname);
$result_g1 = mysql_query("SELECT * FROM teams WHERE div_id=$div_id");
while($row = mysql_fetch_array($result_g1, MYSQL_BOTH))
{
$team_id=$row[team_id];
$team_name=$row[team_name];
echo $team_id . " " . $team_name . "<br/>";
}
}
?>
So - to sum up - is there something wrong with this making it do this? Or is what it is doing totally normal and I have to find a different way?
Thanks so much...
Most likely your browser is caching.
Try adding cache: false as such:
$.ajax({
cache: false,
type: 'GET',
...
The jQuery documentation explains that by doing so, it simply adds a GET parameter to make every request unique in URL.
It works by appending "_={timestamp}" to the GET parameters.
I believe this is caused by your browser's cache mechanism.
Try adding a random number to the request so the browser won't cache the results:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php?r=' + Math.random(),
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
}
});
Or turning jQuery's caching option off by:
var answer = DivId;
$.ajax({
type: 'GET',
url: 'path_to_file/gscript2.php',
data: 'answer=' + answer,
success: function(response) {
$('#ajax_content').html(response);
},
cache: false
});
Or (globally):
$.ajaxSetup({ cache: false });
I would like to send a large JSON file ( > 110k characters) from javascript to php. I am willing to use any method that will work. I can get around 60k characters using xmlhttp transfer commands but anymore than that and the string is chopped off. Here is a small example of how I am currently performing the transfer:
xmlhttp.open("POST","my.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("obj=" + (JSON.stringify(myObj)) + "&" + "name=" +document.getElementById("textBox1").value);
I have also tried but it makes the string longer which I wouldnt care about as long as it transferred all of the string:
xmlhttp.open("POST","my.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("obj=" + encodeURIComponent((JSON.stringify(myObj))) + "&" + "name=" +document.getElementById("textBox1").value);
There is no limit on HTTP post requests that I know of, if your string is being chopped of it could be to improper formatting or a transfer limit specified on your server.
You could try using Jquery.Ajax it's a wrapper for xhttp protocol:
var name = $('#textBox1').val();
var content = encodeURIComponent((JSON.stringify(myObj)));
console.log(content)
//make sure this is what you expect it is.
$.ajax({
url: 'http://yourserver.com/my.php',
async: false,
type: 'POST',
data: ({'content':content,'name':name}),
dataType: 'html',
success: function(data) {
},
error:function(jqXHR, textStatus, errorThrown){
alert("Error type" + textStatus + "occured, with value " + errorThrown);
}
});
Server:
$data= POST['content'];
Since there was never an answer, the way I fixed this problem was to write a function that chopped the string up into pieces. Then I wrote an ajax function to send the pieces one at a time to the php. On the php side I handled the separate pieces. I would suggest that when you send the string pieces, you also send a number telling the php which piece it is looking at. This is probably not the best way to handle this issue but it works every time so that is good enough for me!
Good luck, if you have any questions then let me know!
I'm not a very experience programmer and have been learning HTML/CSS/JS on the fly. I've been trying to parse XML using jQuery AJAX methods with absolutely no luck.
Here is my code in use: http://jsfiddle.net/Kb5qj/1/
And here is my code in plain sight:
$(document).ready(function() {
var divid = "#xmlcontent"
function parseXML(xml) {
$(divid).empty();
$(xml).find("CD").each(function() {
var artist = $(this).find("ARTIST").text();
var title = $(this).find("TITLE").text();
$(divid).append("<li>" + artist + " - " + title + "</li>");
});
}
function printError() {
$(divid).html("An error occurred");
}
$.ajax({
type: "GET",
url: "www.w3schools.com/ajax/cd_catalog.xml",
dataType: "xml",
success: parseXML,
error: printError
});
});
I don't know what the problem could be. I have written and re-written and copy/pasted that $.ajax call many many times, but no matter what I do nothing ever happens. Help me please?
like I mentioned it will fail on jsfiddle as they dnt actually send the get request. here is the api on how to achieve the same: http://doc.jsfiddle.net/use/echo.html
If you try the same on your local system it will fail probably cos you are making a cross domain request and your browser natively blocks such requests. That is where jsonp comes it to play its to retrieve json data over cross domains..
You can hack it a little to do the same for js.. here is a SO post about the same: Is there an existing tool for jsonp like fetching of xml in jquery?
With a little bit of fudging, everything in the parsing seems to work fine. Check out this JSFiddle.
You can't use get requests from JSFiddle, but I mocked up the XML into HTML. You may want to try placing your XML document into the DOM to help suss your issue.