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');
Related
I have one Ajax function which is running properly.but i want when my Ajax response is
<h3>No Couriers found near by you.please select another location</h3>
i want to display some error message else i want to display another map div in else condition.
but every time when i hit Ajax only else condition is working..but when i alert response and see the output it shows this message when
<h3>No Couriers found near by you.please select another location</h3>
but still it not comes in if condition..can anyone help me to do this....
<script>
$('#weight0,#weight1,#weight2,#weight3').click(function() {
var checked = $(this).is(':checked');
if($(this).is(":checked")) {
$.ajax({
type: "POST",
url: '<?php echo Router::url(array("controller" => "Orders","action" => "searchCourier")); ?>',
data: {
frmlat: $("#PoolLatitude").val(),
frmlong: $("#PoolLongitude").val(),
mylocation: $("#PoolLocation").val()
},
dataType: "html",
success: function(response) {
alert(response);
if(response =="<h3>No Couriers found near by you.please select another location</h3>"){
alert(thanks);
} else {
$('#map_canvas').css('display', 'none');//used to hide map after ajax success response.
$("#load_map").html(response);
}
},
complete: function() {
$('.spinicon').hide();
}
});
} else {
$("#secretcode").val("");
}
});
</script>
In your php script, return a boolean flag instead of a string :
<?php
if (some_condition) {
$return = true;
} else {
$return = false;
}
die(json_encode(array('return' => $return)));
And in the ajax success :
...
dataType: 'json',
success: function(data) {
if (data.return) {
alert("return is true");
} else {
alert("return is false");
}
},
...
Hope it helps.
PS : use Json Encode to parse the response and access values easily.
First of all, i suggest you to use status for ajax response something like:
1 for success
0 for failure
Than, as per your statement, your are getting the correct response in:
alert(response);
Than, you must need to check either response having <h3></h3> tags or not.
In your code, the main issue is that, you are using string without quotes in alert alert(thanks); this will return undefined thanks in console and treated as a variable.
This should be alert("thanks");
One more suggestion, it's always better to check browser console when you are not getting success in Ajax or any other script, this will help you to find the errors.
I have a main page in my app called index.php where i want to show some photos. Code in that file is:
<div id="main" name="main">
<input type="button" value="Photos" onclick="showIm()">
</div>
File function.php contains a function to show photos on the screen:
function showPhotos()
{
global $link;
$result = pg_query_params($link, 'SELECT photo_name FROM photos');
while($photos_row = pg_fetch_row($result))
{
echo '<a href="photos/'.$photos_row[0].'">
<img src="photos/'.$photos_row[0].'"></a>';
}
}
My last file is function.js where i try to call showPhotos using ajax
function showIm()
{
$.ajax({
url: "functions.php"
})
}
So inside the last function I want to call showPhotos() to get the results. I think that my implementation is a little complicated but I would like to know if anyone could help.
Well, you have to do something with that result! Add a success method and declare a return dataType
function showIm()
{
$.ajax({
url: "functions.php",
dataType: "html",
success: function(html) {
//do something with the response here
//the "html" variable will contain your PHP response
}
})
}
I have the following code to display links based on the fact that a user is or is not logged:
<?php if(NOT LOGGED){ ?>
<div id="menu"><ul><li><a class="login-button" href="login">LOGIN</a></li></ul></div>
<?php }else{ ?>
<div id="menu"><ul><li><a class="logout-button" href="logout">EXIT</a></li></ul></div>
<?php } ?>
When the "login-button" is is clicked I call a JQuery function that on success will replace it with the following
<div id="menu"><ul><li><a class="logout-button" href="logout">EXIT</a></li></ul></div>
Here is the js
$.ajax({
url: 'login.php',
type: 'POST',
dataType: "json",
success: function (data) {
$('#menu').html('<ul><li><a class="logout-button" href="logout">EXIT</a></li></ul>');
},
error: function (data) {
alert('An Error occurred');
}
});
The problem is that when I click the logout link when it is created by JQuery it doesn´t work.
It only works when the page is refreshed and that is actually replaced by php
Any ideas why?
Not sure it would fix the problem, but your removing the 'ul' in your success function
$('#menu').html('<li><a class="logout-button" href="logout">EXIT</a></li>');
Should be
$('#menu').html('<ul><li><a class="logout-button" href="logout">EXIT</a></li></ul>');
Not sure you are binding the event correctly (as #Lorenzo S says) but this does remind me of an issue I had which was solved by .live:
http://api.jquery.com/live/
Up to quite recently that function was the one you would want but since jQuery 1.7 it has been replaced by .on:
http://api.jquery.com/on/
I am writing a javascript which will post hostname of the site to a php page and get back response from it, but I don't know how to assign the hostname to adrs in url and not sure that code is correct or not.And this needs to done across server
javascript:
function ursl()
{
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
success: function (response)
if (response)=='yes';
{
alert("yes");
}
});
}
track.php
$url=$_GET['adrs'];
$sql="SELECT * FROM website_ad where site='$url'";
$res=mysqli_query($link,$sql);
if(mysqli_num_rows($res)==0)
{
echo"no";
}
else
{
echo"yes";
}
Your ajax function should be written thusly:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=' + window.location.hostname,
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
window.location.hostname will give you the host name. You are passing it to the ajax url by concatenating it. Alternatively, as katana314 points out, you could pass the data in a separate parameter. Your ajax call would then look like this:
$.ajax({
url: 'http://example.com/en/member/track.php?adrs=',
data: {adrs: window.location.hostname},
success: function (response) {
if (response === 'yes') {
$.getScript('http://example.com/en/pop.js', function () {
// do anything that relies on this new script loading
});
}
}
});
I'm not sure what you intend response to be, but this code assumes it is a string and will match true if the string is 'yes'. If response is meant to be something else, you need to set your test accordingly.
$.getScript() will load your external script, but since it's asynchronous you'll have to put any code that is dependent on that in the callback.
In this type of GET request, the variable simply comes after the equals sign in the URL. The most basic way is to write this:
url: 'http://example.com/en/member/track.php?adrs=' + valueToAdd,
Alternatively, JQuery has a more intuitive way of including it.
$.ajax({
url: 'http://example.com/en/member/track.php',
data: { adrs: valueToAdd }
// the rest of the parameters as you had them.
Also note that you can't put a script tag inside a script. You will need some other way to run the Javascript function mentioned; for instance, wrap its contents in a function, load that function first (with a script tag earlier in the HTML), and then call it on success.
And for the final puzzle piece, you can retrieve the current host with window.location.host
You'll need to change this line to look like so:
url: 'http://example.com/en/member/track.php?adrs='+encodeURIComponent(document.URL)
The full success function should look like so:
success: function (response){
if (response==="yes"){
//do your thing here
}
}
That should solve it...
Hey I hope someone can help me out,
I have an external js file that resides in the webroot/js folder that I insert into my view using:
echo $this->Html->script('script');
In the js file I have an ajax request to insert data into my database:
var assetData = {
"project_id": $("#projectId").val(),
"asset_id":"??",
"content": "content":$(this).html()
};
$.ajax({
url:'/assets/add',
type:"POST",
data:assetData
});
In my view I created a hidden form field with the project_id so that I can get it in the js file, however the asset items are created dynamically, the are created and saved into the assets table, and now I want to update that asset with the content.
What would be the best way to get the asset? I can't get the id and save it, for example, in the div's id because it was created in the js file.
I would really appreciate any suggestions!
/assets/add should return the ID of the asset it created.
If you're inserting into a mysql database, then one option is to use mysql_insert_id (there are mysqli and pdo equivilents on the manual).
var assetData = {
"project_id": $("#projectId").val(),
"content": "content":$(this).html()
};
$.ajax({
url:'/assets/add',
type:"POST",
data:assetData,
dataType:'text',
success:function (data)
{
assetData['asset_id'] = (int)data;
}
});
And then your /assets/add should echo out the ID after it is created
echo $asset_id; // some INT id
So you may want to consider HTML partials. These are little bits of HTML representing anything from a single tag, to a popup. The important thing is that it does not have the or tag.
$.post('/assets/add', data, function (html) {
$('#assets').append(html);
}, 'html');
After you POST data, your call returns a snippet of HTML. You can then append that HTML to a DIV on the page.
<div id="assets">
<div class="asset" id="asset-1">
<p>Asset content</p>
</div>
</div>
In your controller (I assume it's CakePHP), you have:
if ($this->Asset->save($this->data)) {
$this->autoLayout = false;
$this->render('asset_partial.html');
}
Using the suggestions I received this is how I managed to solve the problem:
javascript file:
$.ajax({
url:'/assets/create',
type:"POST",
data:assetData,
dataType:'text',
success: function (response) {
if (response.success) {
alert("response: "+response);
} else {
//console.log(response.data, response.code);
alert("response: "+response);
}
}
});
Controller:
public function create($id = null) {
if ($this->data != null) {
$this->Asset->save($this->data);
$this->autoRender = false;
echo $this->Asset->id;
}
}