How do i send parameter in ajax function call in jquery - javascript

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);
});
});

Related

Can't pass the value in php function using ajax

I created the function for my site the users will click the images according to the clicked image I showing the clicked image details so I created the onclick function and I passing that image ID using the ajax function I passing the image ID in PHP file and get that ID into post method and same time passing that variable into PHP class function. My issue is inside the script ID is coming but php file I can't get that variable I don't understand what is the issue. Please help me to find out this issue.
This is the clickable image with onclick function
<div class=\"col-md-3\">
<div class=\"single-new-trend\">
<a href=\"#\" id='BandChangeImg$BraproId' onclick='ImageChange($BraproId);'>
<img src=\"$BraProImg\" alt=\"$BraProName\"></a>
</div>
</div>
This is my ajax script
function ImageChange(x) {
var BrandName = x;
alert(BrandName);
$.ajax({
url: 'validate/brandImage.php',
method: 'POST',
dataType: 'json',
data: {BrandId:BrandName},
success:function(data){
//alert(data);
if($.trim(data))
{
alert("Success!");
}else{
alert("Failed!")
}
}
});
}
Last My PHP file
<?php
include("../db/mySqlDBi.class.php");
$DBConn = new mySqlDB;
$BrandId = $_POST['BrandId'];
include("../classes/personlized.class.php");
$personlized = new personlizedClass;
$result=$personlized->DisplayBrandProductDetails($BrandId);
echo "<script>alert('12334');</script>";
?>
You have
dataType: "json",
in the $.ajax call. jQuery will try to parse the response as JSON, and will get an error if this fails.
The script is sending
echo "<script>alert('12334');</script>";
That's HTML, not JSON, so the above error happens.
Either change it to dataType: "html" or change the PHP to something like
echo json_encode("Brand is $BrandId");

Post on native php (without framework) Into Code Igniter using AJAX

I'm trying to post data on my HTML code to CI with Ajax. But I got no response?
Here is my JS Code
$(document).ready(function(){
$("#simpan").click(function(){
nama_pelanggan = $("#nama_pelanggan").val();
telp = $("#telp").val();
jQuery.ajax({
type: "POST",
url: "http://192.168.100.100/booking_dev/booking/addBookingViaWeb/",
dataType: 'json',
data : {
"nama_pelanggan":nama_pelanggan,
"telp":telp,
},
success: function(res) {
if (res){
alert(msg);
}
}
});
});
});
And here is my form
<form>
Nama Pelanggan <br>
<input type="text" name="nama_pelanggan" id="nama_pelanggan"><br>
Telepon<br>
<input type="text" name="telp" id="telp"><br>
<input type="button" name="simpan" id="submit" value="Simpan">
</form>
and here is my contoller function code
public function addBookingViaWeb(){
$data = array(
'nama_pelanggan' => $this->input->post('nama_pelanggan'),
'telp'=>$this->input->post('telp')
);
echo json_encode($data);
}
Here is my post param
But I got no response
any idea?
add method in from if you use post then
<form method="post" action ="" >
Try using JQuery form serialize() to declare which data you want to post. It automatically put your form input into ajax data. Example :
first set ID to your form tag
<form id="form">
then
$.ajax({
type:'POST',
url : 'http://192.168.100.100/booking_dev/booking/addBookingViaWeb/',
data:$('#form').serialize(),
dataType:'JSON',
success:function(data){
console.log(data);
}
});
First problem I see is in your ajax submission code. Change
$("#simpan").click(function(){
to
$("#submit").click(function(event){
Notice that I added the event parameter. You now need to prevent the default submission behavior. On the first line of your click method add
event.preventDefault();
Now I'm assuming that your url endpoint http://192.168.100.100/booking_dev/booking/addBookingViaWeb/ can handle POST requests. Usually this is done with something like PHP or Ruby on Rails. If I was doing this in PHP I would write something like the following:
<?php
$arg1 = $_POST["nama_pelanggan"];
$arg2 = $_POST["telp"];
// do something with the arguments
$response = array("a" => $a, "b" => $b);
echo json_encode($response);
?>
I personally don't know anything about handling POST requests with js (as a backend) but what I've given you should get the data over there correctly.
I got solution for my problem from my friend xD
just add header("Access-Control-Allow-Origin: *"); on controller function
Thank you for helping answer my problem.

How do i submit a hidden form using ajax when the page loads?

How can i submit a hidden form to php using ajax when the page loads?
I have a form with one hidden value which i want to submit without refreshing the page or any response message from the server. How can implement this in ajax? This is my form. I also have another form in the same page.
<form id = "ID_form" action = "validate.php" method = "post">
<input type = "hidden" name = "task_id" id = "task_id" value = <?php echo $_GET['task_id'];?>>
</form>
similar to Zafar's answer using jQuery
actually one of the examples on the jquery site https://api.jquery.com/jquery.post/
$(document).ready(function() {
$.post("validate.php", $("#ID_form").serialize());
});
you can .done(), .fail(), and .always() if you want to do anything with the response which you said you did not want.
in pure javascript
body.onload = function() {
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("POST","validate.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("task_id=" + document.getElementById("task_id").value);
};
I think you have doubts invoking ajax submit at page load. Try doing this -
<script type="text/javascript">
$(document).ready(function(){
$.ajax({
"url": "validate.php",
"type": "post"
"data": {"task_id": $("#task_id").val();},
"success": function(){
// do some action here
}
})
})
</script>
If you're using jQuery you should be able to get the form and then call submit() on it.
E.g.:
var $idForm = $('#ID_form');
$idForm.submit();
Simple solution - jQuery AJAX post the value as others have suggested, but embed the PHP value directly. If you have multiple forms, you can add more key:value pairs as needed. Add a success/error handler if needed.
<script type="text/javascript">
$(document).ready(function(){
$.post( "validate.php", { task_id: "<?=$_GET['task_id']?>" } );
})
</script>
As others have said, no need for a form if you want to send the data in the background.
validate.php
<?php
$task_id = $_POST['task_id'];
//perform tasks//
$send = ['received:' => $task_id]; //json format//
echo json_encode($send);
JQuery/AJAX:
$(function() { //execute code when DOM is ready (page load)//
var $task = $("#task_id").val(); //store hidden value//
$.ajax({
url: "validate.php", //location to send data//
type: "post",
data: {task_id: $task},
dataType: "json", //specify json format//
success: function(data){
console.log(data.received); //use data received from PHP//
}
});
});
HTML:
<input type="hidden" name="task_id" id="task_id" value=<?= $_GET['task_id'] ?>>

Echo PHP message after AJAX success

I have a modal that will display when the user clicks a delete button. Once they hit the delete button I am using AJAX to subimit the form. Eveything works fine, but it is not display my success message which is set in PHP.
Here is my AJAX code:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function () {
// This is empty because i don't know what to put here.
}
});
}
Here is the PHP code:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
} else {
$errors[] = lang("SQL_ERROR");
}
And then I call it like this:
<div class="col-lg-12" id="resultBlock">
<?php echo resultBlock($errors,$successes); ?>
</div>
When I use AJAX it does not display the message. This works fine on other pages that does not require AJAX to submit the form.
I think you are getting confused with how AJAX works, the PHP script you call will not directly output to the page, consider the below simplified lifecycle of an AJAX request:
Main Page -> Submit Form -> Put form data into array
|
--> Send array to a script to be processed on the server
|
|----> Callback from the server script to modify DOM (or whatever you want to do)
There are many callbacks, but here lets discuss success and error
If your PHP script was not found on the server or there was any other internal error, an error callback is returned, else a success callback is fired, in jQuery you can specify a data array to be received in your callback - this contains any data echoed from your PHP script.
In your case, you should amend your PHP file to echo your arrays, this means that if a successful request is made, the $successes or $errors array is echoed back to the data parameter of your AJAX call
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo $successes;
} else {
$errors[] = lang("SQL_ERROR");
echo $errors;
}
You can then test you received an object by logging it to the console:
success: function(data) {
console.log(data);
}
Well, it's quite not clear what does work and what does not work, but two things are bothering me : the function for success in Ajax is empty and you have a header function making a refresh in case of success. Have you tried removing the header function ?
success: function(data) {
alert(data);
}
In case of success this would alert the data that is echoed on the php page. That's how it works.
I'm using this a lot when I'm using $.post
Your header will not do anything. You'll have to show the data on the Java script side, maybe with alert, and then afterwards redirect the user to where you want in javascript.
you need put some var in success function
success: function(data) {
alert(data);
}
then, when you read var "data" u can do anything with the text
Here is what I changed the PHP to:
if ($deletion_count = deleteUsers($deletions)) {
$successes[] = lang("ACCOUNT_DELETIONS_SUCCESSFUL", array($deletion_count));
echo resultBlock($errors,$successes);
} else {
$errors[] = lang("SQL_ERROR");
echo resultBlock($errors,$successes);
}
And the I changed the AJAX to this:
function deleteUser(){
var id = <?php echo $userdetails['id'] ?>;
$.ajax({
type: "POST",
url: 'admin_user.php?id=' + id,
data: $('form.adminUser').serialize(),
error: function(e){
alert(e);
},
success: function (data) {
result = $(data).find("#success");
$('#resultBlock').html(result);
}
});
}
Because data was loading all html I had to find exactly what I was looking for out of the HTMl so that is why I did .find.

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

Categories