I have index.php:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.on').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
});
});
$('.off').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
});
});
});
</script>
<body>
<img class="bulb" src="bulb.png" alt="...">
<button class="on" value="http://pageon.org">On</button>
<button class="off" value="http://pageoff.org">Off</button>
</body>
I send value of buttons to try.php. Depending on the clicked button, I get one variable in the try.php file, for the ON button - 1 , for the OFF button - 0 (variable $curl_response).
Is it possible to change the img in the index.php file dynamically, depending on the received variable from the try.php page? For example, if the received variable is 1, src = "bulb.png", and if 0, then src = "bulb2.png"?
try.php :
<?php
$name = $_POST['myVar'];
$service_url = $name;
$curl = curl_init($service_url);
// Ustaw opcje połączenia
curl_setopt($curl, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 );
//curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$curl_response = curl_exec($curl);
curl_close($curl);
?>
EDIT:
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val}
success: function(result){
switch(result){
case "0":
$(".bulb").attr("src", "bulb.png");
break;
case "1":
$(".bulb").attr("src", "bulb2.png");
break;
}
}
});
});
});
</script>
Yes, you could use this, on the AJAX success:
$.ajax({
...
success: function(result){
switch(result){
case "1":
$("#yourImage").attr("src", "yourImagePath1.jpg");
break;
case "2":
$("#yourImage").attr("src", "yourSecondImagePath.jpg");
break;
}
}
});
EDIT/SUGGESTION
You don't need to trigger 2 separate events for each button if they are going to call the same URL and pass the same structure data. Use the same class to trigger:
HTML
<button class="buttonClass" value="http://pageon.org">On</button>
<button class="buttonClass" value="http://pageoff.org">Off</button>
JS
$(".buttonClass").click(function(){
var val = $(this).text();
//make here your ajax call passing 'val'
});
Have a look at the success option that you pass to $.ajax. That's where you provide the callback function that you want to run if the https request status is 200. Something like
$.ajax({
/** your other stuff, and... */
success : function(data) {
if (data == 1) {
$('button.on').attr({src : "bulb.png"})
}
// and so on
}
});
See http://api.jquery.com/jQuery.ajax/ for further information.
Yes simply you can add if-else condition based on your flag received in your ajax success method and update img src attribute using JavaScript
You can send an AJAX request when one of the buttons is clicked and handle the response, like this:
<script type="text/javascript">
$(document).ready(function () {
$('.on, .off').click(function() {
var val = $(this).val();
$.ajax({
url: "try.php",
type: "POST",
data: {'myVar': val},
success: function(result){
switch(result){
case "0":
$(".bulb").attr("src", "bulb.png");
break;
case "1":
$(".bulb").attr("src", "bulb2.png");
break;
}
}
});
});
});
</script>
Related
I am trying to send values to other page Using Ajax
But i am unable to receive those values , i don't know where i am wrong
here is my code
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var dataString1 = "fval="+fval;
alert(fval);
var sval = document.getElementById('country').value;
var dataString2 = "sval="+sval;
alert(sval);
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: "{'data1':'" + dataString1+ "', 'data2':'" + dataString2+ "'}",
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
in alert i am getting those value but in page 'getmoreinfo.php' i am not receiving any values
here is my 'getmoreinfo.php' page code
if ($_POST) {
$country = $_POST['fval'];
$country1 = $_POST['sval'];
echo $country1;
echo "<br>";
echo $country;
}
Please let me know where i am wrong .! sorry for bad English
You are passing the parameters with different names than you are attempting to read them with.
Your data: parameter could be done much more simply as below
<script type="text/javascript">
function get_more_info() { // Call to ajax function
var fval = document.getElementById('get_usecompny').value;
var sval = document.getElementById('country').value;
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: {fval: fval, sval: sval},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
Or cut out the intermediary variables as well and use the jquery method of getting data from an element with an id like this.
<script type="text/javascript">
function get_more_info() { // Call to ajax function
$.ajax({
type: "POST",
url: "getmoreinfo.php", // Name of the php files
data: { fval: $("#get_usecompny").val(),
sval: $("#country").val()
},
success: function(html)
{
$("#get_more_info_dt").html(html);
}
});
}
</script>
No need to create 'dataString' variables. You can present data as an object:
$.ajax({
...
data: {
'fval': fval,
'sval': sval
},
...
});
In your PHP, you can then access the data like this:
$country = $_POST['fval'];
$country1 = $_POST['sval'];
The property "data" from JQuery ajax object need to be a simple object data. JQuery will automatically parse object as parameters on request:
$.ajax({
type: "POST",
url: "getmoreinfo.php",
data: {
fval: document.getElementById('get_usecompny').value,
sval: document.getElementById('country').value
},
success: function(html) {
$("#get_more_info_dt").html(html);
}
});
I want to switch from a displayed image to another after an AJAX request completes.
Here is the code for the AJAX call:
<script type="text/javascript">
$(document).ready(function(){
$('.item').click(function(){
var $id = $(this).attr('data-id');
$.ajax({
type: "POST",
url: "test.php",
data: { id: $id },
success: //
})
});
});
</script>
Here is the HTML :
<div class="item" data-id="1"><img src="image1.png" /></div>
If image1.png is displayed, I want to display image2.png instead.
If image2.png is displayed, I want to display image1.png instead.
Please, help me to fill the success part in the AJAX process.
You can use the .find() method to find the image child, and then .attr() to get and set the attribute for the src property.
So before the AJAX call, find the image:
var image = $(this).find('img');
Then in the success function, check the src attribute and set it using attr():
success: function(data) {
if (image.attr('src') == 'image1.png') {
image.attr('src', 'image2.png');
} else {
image.attr('src', 'image1.png');
}
}
See it demonstrated in the example below:
var urls = [
"https://i.stack.imgur.com/C92ci.png?s=32&g=1", //image1.png
"https://www.gravatar.com/avatar/8911010cdec4bb9d56b83b6bbbb1f341?s=32&d=identicon&r=PG"
];
$(document).ready(function() {
//demonstration container- for AJAX request response
var questionsContainer = $('#questions');
$('.item').click(function() {
var $id = $(this).attr('data-id');
var image = $(this).find('img');
$.ajax({
url: "https://api.stackexchange.com/2.2/questions?order=desc&sort=activity&site=stackoverflow",
success: function(data) {
var index = urls.indexOf(image.attr('src'));
image.attr('src', urls[Math.abs(index-1)]);
/*if (image.attr('src') == urls[0]) {
image.attr('src', urls[1]);
} else {
image.attr('src', urls[0]);
}*/
questionsContainer.html('# of Questions: ' + data.items.length);
}
});
questionsContainer.html('...');
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item" data-id="1"><img src="https://www.gravatar.com/avatar/8911010cdec4bb9d56b83b6bbbb1f341?s=32&d=identicon&r=PG" /></div>
<div id="questions">Click the image to load # of questions</div>
Hope this helps.If needed we can use toggle jquery function to toggle between these two images.
<script type="text/javascript">
$(document).ready(function(){
$('.item').click(function(){
var $id = $(this).attr('data-id');
var $imgId = $('.item img').attr('src');
$.ajax({
type: "POST",
url: "test.php",
data: { id: $id , ImageId :$imgId },
success: function(data){
if(ImageId == 'image1.png'){
$(this).attr('src', 'image2.png');
}
else{
$(this).attr('src', 'image1.png');
}
}
})
});
});
</script>
I want to increment count field in database when a link is clicked in php file.
So, I've added the following jquery part to my .php file. But still, it doesn't work. Please help!
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
code.php:
<?php
$conn=mysqli_connect("localhost","root","","sample");
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($connection);
?>
You made a several mistakes in your code.
Update
You can send your SID input type text from ajax with data and you can get the value in your php file with the $sid = $_POST['sid'].
<body>
click here
<input type="text" value="" name="sid" id="sid">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(e){
$('#click').click(function(event)
{
var sidvalue = $("#sid").val(); /*from here you get value of your sid input box*/
event.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php",
data: 'sid='+sidvalue ,
success: function() {
window.location.href = 'https://www.google.com/';
}
});
});
});
</script>
After the ajax success response you can make redirect to your desire location.
Code.php
<?php
$conn=mysqli_connect("localhost","root","","sample");
$sid = $_POST['sid']; // use this variable at anywhere you want.
mysqli_query($conn,"UPDATE e set count=(count+1) WHERE sid='1'");
mysqli_close($conn);
?>
in code.php in mysqli_close you should use $conn not $connection.
Go with this code. It might help you. I have just tested all the things in localhost. This is working perfect.
use preventDefault() when click event is called.check jquery :
<body>
click here
<script>
$(function ()
{
$('#click').click(function(e)
{
e.preventDefault();
var request = $.ajax(
{
type: "POST",
url: "code.php"
});
});
}
</script>
</body>
Redirect your link on ajax success. Like this -
<body>
click here
<script>
$(function ()
{
$('#click').click(function()
{
var request = $.ajax(
{
type: "POST",
url: "code.php",
success: function(response){
window.location="http://www.google.com";
}
});
});
}
</script>
I have some page with form, which loading some data to POST when i submit it. Then it links user to the next page. On this page I catch data from POST, and I have two dropdownlists, where the second one depends on the first. The first get's value from POST data:
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'"); </script>';
Where $GLOBALS["i"] = id from DB, which has kept in data from POST by previous page.
But it doesn't work for the second dropdownlist which depends on it:
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
I think it can be from the part of code, which realises depending of the second dropdown list:
<script>
jQuery(function(){
var id = jQuery(".mark").val();
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
jQuery(".mark").change(function(){
var id = jQuery(".mark").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function(data){
jQuery(".comm").html(data);
}
});
});
Where "mark" - first dropdownlist, "comm" - the second one.
This is the first part of my problem.
The second: I have some value on the page which depends on the value of the second dropdownlist. I tried to:
jQuery(".comm").change(function(){
var id = jQuery(".comm").val();
if(id==0){
}
jQuery.ajax({
type:"POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function(data){
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type:"POST",
url: "../wp-content/price.php",
data: {price1: price1,price2: price2,price3: price3,price4: price4,price5: price5,price6: price6,price7: price7,price8: price8, price9: data},
success: function(data){
jQuery(".summPrice").html(data);
}
});
}
});
But it works only one time, and i don't know why.
I'll be glad for any offers.
I don't have a full visibility of the rendered html and of the ajax responses, but I would give a try with:
Remove this lines
echo '<script type="text/javascript">
jQuery("#markid").val("'.$GLOBALS["i"].'");
</script>';
echo '<script type="text/javascript">
jQuery("#comm").val("'.$GLOBALS["i1"].'"); </script>';
And do something like this where you print the html
...
<select id="markid" data-val="<?php echo isset($GLOBALS["i"]) ? $GLOBALS["i"] : -1;?>"></select>
<select id="comm" data-val="<?php echo isset($GLOBALS["i1"]) ? $GLOBALS["i1"] : -1;?>"></select>
And in your javascript have something like
<script>
(function ($) {
//when everything is ready
$(fillUpCommOptions);
$(watchSelectsChanges);
function fillUpCommOptions() {
var id = $('#markid').data('val') ? $('#markid').data('val') : $('#markid').val();
$('#markid').removeAttr('data-val');//remove data-val, at next change event we want the select new val
$.ajax({
type: "POST",
url: "wp-content/com.php",
data: {id_mark: id},
success: function (data) {
//assuming data is something like
// '<option value="niceValue">nice value</option>
$("#comm").html(data);
if ($("#comm").data('val')) {
//apply values from post also for the second dropdown
// assuming that data contains and option with value == $("#comm").data('val')
$("#comm").val($("#comm").data('val'));
$('#comm').removeAttr('data-val');
$("#comm").change()//trigger change after setting the value
}
}
});
}
function watchSelectsChanges() {
$('#markid')
.off('change')//just in case, could not be needed
.on('change', fillUpCommOptions);
$('#comm')
.off('change')//just in case, could not be needed
.on('change', handleDependentValues);
}
function handleDependentValues() {
var id = $("#comm").val();
if (id) {
$.ajax({
type: "POST",
url: "wp-content/pricecar.php",
data: {id_mark: id},
success: function (data) {
jQuery(".price9").html(data);
var price1 = jQuery(".price1").val();
var price2 = jQuery(".price2").val();
var price3 = jQuery(".price3").val();
var price4 = jQuery(".price4").val();
var price5 = jQuery(".price5").val();
var price6 = jQuery(".price6").val();
var price7 = jQuery(".price7").val();
var price8 = jQuery(".price8").val();
var price9 = jQuery(".price9").val();
jQuery.ajax({
type: "POST",
url: "../wp-content/price.php",
data: {
price1: price1,
price2: price2,
price3: price3,
price4: price4,
price5: price5,
price6: price6,
price7: price7,
price8: price8,
price9: data
},
success: function (data) {
jQuery(".summPrice").html(data);
}
});
}
})
}
}
})(jQuery);
hey guys i'm trying to make changes in my blade template using ajax , when i press the button it changes the value of data in database and i want to display this data at once on my blade template .
that's my java script code :
(function($){
$('.wishlistForm').on('submit', function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
method: 'post',
dataType: 'json',
success: function(response){
var wishlistButton = form.find("button[type='submit']");
var x = parseInt($('.wish-btn-count').text());
if(response.actiondone == 'added') {
$('.wish-btn-count').text(x++);
console.log(x);
wishlistButton.text(response.message);
} else if(response.actiondone == 'removed') {
$('.wish-btn-count').text(x--);
console.log(x);
wishlistButton.text(response.message);
}
}
});
return false;
});
})(jQuery);
and here is the part i want to change in my template :
<div class="wish-btn-count" id="wishlist">
{{$wishlistcount}}
</div>
so how can i do it ? and for record it returns the value right in the console but don't show it in my view
Prevent the default submit event, so you can trigger the ajax
$('.wishlistForm').on('submit', function(e){
e.preventDefault();
This may be the solution.
If you are receiving json object response from the ajax call,first you have to parse that object and then use it.
Try this,
(function($){
$('.wishlistForm').on('submit', function(){
var form = $(this);
$.ajax({
url: form.attr('action'),
data: form.serialize(),
method: 'post',
dataType: 'json',
success: function(response){
/*Add this in your code*/
var response = JSON.parse(response.trim());
var wishlistButton = form.find("button[type='submit']");
var x = parseInt($('.wish-btn-count').text());
if(response.actiondone == 'added') {
$('.wish-btn-count').text(x++);
console.log(x);
wishlistButton.text(response.message);
} else if(response.actiondone == 'removed') {
$('.wish-btn-count').text(x--);
console.log(x);
wishlistButton.text(response.message);
}
}
});
return false;
});
})(jQuery);