We are creating an administration console, the client will udpate his site by himself.
To do that, we creating div with js and PHP (ajax) :
$(document).ready(function($)
{
function loadContent(page)
{
$.ajax(
{
url: 'contenu/contenu.php',
type: 'POST',
dataType: 'html',
data:
{
'onglet': page
},
success:function(contenu)
{
console.log("success");
$("div."+page).html(contenu);
}
})
};
});
And the PHP code (just a part of it) :
$reponse = $db->query('SELECT * FROM philosophie');
$data = $reponse->fetch();
//maj de la version FR de philosophie
echo '<form action="#" method="POST">
<label>Texte en français :</label><br/>
<textarea name="texte_fr">'.$data["texte_fr"].'</textarea><br/>
<br />
<input type="button" id="maj_philosophie_fr" value="Mettre à jour ce texte" />
<br /><br />';
The form appears on the site, it's working great.
After, I want to know how many button with id beginning with "maj_" are inside the site with this code :
alert($("[id^='maj_']").length);
I still have 0 as reply.
The element is not ready and I'm not able to get a change event on my divs.
I see the elements in firebug (DOM section), the are in red characters.
Have you an idea please ?
Looks like your alert is running before your success function has been called. Try moving your alert inside there, and better yet, throw it in the next event cycle with a setTimeout.
$(document).ready(function () {
function loadContent (page) {
$.ajax({
url: 'contenu/contenu.php',
type: 'POST',
dataType: 'html',
data: { 'onglet': page },
success: function (contenu) {
console.log("success")
$("div."+page).html(contenu)
setTimeout(function () {
alert($("[id^='maj_']").length)
}, 100)
// might even work with 0, if the dom render function
// is the very next thing in the queue
}
})
}
})
If you have to work with many nested ajax calls, you probably want to look into using the promise api. Here are the docs for the jQuery implementation of $.promise()
Making sure your code runs after a success function has been called is not something that can be worked around. The code can't know about the data ahead of receiving it, this means either nesting your success callbacks, or using other solutions like chaining named function callbacks, or preferably promises.
Related
I try to pass this value to my php code, but I do not know how to do it. post method does not work. (I do not know why).
<script>
var val = localStorage.getItem('sumalist');
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function () {
console.log(val);
}
});
</script>
and in my php code, value is not set.
if (isset($_POST["value"])) {
echo "Yes, value is set";
$value = $_POST["value"];
}else{
echo "N0, value is not set";
}
PS: My php code is in the same file in js code.
Check if this works
<?php
if(!empty($_POST)) {
$value = (isset($_POST["value"])) ? $_POST["value"] : NULL;
$return = ($value != NULL) ? "Yes, value is: ".$value : "N0, value is not set";
echo $return;
exit;
}
?>
<script src="//code.jquery.com/jquery-3.3.1.js"></script>
<script>
var val = 'value sent';
$.ajax({
type: "POST",
url: "index.php",
data: {value: val},
success: function (ret) {
console.log(ret);
}
});
</script>
Open console for result
Please use console if you're using chrome then open console and try debugging,
And first you run that ajax function in jquery ready function like this
$(document).ready(function (){ $.ajax( replaced for ajax function ) }
If you want to use the response in callback success function, use this:
success: function (ret) {
console.log(ret); //Prints 'Yes, value is set' in browser console
}
In your browser you have Developer Tools - press F12 to open, go to Network tab (FireFox, Chrome, IE - all the same), then reload your page and you will see the line for your AJAX call (if it is performed on load, or trigger your call if this is not the case), select it and right hand you'll see a extra frame where you can see all the details of your request, including request params, headers, response headers, the actual response and many other.
That's the best solution to check your AJAX request without asking uncompleted questions and seeking for the answers in case someone can assemble your full case in his mind.
Believe me - this is the best solution for you and not only for this case!
Of course your JS should be performed when DOM is ready so you have to wrap it in
${function() {
// your code here
});
in case you want to be executed on load.
In the middle of a PayPal Checkout Express (client-side) javascript, I need to use AJAX to call the output of a PHP page, but I'm a bit stuck.
The PHP page:
$data = array('retid' => $username);
header('Content-Type: application/json');
echo json_encode($data);
Now inside the other javascript page I simply want to capture the PHP variable $username, via AJAX, as a javascript variable.
<?php
$IDToPassPlus = ($id.'&retid=');
?>
<script>
//It's the inclusion of this part, which tries to get the "retid" js variable, that stops the script from rendering the Paypal button:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
},
});
paypal.Button.render({
env: 'sandbox',
client: {
sandbox: 'xxxxx',
production: 'xxxxx'
},
commit: true,
style: {
layout: 'vertical',
size: 'responsive',
shape: 'rect',
color: 'gold'
},
payment: function(data, actions) {
return actions.payment.create({
payment: {
transactions: [
{
amount: { total: '0.99', currency: 'GBP' }
}
],
redirect_urls: {
'cancel_url': 'pay-return-cancel.php?id=<?php echo $IDToPassPlus; ?>'+retid
}
}
});
},
onAuthorize: function(data, actions, error) {
return actions.payment.execute().then(function() {
window.alert('Payment Complete!');
window.location.replace('test-return.php?id=<?php echo $IDToPassPlus; ?>'+retid);
if (error === 'INSTRUMENT_DECLINED') {
actions.restart();
}
});
},
onCancel: function(data, actions) {
return actions.redirect();
},
onError: function(err) {
window.location.replace('pay-return-error.php?id=<?php echo $id; ?>'+retid);
}
}, '#paypal-button');
</script>
Without the contributor's AJAX suggestion, the button works perfectly. But I'm trying to pass a variable from a PHP page by way of AJAX, to add it onto the redirects.
it's possible to use on in-page javascript as
<script>
var js_var = "<?php echo $php_var;?>";
//now you have php var value in javascript to use on .php page
If it's not what you are seeking, then please elaborate your question.
ok so as far I understood you want to retrieve the PHP response via ajax and you don't know how to make ajax call. Here is an example you may use on your js file:
$.ajax({
type: 'POST',
url: 'YOUR PHP SCRIPT URL',
dataType: 'json',//this will make it understand what datatype to expect in response
success: function(response) {
var retid = response.data.retid; //here you get on successfull response
},
});
First, read this entire page; it will really help you throughout your career as a developer, it has helped me tremendously: https://stackoverflow.com/help/mcve
Then, lets use the knowledge gained from that page to make an MCVE. Put this on a new page:
$.ajax({
type: 'POST',
url: 'test-call.php',
dataType: 'json',
success: function(response) {
var retid = response.data.retid;
console.log(retid);
},
});
This should print the value of retid to your console. Take a look at your console. Notice any errors, or does the value of retid print as expected?
So why have we taken time to create a new page and put this on it? We are narrowing down our issue, we're trying to find the exact cause of the problem by creating an MCVE. If we don't know what is causing the problem, and if we can't create a very basic example to illustrate the problem, we will have a hard time solving the problem and/or asking for help.
(Note 1, make your code "pretty" when you post it here. Indent it as it should be indented; this makes it easier for others to read. You are asking people to take time out of their day to help you, for free; make it as easy as possible for them to read and understand your code)
(Note 2, here is an example of where I had some very, very complicated MySQL interactions that I had a question about. Rather than post all of the complicated code, I followed the MCVE concept: DRY - how to extract repeated code to...a stored function maybe? and made some fake, very very simplified examples of my problem. Since I did that, I was able to get quick, concise answers from experts, notice the answer I accepted was from one of the top-scored users on all of Stackoverflow)
First, precisions : I'm using MAMP and Brackets, and Chrome to test.
Here's what I have :
<ul>
<li class="brick" data-pseudo="one">Some text or elements</li>
<li class="brick" data-pseudo="two">Some text or elements</li>
<li class="brick" data-pseudo="three">Some text or elements</li>
</ul>
li.bricks are just rectangle articles "linking" to Work1, Work2 and Work3, and generated by a PHP function from an array.
I'm trying to get the "pseudo" data of the clicked .brick to put it in a PHP variable and use it to call another array in another php function, in order to generate the HTML elements of Work1, Work2,...
I found I had to use AJAX and managed to get that code :
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
$('.brick').click(function(){
//some code
pseudo = $(this).data('pseudo');
sendPseudo(pseudo); //calling sendPseudo() function
});
And here's my testing PHP function :
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
... I'm calling in my HTML document :
<section class="site">
<div class="left">
<?php loadWork() ?>
</div>
<div class="right">
//some other content
</div>
</section>
And so I have two problems. Firstly, when a .brick is clicked, the alert pops up but it's empty, absolutely nothing appears in it, but when I console.log the var pseudo, I see "one", "two"... And secondly, the echo in testing PHP function does not generate the paragraph with the pseudo.
Pleeeaaase, help me to find out what I'm doing wrong, it's making me go crazy !
Thank you !
I think there is some confusion in your order. loadWork(), as you say, is part of an html file gets called as soon as the browser reads the html file and it's only called once. If loadWork() hasn't been defined yet (or exists in another file as your AJAX request suggests based on it's call to my_php_function_page.php) then it won't output anything. In other words, loadWork() needs its post data to exist when the browser requests the html.
You can put the php in the same file as the html that is being called on, but it looks like you might be trying to get the results of loadWork() inserted into a div that already exists. Change your ajax function so that if(data!="") changes the inner html of your div to include the data:
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
success: function (data) { //testing the success
alert(data);
$('.left').html(data);
},
error: function (errorThrown) {
alert('You are wrong !');
}
});
}
I think you have missed calling your function loadWork() in my_php_function_page.php, this code may be fix your empty alert issue.
var pseudo;
function sendPseudo(info){
$.ajax({
type: "POST",
url: "my_php_function_page.php",
ContentType: 'application/json',
data: {
'data_name': info
},
data=data.trim(); // to remove the unwanted space around the string
success: function (data) { //testing the success
if(data!="")
{
alert(data);
$(".right").html(data); // This adds your AJAX success data to the class left inside your DIV
}
else
{
alert("You're wrong !");
}
},
});
}
my_php_function_page.php
function loadWork(){
$workToLoad = $_POST['data_name'];
echo '<p>'.$workToLoad.'</p>';
}
loadWork();
I'm not sure why, but sometimes data function is not working, so I always use attr('data-pseudo') in your case.
so it would be like this:
pseudo = $(this).attr('data-pseudo');
I have a problem. I am learning React js and I have a template which i must edit. I need to add some ajax methods for getting and sending info. I manage to do some of those actions but now I have a problem.
I have php scripts which is getting me json_encode.
getCategories: function() {
$.ajax({
url: '#########my_url#########',
dataType: 'json',
success: function(data) {
this.setState({datas: data});
}.bind(this)
});
},
and I have this
getInitialState: function() {
return {datas: []};
},
The problem is I always get firstly the empty array and then the result. And when I try to work with it, it gets me error because it tries to map the empty array. This is the console.log before I try to play with the object.
[HMR] Waiting for update signal from WDS...
[]
[WDS] Hot Module Replacement enabled
[Object, Object, Object, Object]
How can I make it to work after the object is full?
First option: render your view on ajax call success
Second option: anticipate the case your state.datas is still empty
for example if you're working in your render function try:
{ this.state.datas ? <div> Loading </div> : <....
Above is JSX syntax
Hope it helps
EDIT:
if(this.state.datas.length == 0) {
var mycomponent =<div> Loading ... </div>;
} else {
var mycomponent = this.state.datas;
}
Basically this should work.
First of all I'd like to ask that you don't suggest I turn to a jQuery plugin to solve my issue. I'm just not willing to make my app work with a plugin (and it prevents me from learning!)
I have a form with a bunch of fields that I'm passing to my backend via the use of jQuery's $.post() This is what I have as my jQuery function:
$.post(
"/item/edit",
$("#form").serialize(),
function(responseJSON) {
console.log(responseJSON);
},
"html"
);
This is how I opened my form:
<form action="http://localhost/item/edit" method="post" accept-charset="utf-8" class="form-horizontal" enctype="multipart/form-data">
This was auto generated by codeigniter's form_open() method (hence why action="" has a value. Though this shouldn't matter because I don't have a submit button at the end of the form)
Within my #form I have this as my file input: <input type="file" name="pImage" />
When the appropriate button is hit and the $.post() method is called, I have my backend just print the variables like so: print_r($_POST) and within the printed variables the 'pImage' element is missing. I thought that maybe files wouldn't come up as an element in the array so I went ahead and just tried to upload the file using this codeigniter function: $this->upload->do_upload('pImage'); and I get an error: "You did not select a file to upload."
Any idea as to how I can overcome this problem?
You cannot post an image using AJAX, i had to find out here as well PHP jQuery .ajax() file upload server side understanding
Your best bet is to mimic an ajax call using a hidden iframe, the form has to have enctype set to multipart/formdata
Files wont be sent to server side using AJAX
One of the best and simplest JQuery Ajax uploaders from PHP LETTER
all you need is include js in your header normally and Jquery code will be like below
$.ajaxFileUpload({
url:'http://localhost/speedncruise/index.php/snc/upload/do_upload',
secureuri:false,
fileElementId:'file_upload',
dataType: 'json',
data : {
'user_email' : $('#email').val()
},
success: function (data, status) {
// alert(status);
// $('#avatar_img').attr('src','data');
}
,
error: function (data, status, e) {
console.log(e);
}
});
wish this can help you
I can't do this with codeigniter and Ajax, I pass the image to base64 and in the controller I convert into a file again
//the input file type
<input id="imagen" name="imagen" class="tooltip" type="file" value="<?php if(isset($imagen)) echo $imagen; ?>">
//the js
$(document).on('change', '#imagen', function(event) {
readImage(this);
});
function readImage(input) {
var resultado='';
if ( input.files && input.files[0] ) {
var FR= new FileReader();
FR.onload = function(e) {
//console.log(e.target.result);
subirImagen(e.target.result);
};
FR.readAsDataURL( input.files[0] );
}
}
function subirImagen(base64){
console.log('inicia subir imagen');
$.ajax({
url: 'controller/sube_imagen',
type: 'POST',
data: {
imagen: base64,
}
})
.done(function(d) {
console.log(d);
})
.fail(function(f) {
console.log(f);
})
.always(function(a) {
console.log("complete");
});
}
//and the part of de controller
public function sube_imagen(){
$imagen=$this->input->post('imagen');
list($extension,$imagen)=explode(';',$imagen);
list(,$extension)=explode('/', $extension);
list(,$imagen)=explode(',', $imagen);
$imagen = base64_decode($imagen);
$archivo='archivo.'.$extension;
file_put_contents('imagenes/'.$archivo, $imagen);
chmod('imagenes/'.$archivo, 0777); //I use Linux and the permissions are another theme
echo $archivo; //or you can make another thing
}
ps.: sorry for my english n_nU