AJAX Request on jQuery Mobile Collapse - javascript

I currently have a dynamic number of these being generated with a foreach() loop:
<div id="<?php echo $data['id']; ?>" data-role="collapsible" data-theme="a">
<h1 style="white-space: normal"><?php echo $data['text']; ?></h1>
<center>
<p><?php echo $data['text']; ?></p>
</center>
</div>
What I want, is for an AJAX POST request to be dispatched to another resource with the parameters of $data['id'] when the collapsible <div> opens.
I tried using a .click method, but I was not able to make it work for a dynamic list of <div>s. I feel a method that waited until the animation was done (as to ensure the page is still responsive) is the best way.
Can someone please help with this?

For dynamically generated content, I would suggest you use the .on() method. Take for example the following code:
$('#container').on('click', 'div', function() {
var id = $(this).attr('id');
$(this).animate({
your animation
}, 5000, function() {
$.ajax({
url: "another_resource.php",
type: "POST",
data: {
id: id
}, //data to be sent
dataType: "text", //return data type
async: false,
success: function(data) {
console.log(data);
},
error: function(data) {
console.log(data);
}
});
});
}
The first parameter is the event(s)(can be space delimited for multiple events), while the second can either be the targeted element, or the function to execute. The last, in this case, is of course the function to execute.
The ajax will execute when the animation is complete, as requested.

Related

why I can't get the value when make a jquery/ajax call on link click?

In my website I have a link where user id is store like this :
<p>by <?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</p>
Here you can see variable $uid. This is the user id. So I want to make ajax call when I click on this link. It's should get the value of $uid to result page ofUser.php. But in result page (ofUser.php) it's showing :
Undefined index: id
Can you tell me how can I solve it ?
Here is the JS offUser function
function ofUser(id, event){
id = $(id);
event.preventDefault();
var formData = id;
$.ajax({
url : <?php echo "'ofUser.php'"; ?>,
type : 'POST',
xhr : function () {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend : function () {
$("#ofUser_message").val("Searching...");
},
success : function (data) {
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
},
data: formData,
cache: false,
contentType: false,
processData: false
});
}
offUser.php
echo $uid = (int) $_POST['id'];
id = $(id); will cast id to jQuery object which is not making any sense here. It will make id as array(id=$(1) => [1])
Also note, your data being sent over server should be an object.
Try this:
function ofUser(id, event) {
event.preventDefault();
$.ajax({
url: 'ofUser.php',
type: 'POST',
xhr: function() {
var myXhr = $.ajaxSettings.xhr();
return myXhr;
},
beforeSend: function() {
$("#ofUser_message").val("Searching...");
},
success: function(data) {
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
},
data: {
id: id
},
cache: false
});
}
Edit: Remove processData : true as it will send data as DOMDocument
Just try to pass id = id; instead id = $(id); because $(id) means you are trying to get any DOM element values using jQuery, I hope it will work, also tell me that, what HTML is generated for your this code
<p>by <?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</p>
To solve this problem, SIMPLIFY to make sure you are correctly passing the ID value. In your AJAX success function, ALERT the value you send back so you can immediately see what you received in PHP.
Try setting it up this way instead:
html:
<p>by <a id="uid_<?php echo $uid; ?>" href="#" ><?php echo $store_name; ?> (<?php echo $no_pro_of_user; ?>)</a></p>
javascript:
$('[id^=uid_]').click(function(event){
event.preventDefault();
var formData = this.id.split('_')[1];
$("#ofUser_message").val("Searching...");
$.ajax({
type : 'POST',
url : 'ofUser.php',
data : id=formData,
success : function (data) {
alert(data);
$("#danger").hide();
$("#bydault_pagination").hide();
$("#bydeafult_search").hide();
$("#ofUser_message").html(data);
}
});
});
ofUser.php
$uid = $_POST['id']; //REMOVE the (int) for now, to verify what PHP is receiving - then add it back.
echo 'Received $uid';
Notes:
(1) Note that you misspelled ofUser.php and offUser.php (not sure which is correct - I went with ofUser.php)
(2) Try not to use inline javascript. jQuery is easiest to use when you break out the javascript from the HTML, as per above example.
(3) In above example, the jQuery selector starts with is used:
$('[id^=uid_]').click(function(event){
That code is fired by any element whose ID begins with uid_, as we configured the <a> tag's ID to appear. That makes it easy to see in your HTML.
(4) This line:
var formData = this.id.split('_')[1];
uses pure javascript to get the ID, because it's faster - and simpler to type. The code splits off the 2nd part of the ID, at the _ char, resulting in just the ID number. That ID number is then assigned to the variable formData
(5) In the AJAX code block, make sure the url is spelled correctly:
url : 'ofUser.php',
Here are some other SIMPLE AJAX examples that might help. Don't just look at them - reproduce them on your server and play with them. They are simple, but you may learn a lot:
AJAX request callback using jQuery
When click over any hyperlink then start redirecting to provided URL. so you need to prevent its default action using below code inside your click event handler
event.preventDefault();

Set session when clicking html link?

I have searched and tested different solutions all day without luck. In the below code I want (when clicked) to set a session on the "open" links I echo in the foreach loop. I tried using AJAX but I am new to AJAX and could not make it work. I know how to do it using GET but it is too risky, so i welcome your suggestion and preferably examples.
$task_array = array_combine($task_id_unique, $task_status);
foreach ($task_array as $card_nr => $card_status) {
?>
<table>
<tr>
<th>card nr.</th>
<th>Status</th>
</tr>
<td><?php
echo $card_nr;?></td>
<td>
<?php
if ($card_status == true) {
echo "<a href=workcard.php>Open</a>";
}
else echo "Done ". $card_nr;?></td>
</table>
What have you tried and what doesn't work, because this looks like what you need...
HTML:
Register Now!
PHP:
if(isset($_GET['a'])){
$_SESSION['link']= 'whatever';
}
And if you need to do it without a page refresh, then use AJAX.
You should use ajax on click of link:
$.ajax({
url: 'test.php',
dataType: 'json',
type: 'post',
data: {name: "value", name2: "value2" /* ... */},
success: function (data) {
}
});
in your test.php, $_POST['name'] is equal to "value". and there you can do everything you want.
first, add html class on "Open" link and custom html5 attribute to store your card data. for example data-card.
Open
next, create Onclick event for a link to send an ajax request.
$( document ).ready(function() {
$(".your-class").click(function() {
var card_nr = $(this).attr('data-card');
$.ajax({
url: "workcard.php",
type: "POST",
data: "card=" + card_nr
}).done(function() {
// do something
});
return false;
});
});

How do i send parameter in ajax function call in jquery

I'm creating an online exam application in PHP and am having trouble with the AJAX calls.
I want the questions to be fetched (and used to populate a div) using an AJAX call when one of the buttons on the right are clicked. These buttons are not static; they are generated on the server (using PHP).
I'm looking for an AJAX call to be something like this:
functionname=myfunction(some_id){
ajax code
success:
html to question output div
}
and the button should call a function like this:
<button class="abc" onclick="myfunction(<?php echo $question->q_id ?>)">
Please suggest an AJAX call that would make this work
HTML
<button class="abc" questionId="<?php echo $question->q_id ?>">
Script
$('.abc').click(function () {
var qID = $(this).attr('questionId');
$.ajax({
type: "POST",
url: "questions.php", //Your required php page
data: "id=" + qID, //pass your required data here
success: function (response) { //You obtain the response that you echo from your controller
$('#Listbox').html(response); //The response is being printed inside the Listbox div that should have in your html page. Here you will have the content of $questions variable available
},
error: function () {
alert("Failed to get the members");
}
});
})
The type variable tells the browser the type of call you want to make to your PHP document. You can choose GET or POST here just as if you were working with a form.
data is the information that will get passed onto your form.
success is what jQuery will do if the call to the PHP file is successful.
More on ajax here
PHP
$id = gethostbyname($_POST['id']);
//$questions= query to get the data from the database based on id
return $questions;
You are doing it the wrong way. jQuery has in-built operators for stuff like this.
Firstly, when you generate the buttons, I'd suggest you create them like this:
<button id="abc" data-question-id="<?php echo $question->q_id; ?>">
Now create a listener/bind on the button:
jQuery(document).on('click', 'button#abc', function(e){
e.preventDefault();
var q_id = jQuery(this).data('question-id'); // the id
// run the ajax here.
});
I would suggest you have something like this to generate the buttons:
<button class="question" data-qid="<?php echo $question->q_id ?>">
And your event listener would be something like the following:
$( "button.question" ).click(function(e) {
var button = $(e.target);
var questionID = button.data('qid');
var url = "http://somewhere.com";
$.ajax({ method: "GET", url: url, success: function(data) {
$("div#question-container").html(data);
});
});

sending span text to another page with JS and php

I have a dynamically changing span on a page displaying the number of votes a project has received. On another (target) page i have a list of projects. i want to be able to display that vote count there. i know how to grab the text from the span on the page.
it would be something like this.
<span id="count1"></span>
var prj1c = $("#count1").text;
in know that on the other page i end up using
<?php echo $prj1c(this being after i assign the prj1c var to php somewhere) ?>
i also know i could create a php include page and call it on the target page, though i would like not to create a separate page for each of these instances.
so to sum up: how do i change a JS var to php and call it from another page- remember the text in the span changes (when users vote up or down)?
Try this, use .text() instead of .text
var prj1c = $("#count1").text(); //instead of var prj1c = $("#count1").text;
$.ajax({
type: "POST",
url: "yourpage.php",
data: {count :prj1c},
success: function(response) {
alert("Response "+response);
}
});
in yourpage.php add this <?php echo $_POST['count']; ?>
Update:
$(function(){
$("#count1").click(function(){
window.location='page2.php?count='+$(this).text();
});
});
in page2.php:
<ul>
<li id="projectName">
<img><span>vote count goes HERE: <?php echo $_GET['count']; ?></span>
</li></ul>
You can try with jQuery Ajax request. When user vote up/down you can make an ajax call to the target page.
Eg.
var prj1c = $("#count1").text();
$.ajax({
type: "POST",
url: "targetPage.php",
data: "count="+prj1c,
success: function(response) {
alert("Response "+response);
}
});
Get the prj1c value in targetPage.php
$prj1c = $_REQUEST['count'];
// Follow appropriate steps later in targetPage.php

jquery .ajax always returns error - data being added to database

I am trying to add users to a database using jquery ajax calls. The users get added just fine to the database, but the ajax always returns with error. I'm not sure how to retrieve the specific error either. Below is my code, form, php, and jquery.
Here is the jquery
$(document).ready(function() {
//ajax call for all forms.
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
Here is the PHP
<?php
include 'class_lib.php';
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
echo json_encode('true');
} else {
echo json_encode('false');
}
}
Here is the HTML
<div id='newUser' class='tool'>
<h3>New User</h3>
<form method='post' name='newUser' data='../php/newUser.php'>
<span>Username</span><input type='text' name='username'><br>
<span>Password</span><input type='password' name='password'>
<input type='submit' name='submit' class='button' style='visibility: hidden'>
</form>
<span class='result'> </span>
</div>
#Musa, above you mentioned
My guess is its a parsing error, try removing dataType: 'json', and see if it works
You absolutely solved the problem I was having! My ajax post request was similar to above and it just kept returning to the 'error' section. Although I checked using firebug, the status was 200(ok) and there were no errors.
removing 'dataType:json' solved this issue for me. Thanks a lot!
Turns out I had to add async: false to the $.ajax function. It wasn't getting a response back from the php.
I know this is an old question but I have just run into a weird situation like this ( jquery ajax returns success when directly executed, but returns error when attached to button, even though server response is 200 OK )
And found that having the button inside the form tags caused JQuery to always return error. Simply changing the form tags to div solved the problem.
I believe JQuery assumes the communication should be form encoded, even though you say it is application/json.
Try moving your button outside your form and see what happens...
I had the same problem and discovery there. All the time the problem is the version of my jQuery, I had use jquery version (jquery-1.10.2.js) but this version is not Ajax stablish. So, I change version for (jquery-1.8.2.js) and this miracle heppened.
Good Luck Guy!
You should specify status Code 200 for successful response.
<?php
http_response_code(200);
?>
See here: http://php.net/manual/en/function.http-response-code.php
The first solution
Try to remove dataType in your js file like that:
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
data: form.serialize(),
success: function (response) {
alert('something');
},
error: function() {
alert('fail');
}
});
});
});
The second solution
Send a real clean JSON to AJAX like that:
PHP
if(isset($_POST['username'])) {
$user = new Users;
$user->cleanInput($_POST['username'], $_POST['password']);
if($user->insertUser()) {
$error = [
"title"=> 'true',
"body"=> 'some info here ... '
];
echo json_encode($error);
} else {
$error = [
"title"=> 'false',
"body"=> 'some info here ... '
];
echo json_encode($error);
}
}
JavaScript
$(document).ready(function() {
$('.button').click(function() {
var form = $(this).closest('form');
$.ajax({
type: "POST",
url: form.attr('data'),
dataType: 'json',
data: form.serialize(),
success: function (data) {
let x = JSON.parse(JSON.stringify(data));
console.log(x.title);
console.log(x.body);
},
error: function() {
//code here
}
});
});
});

Categories