So here's the problem:
Trying to make an ajax call using .ajax. However, there's something going wrong somewhere because my controller isn't redirecting to the good view file and nothing is displaying on my page.
Here is where the ajax call happens
$('#validate').on('click',function(){
var data = []; // data container
// collect all the checked checkboxes and their associated attributes
$("table#subsection_table input[type='checkbox']:checked").each(function(){
data.push({
subsectionid : $(this).val(),
sectionid : $(this).data('sectionid'),
year : $(this).data('year')
})
});
// JSON it so that it can be passed via Ajax call to a php page
var data = JSON.stringify(data);
$.ajax({
url : "<?php echo Yii::app()->createAbsoluteUrl("scheduler/AjaxExample"); ?>",
type: "POST",
data : "myData=" + data,
success : function()
{
alert("in success");
$("#ajax-results").html(data);
$("#ajax-results").dialog({ width: 500, height: 500})
},
error: function()
{
alert("there was an error")
}
})
console.log(JSON.stringify(data));
$('#dialog').html(data).dialog({ width: 500, heigh: 500});
});
Now here's my controller code:
public function actionAjaxExample()
{
$post_data = $_POST['myData'];
$this->renderPartial('_ajax', array(
'data'=> $post_data,
)
);
}
trying to redirect to _ajax view file:
<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
echo "HI FROM BACKEND! here's what you gave to PHP: <br>";
print_r($data);
?>
So I'm obviously doing something wrong but... I can't seem to find where because the ajax call DOES happen ( at least in my #validate on click event). However, the last view file isn't displaying it's alert box OR the "hello from back end".
Try :
remove var data = JSON.stringify(data);
change
data:{myData:data},
I think the issue is with the quotes of the url.
Please check if you are getting some JavaScript error in console.
If you are getting some error, Please change this
$.ajax({
url : "<?php echo Yii::app()->createAbsoluteUrl("scheduler/AjaxExample"); ?>",
type: "POST",
to
$.ajax({
url : '<?php echo Yii::app()->createAbsoluteUrl("scheduler/AjaxExample"); ?>',
type: "POST",
If not getting any error, Please check the xHr tab in console, whats the url, your ajax is hitting. Please let me know in case of any issue
Related
i need help because i'm stuck and don't know what's wrong ,i try to send user clicked button "id" to php to get related data from database in the same page
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
console.log(res, data);
},
error: function(err) {
alert(err);
}
});
});
the ajax print success in console log ,here is php code to get the value if clicked id
<?php
if(isset($_POST['ToEditId'])){
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
}
but nothing happen in php file !!
Which is the expected behaviour.
PHP is not dynamic. It doesn't "update".
PHP only runs once. This means that once your page is rendered, you cannot use PHP to change it again. You actually would have to use javascript to change the page, like so;
PHP side:
<?php
if(isset($_POST['ToEditId'])){
echo $_POST['ToEditId'];
$to_edit_id=$_POST['ToEditId'];
var_dump($to_edit_id);
die(); // prevent entire page from re-rendering again.
}
JS side:
$(".button_class").on("click", function() {
ToEditId = $(this).attr('id');
console.log(ToEditId ); //to check clicked id is Ok
$.ajax({
type: "POST",
url: same/php/page/path,
data: {
ToEditId: ToEditId
},
success: function(res, data) {
//Add your PHP file's response to the body through javascript.
$('body').append(res);
},
error: function(err) {
alert(err);
}
});
});
As #IncredibleHat mentioned, you should make sure your page doesn't render any of its usual HTML, so it won't return the entire page back to your ajax call. So put the PHP all the way above your html!
My AJAX call previously returned an array of data as JSON using "echo jason_encode(array)" in my PHP code and I then looped through the result in my script and built the HTML using the returned data before displaying.
Now I changed the code to build the HTML in my PHP code and I want to return the HTML string to my script and display the HTML but I have no idea how to get it working and I have looked at over a dozen examples on this site and others but no luck.
PHP
$html = '<tr><td><div class="dummy">This is some text.</div></td></tr>';
$arr[] = array('html' => $html);
echo json_encode($arr);
Script
<script type="text/javascript">
$('.mashed_row a').click(function () {
var link_id = $(this).attr('link_id');
$.ajax({
type: 'POST',
url: 'explode',
data: {'<?php echo $this->security->get_csrf_token_name(); ?>' : '<?php echo $this->security->get_csrf_hash(); ?>', link_id},
dataType: 'json',
success : function(data) {
if(data)
{
var txt = data['html'];
$("#xarticletab").html("");
$("#xarticletab").append(txt).removeClass("hidden");
$("#comments").removeClass("hidden");
}
}
});
return false;
});
</script>
First of all, I think there is an error on your JS code: link_id alone.
on JS, you should define key: value. So, maybe 'link_id': link_id ?
Correct typo: {key1: 'value1', 'key2': 'value2'}
After, use console editor of your browser to know if there is any Javascript error.
Alternatively, you can play with javascript functions: console.log(data); or event alert(data)
So I have a page index.php?packageID=153. That page has a form which when submitted is sent to PHP via Ajax call
<script type="text/javascript">
$(document).ready(function()
{
$(document).on('submit', '#form_name', function()
{
var data = $(this).serialize();
$.ajax({
type : 'POST',
url : 'phpfile.php',
data : data,
success : function(data) {
$('.result-modal').html(data);
},
error: function (request, status, error) {
alert(error.responseText);
//or console.log(request.responseText), or status or error;
}
});
return false;
});
});
</script>
I want to get that ID from the URL. I usually just do $_GET['PackageID'] (in my PHP file) to get the ID from the URL when I'm not using Ajax, but it doesn't work with ajax (from what I'm experiencing). How do I get That ID in my PHP file?
Two possibilites:
You insert the PackageID as a GET parameter into the url:
url : 'phpfile.php?PackageId=<?php echo $_GET['PackageID']; ?>',
You insert the parameter into the JavaScript data object like:
var data = $(this).serialize();
data.PackageId = <?php echo $_GET['PackageId']; ?>;
$.ajax({
[...]
However you do it, at some point you have to output text from PHP inside your JavaScript code.
It's a PHP file so you can still use PHP. Add something like this at the top of the file.
<?php
echo '<script>';
echo "var id = $_GET['packageID']";
echo '</script>';
?>
I want to send my request to CodeIgniter to get response from my database:
$(document).ready(function(){
$('.confirm_send').on('click',function(){
var base = '<?php echo base_url(); ?>';
var confirm_send_id=$(this).attr('id');
$.ajax({
'url': base + 'my_site/confirm_send',
'type':'post',
'dataType':'json',
'data':{
'id':confirm_send_id
},
'success':function(){
alert("sucssess");},
'error':function(){
alert("Error");
}
});//end of ajax confirm send button
});//end of confirm send button
});//end of jquery
But I am getting an error.
Try This:
$('.confirm_send').on('click',function(){
var base = '<?php echo base_url(); ?>';
var confirm_send_id = $(this).attr('id');
$.ajax({
url: base + 'my_site/confirm_send', //make sure it is a valid path
type: 'POST',
data:({'id':confirm_send_id}),
success : function(response){
alert("Success");
},
error : function(response){
alert("Error");
}
});//end of ajax confirm send button
});
Its a server side coding issue thats why it`s getting issue you can check error using response window it will display coding error.
You can't inject PHP code into JavaScript. Remember that whatever script or css that you define will be run in the user's browser - and browsers don't interpret PHP code neither have direct access to your server.
You've gotta hard-code the base_url variable.
If you don't know it just echo base_url(); on a page and copy it.
$(document).ready(function(){
$('.confirm_send').on('click',function(){
var base = 'http://yourproject_base_url'; //Set the full base url manually here.
var confirm_send_id=$(this).attr('id');
$.ajax({
'url': base + 'my_site/confirm_send',
'type':'post',
'dataType':'json',
'data':{
'id':confirm_send_id
},
'success':function(){
alert("sucssess");},
'error':function(){
alert("Error");
}
});//end of ajax confirm send button
});//end of confirm send button
});//end of jquery
I wonder how I can pass value from Jquery to PHP. I found similar codes but not even one of them work.
Everytime alert shows value of variable but when I open site there is not any. Var_dump shows that $_POST is null. I am ran out of ideas do you have any?
jQuery code:
$("#password-button").click(function(){
var password="";
var numbers =[0,0,0,0,0,0];
for(var i=0;i<=5;i++){
numbers[i] = Math.floor((Math.random() * 25) + 65);
password += String.fromCharCode(numbers[i]);
}
$(".LoginError").text("Nowe haslo: " + password);
$.ajax({
type: 'post',
url: 'dzialaj.php',
data: {'password': password},
cache:false,
success: function(data)
{
alert(data);
console.log(result)
console.log(result.status);
}
});
});
PHP:
if(isset($_POST['password'])){
$temp = $_POST['password'];
echo $temp;
}
Since it looks like you are new on ajax, let's try something more simple ok? Check this js:
<script>
var string = "my string"; // What i want to pass to php
$.ajax({
type: 'post', // the method (could be GET btw)
url: 'output.php', // The file where my php code is
data: {
'test': string // all variables i want to pass. In this case, only one.
},
success: function(data) { // in case of success get the output, i named data
alert(data); // do something with the output, like an alert
}
});
</script>
Now my output.php
<?php
if(isset($_POST['test'])) { //if i have this post
echo $_POST['test']; // print it
}
So basically i have a js variable and used in my php code. If i need a response i could get it from php and return it to js like the variable data does.
Everything working so far? Great. Now replace the js mentioned above with your current code. Before run the ajax just do an console.log or alert to check if you variable password is what you expect. If it's not, you need to check what's wrong with your js or html code.
Here is a example what i think you are trying to achieve (not sure if i understand correctly)
EDIT
<script>
var hash = "my hash";
$.ajax({
type: 'post',
url: 'output.php',
data: {
'hash': hash },
success: function(data) {
if (data == 'ok') {
alert('All good. Everything saved!');
} else {
alert('something went wrong...');
}
}
});
</script>
Now my output.php
<?php
if(isset($_POST['hash'])) {
//run sql query saving what you need in your db and check if the insert/update was successful;
// im naming my verification $result (a boolean)
if ($result) echo 'ok';
else echo 'error';
}
Since the page won't redirect to the php, you need a response in you ajax to know what was the result of you php code (if was successful or not).
Here is the others answers i mentioned in the coments:
How to redirect through 'POST' method using Javascript?
Send POST data on redirect with Javascript/jQuery?
jQuery - Redirect with post data
Javascript - redirect to a page with POST data