there's something strange going on in my ajax code. I'm have some difficulty narrowing it down.
JavaScript:
//Discard Displaying Cards
$(".discard").click(function(){
var gameId = 20;
var cardArray = [];
$( ".card" ).each(function() {
var cardId = $(this).attr('id');
cardArray.push(cardId);
});
$.ajax({
type: 'POST',
url: './system/actions/discard.php',
data: "gameId=" + gameId + "&cardArray=" + cardArray,
success: function(data) {
console.log(cardArray);
console.log("Success.");
console.log(data);
}
});
});
The javascript posts to a file discard.php where it is given two parameters: gameId and cardArray. gameId is static right now, but cardArray is made up of the DOM ids of each of the ".card" elements loaded on the page. Each DOM id reflects the card_id in my database.
discard.php
//Classes
include $_SERVER["DOCUMENT_ROOT"] . '/system/classes/cards.php';
header("Content-Type: text/html");
$gameId = empty($_GET['gameId']) ? '' : $_GET['gameId'];
$numbers = empty($_GET['cardArray']) ? '' : $_GET['cardArray'];
$regex = preg_replace('/[^,;a-zA-Z0-9_-]|[,;]$/s', '', $numbers);
$cardArray = explode(",", $regex);
foreach ($cardArray as $cardId) {
discardCards($cardId, $gameId);
};
The discard.php is supposed to read the $_GET headers from the ajax request. But for some reason, it fails. The funny thing is, if I call the page directly with manual GET headers, e.g I browse to:
domain.com/system/actions/discard.php?gameId=20&cardArray=["1","3"]
OR even
domain.com/system/actions/discard.php?gameId=20&cardArray=1,3
The script works fine!
I thought it may have been something with the format ajax is posting in, hence the regex, but alas, it did not work. Because I'm not even sure how to display or view the requested ajax data URL on the page it called on, I'm finding it particularly difficult to debug.
Any suggestions? Thanks in advance.
You are using:
type: 'POST',
But you are receiving it as $_GET, change it to $_POST:
$gameId = empty($_POST['gameId']) ? '' : $_POST['gameId'];
$numbers = empty($_POST['cardArray']) ? '' : $_POST['cardArray'];
Or change the AJAX function to:
type: 'GET',
And also, the data is supposed to be a string. So use serialize():
$(form_id).serialize();
Where form_id is the id of the form.
Related
So, I'm trying to figure out how I can determine if a PHP script redirects in the middle of an AJAX call. Anyone know whether or not JQuery AJAX is aware of/tracks location changes?
The scenario would be something like this...
function createOrder()
{
var contentRequest = $.ajax({
url : '/orders/create',
method : 'POST',
data : '',
success : function( data, status, xhr )
{
// Detect the header change in 'create.php' here,
// perhaps update the history/current url.
}
};
create.php
<?php
$NewOrder = Order::CreateNew();
header("Location: /orders/edit?orderID=$NewOrder->ID");
?>
Probably could have done a little more digging on my own, but...
function createOrder()
{
var contentRequest = $.ajax({
url : '/orders/create',
method : 'POST',
data : '',
success : function( data, status, xhr )
{
var responseURL = xhr.getResponseHeader('Location');
}
};
Seems to be the solution.
Trying to insert a car image from one of my databases into my webpage
get_new_car_pictures:
$make = $_REQUEST['make'];
$model = $_REQUEST['model'];
$query = "SELECT * FROM database_new WHERE make = $make AND model = $model";
$car = $db->get_row($query);
$img = $car['img_url'];
echo "<img src=".$img." />";
ajax function:
function insertImageAJAX(){
return $.ajax({
type: 'GET',
url: '/ajax/get_new_car_pictures.php',
data: "model=" + params.model + "&make=" + params.make,
success: function(data){
$("#car-image".html(data));
}
}
});
car-image is the div where I want the image to appear
I have tried to follow Ajax tutuorials online but for whatever reason, this is not working...
use concatenation on query and varchar has to be in single quotation
$query = "SELECT * FROM database_new WHERE make = '".$make."' AND model = '".$model."'";
and also fix js
function insertImageAJAX(){
return $.ajax({
type: 'GET',
url: '/ajax/get_new_car_pictures.php',
data: {'model':params.model, 'make': params.make},
success: function(data){
$("#car-image").html(data);
}
}
});
For one thing, you've misplaced a parenthesis:
$("#car-image".html(data));
should be
$("#car-image").html(data);
Try adding an error callback to take a closer look at what's going on.
jQuery Ajax error handling, show custom exception messages
Also, I'd recommend setting the image's src attribute with the response instead of setting its HTML.
Let me know what the error says and we can go from there.
This question already has an answer here:
ajax request without data not working
(1 answer)
Closed 8 years ago.
I have asked this earlier but still I wasn't lucky to get it work. Simply I am trying to update profile picture with a default picture when Delete button is clicked and I am trying to use ajax to do this, however whenever I click on the button nothing happens and the picture is not updated. I have tested the php page by itself and it works nicely but the js isn't working so could someone spot what I am doing wrong here?
html
<button href="javascript:void(0);" onclick="delete;" class="btn btn-default delbutt">Delete</button>
js
function delete()
{
$.ajax({
type: "POST",
url: "test.php?action=delete",
cache: false,
success: function(response)
{
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
});
}
and here is the php lastly
$username = $_SESSION["userCakeUser"];
if(isset($_POST["action"]) && !empty($_POST["action"]) || isset($_GET["action"]) && !empty($_GET["action"]))
{
if(isset($_GET["action"]) == "delete")
{
$profile = 'default.jpg';
$pp = $db->prepare("update users set profile = ? where username = ?");
echo $db->error;
$pp->bind_param('ss', $profile, $username->username);
$pp->execute();
}
}
else {
echo "Something is wrong. Try again.";
}
POST queries are by default not cached in jQuery ajax (1), so you probably should just use the $.post helper instead. Also, querystring values are not parsed to the $_POST super-global, so your code as-is will always read null from $_POST["action"].
function delete(){
$.post(
"test.php",
{
action: 'delete'
},
success: function(response){
var $divs = $("<div>" + response + "</div>");
$("#phd").fadeOut('slow');
$(".suc_pic").fadeIn('slow').empty().append($divs.find("#msg"));
}
);
}
(1) As defined in the API reference:
Pages fetched with POST are never cached, so the cache and ifModified
options in jQuery.ajaxSetup() have no effect on these requests.
It is my understanding that jQuery AJAX requests should have a data: option in there somewhere. Also, I see you're using GET to make the request, but tell jQuery to use POST.
$.ajax({
type: "GET",
url: "test.php",
cache: false,
data : {
action : 'delete'
success : function(response)
{
etc...
I'm no jQuery expert, but I think that may be your problem. The only other thing I can think of is the success function isn't working properly. Check your F12 menu and post any warnings/errors so we can see it.
I have this code below:
<?php
$stmt = $pdo_conn->prepare("SELECT * from controldata where field = :field ");
$stmt->execute(array(':field' => 'notice_board'));
$result = $stmt->fetch();
?>
<textarea id="notice_board_textarea" data-id="notice_board" rows="8"><?php echo stripslashes(strip_tags($result["value"])); ?></textarea>
<script type="text/javascript">
$('#notice_board_textarea').on('blur', function () { // don't forget # to select by id
var id = $(this).data('id'); // Get the id-data-attribute
var val = $(this).val();
$.ajax({
type: "POST",
url: "dashboard.php?update_notice_board=yes",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id // Id of the item stored on the data-id
},
});
});
</script>
which selects data from a MySQL database and shows it in a textarea
then then JS code updates it by POSTing the data to another page but without refreshing the page or clicking a save/submit button
on dashboard.php i have this code:
if($_GET["update_notice_board"] == 'yes')
{
$stmt = $pdo_conn->prepare("UPDATE controldata SET value = :value WHERE field = :field ");
$stmt->execute(array(':value' => $_POST["notes"], ':field' => 'notice_board'));
}
but its not updating the data
am i doing anything wrong?
Wrong:
if ($_POST["update_notice_board"] == 'yes') {
Right:
if ($_GET['update_notice_board'] == 'yes') {
When you append something straight to the URL, it is ALWAYS GET:
url: "dashboard.php?update_notice_board=yes",
Updated answer:
Based on what's written in the comments below, my guess is, it is a server side issue, beyond what is shared here. Perhaps dashboard.php is part of a framework that empty the super globals or perhaps the request is not going directly to dashboard.php
Old suggestions:
When you use type: "POST" you wont find the parameters in the $_GET variable. (U: Actually you probably would find it in $_GET, but in my opinion it's cleaner to put all vars in either $_GET or $_POST, although there may be semantic arguments to prefer the splitting).
Add your parameter to the data object of your ajax call and read it from the $_POST variable instead:
$.ajax({
type: "POST",
url: "dashboard.php",
data: {
notes: val, // value of the textarea we are hooking the blur-event to
itemId: id, // Id of the item stored on the data-id
update_notice_board:"yes"
},
success: function(reply) {
alert(reply);
},
error:function(jqXHR, textStatus, errorThrown ) {
alert(textStatus);
}
});
and
if($_POST["update_notice_board"] == 'yes')
(You may also look in $_REQUEST if you don't care whether the request is get or post.)
Compare the documentation entries:
http://www.php.net/manual/en/reserved.variables.get.php
http://www.php.net/manual/en/reserved.variables.post.php
http://www.php.net/manual/en/reserved.variables.request.php
Working client-side example:
http://jsfiddle.net/kLUyx/
I have been trying to create an ajax request in codeigniter. I've seen this question: Simple Ajax/Codeigniter request but I wasn't able to absorb that as there were the answers in which people were using PHP inside Javascript. I didn't know it was possible, however I gave that a try but it seems like the PHP wasn't being executed.
So here are my questions:
Is it really possible to use PHP inside Javascript, or am I mistaken?
What's the right way to perform an Ajax request in Codeigniter? What I've tried is the following:
var param = {name : event_name, date : event_date, time : event_time};
$.ajax({
// As seen from the question here at stackoverflow.
url : "<?php echo base_url('event/new_event'); ?>",
type : 'POST',
data : param,
beforeSend : function(){ },
success : function(){
alert("Event created! Feel free to add as much details as you want.");
namebox.val("");
$("#new-event-modal").find(".close").trigger('click');
window.location.href = "<php echo base_url('user/dashboard'); ?>";
},
complete : function(){ },
error : function(){ }
});
I know the possibility that I could hardcode the URL in the request but that wouldn't be a good practice!!
the easiest way for you to accomplish this is by using some jquery:
function getBaseUrl() {
var l = window.location;
var base_url = l.protocol + "//" + l.host + "/" + l.pathname.split('/')[1];
return base_url;
}
var postdata = {name : event_name, date : event_date, time : event_time};
var url = getBaseUrl()+"/event/new_event";
$.post(url, postdata, function(result){
...alert(result);
});
or call it straight from JS by caching it:
<script>
var test = "<?php echo base_url(); ?>"+"event/new_event";
alert(test);
</script>
Here is a dirty hack that I was going to use:
Create a hidden field somewhere on the page and when this page loads echo out the base_url() as the value of that hidden field.
Now when you want to make an ajax request, access that hidden field
and grab the base url and use it however you want.
The right way is always the simplest way, there is no need to import Jquery in your client if you are not already using it.
This is your controller
<?php if (!defined('BASEPATH')) die();
class Example_ctrl extends CI_Controller {
public function ajax_echo()
{
// get the ajax input
$input = json_decode(file_get_contents('php://input'));
// $input can be accessed like an object
$password = $input->password;
$name = $input->name;
// you can encode data back to JSON
$output = json_encode($input);
// and the response goes back!
echo($output);
}
}
?>
This goes into your client
<script>
// here's the data you will send
var my_data = {name: "Smith", password: "abc123"};
// create the request object
var xhr = new XMLHttpRequest();
// open the object to the required url
xhr.open("POST", "example_ctrl/ajax_echo", true);
// on success, alert the response
xhr.onreadystatechange = function () {
if (xhr.readyState != 4 || xhr.status != 200)
return;
alert("Success: " + xhr.responseText);
};
// encode in JSON and send the string
xhr.send(JSON.stringify(my_data));
</script>
There is no better way to do this .
Php codes can't be executed from external javascript files.
Try any of these :-
1) base_url() is something's that's will not change , better store it in cookie and then access it in both server side code and client side code
2) you can store the same base_url() in local storage , it will be available in your external JavaScript files
Hope it helps you :)