I want to append php code and I want to use script varible in my php code.
How can i do this?
function sendajax(id,status,count){
$.ajax({
url : '{{url("admin/loadmoredata")}}',
method : "POST",
data : {id:id,status:status,count:count, _token:"{{csrf_token()}}"},
dataType : "json",
success : function (data)
{
if(status = 1)
{
if(data[0] == 400){
$('.acceptorder-btn').html('no data');
}else{
console.log(data[2])
var row = data[1];
$.each(data[2], function( index, value ) {
row++
$('.load').append(`<tr> <td> `+row+` </td> <td> <?php $vlue = `+value["id"]+` ; dd($vlue); ?></td> <td>`+value["receiver_name"]+`</td></tr>` );
$('#btn-more').removeAttr('data-id');
$('.loadmore-btn').attr('data-id',value['id']);
});
}
// $('.load').append(data);
}
else
{
$("#btn-more").html("No Data");
}
}
});
}
});
I can show script variable like this echo '+value["id"]+'
but I can't use this for variable in php and when I dd() variable it returns null.
Related
I have a global ajaxSuccess event and a local success function attached to an ajax request.
I want to cancel the success function if the global find status = false in the response.
like this
$(document).ajaxSuccess(function (event, xhr) {
let result = xhr.responseJSON;
if (result.status === false) {
//here the ajax should be stopped, I don't want to call the local functio
}
}
$.ajax(url, {
'method': method,
'success': function () {
//success function to call if the global ajaxSuccess is ok
}
})
can this be achieved ?
This will give you an insight into what you may be looking for. You will need to return the backend data in json.
why don't you set status to certain values
Eg. false= 0 and true = 1. You can then print success or failure based on values returned from the backend in this sample from PHP backend.
Here am sending a post variable with value of test_ok. If the value is test_ok then alert success else alert fail and
stop further action
<script>
$(document).ready(function(){
var test ='test_ok';
var datasend = "test="+ test;
$.ajax({
type:'POST',
url:'test.php',
data:datasend,
crossDomain: true,
cache:false,
success:function(result){
$('#result').fadeIn('slow').prepend(msg);
if (result.status ==0) {
alert('failed');
return false;
}
if (result.status == 1) {
alert('success');
}
}
});
});
</script>
test.php
<?php
$test = $_POST['test'];
$output = array();
if($test == "test_ok"){
$output[] = array(
"status" => '1'
);
}
if($test != "test_ok"){
$output[] = array(
"status" => '0'
);
}
echo json_encode($output);
I have some code which is working just fine counting the number of clicks of a single button. However I don't know how to let it count multiple buttons for me.
How should I extend my code to count clicks from other buttons?
PHP script:
<?php
$counterFile = 'counter.txt' ;
if (isset($_GET['increase'])) {
if (($counter = #file_get_contents($counterFile) ) === false ) {
die('Error : file counter does not exist');
}
file_put_contents($counterFile,++$counter) ;
echo $counter ;
return false ;
}
if (!$counter = #file_get_contents($counterFile)) {
if (!$myfile = fopen($counterFile,'w')) {
die('Unable to create counter file !!') ;
}
chmod($counterFile,0644);
file_put_contents($counterFile,0) ;
}
?>
Javascript:
$('#download1').on('click',function(){
jQuery('div#counter').html('Loading...') ;
var ajax = jQuery.ajax({
method : 'get',
url : '/test.php', // Link to this page
data : { 'increase' : '1' }
}) ;
ajax.done(function(data){
jQuery('div#counter').html(data) ;
}) ;
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable') ;
}) ;
});
To clear things up I've split my answer into three parts (PHP, JS and HTML) so you can see how it works.
PHP
$counterFile = 'counter.txt';
if (isset($_GET['increase'])) {
if (($counters = unserialize(#file_get_contents($counterFile))) === false) {
die('Error : file counter does not exist');
}
switch ($_GET['counter']) {
case 'counter_one':
$counters['counter_one'] += $_GET['increase'];
break;
case 'counter_two':
$counters['counter_two'] += $_GET['increase'];
break;
}
file_put_contents($counterFile, serialize($counters)) ;
foreach ($counters as $name => $count) {
echo $name.": ".$count."<br />";
}
exit;
}
if (!$counters = unserialize()#file_get_contents($counterFile)) {
if (!$myfile = fopen($counterFile,'w')) {
die('Unable to create counters file');
}
chmod($counterFile,0644);
file_put_contents($counterFile, serialize(array('counter_one' => 0, 'counter_two' => 0)));
}
Javascript
$(document).ready(function ($) {
$(document).on('click', '.counter', function() {
var counter = $(this).data('counter');
jQuery('div#counter').html('Loading...') ;
var ajax = jQuery.ajax({
method : 'get',
url : '/test.php', // Link to this page
data : { 'increase' : '1', 'counter': counter }
}) ;
ajax.done(function(data){
jQuery('div#counter').html(data);
});
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable') ;
});
});
});
HTML
Simply add a data attribute to your buttons.
<button class="counter" data-counter="counter_one">Click me</button>
<button class="counter" data-counter="counter_two">Click me</button>
Send the button ID to the server script, and store an associative array in the file in JSON format.
PHP:
<?php
$counterFile = 'counter.json' ;
if ( isset($_GET['increase'], $_GET['button']) )
{
$button_name = $_GET['button'];
if ( ( $counter = #file_get_contents($counterFile) ) === false ) die('Error : file counter does not exist') ;
$count_array = json_decode($counter, true);
$count_array[$button_name] = isset($count_array[$button_name]) ? $count_array[$button_name] + 1 : 1;
file_put_contents($counterFile, json_encode($count_array)) ;
echo $count_array[$button_name] ;
return false ;
}
if ( ! $counter = #file_get_contents($counterFile) )
{
if ( ! $myfile = fopen($counterFile,'w') )
die('Unable to create counter file !!') ;
chmod($counterFile,0644);
file_put_contents($counterFile, json_encode(array())) ;
}
?>
JS:
$('.download').on('click',function(){
jQuery('div#counter').html('Loading...') ;
var ajax = jQuery.ajax({
method : 'get',
url : '/test.php', // Link to this page
data : { 'increase' : '1', button: this.id }
}) ;
ajax.done(function(data){
jQuery('div#counter').html(data) ;
}) ;
ajax.fail(function(data){
alert('ajax fail : url of ajax request is not reachable') ;
}) ;
}) ;
Your making this way harder than you need too. Just use a DB for this. You are already using AJAX so just call the DB with AJAX and count the clicks that way.
php script counterdownload1.php:
<?
$sql = mysql_query("UPDATE download1 SET counter = counter+1");
?>
ajax:
$('#download1').on('click',function(){
// blah blah your code
$.ajax({
type: "POST",
url: "counterdownload1.php"
});
)};
I have made a little AJAX-script for my site, which executes a php-script in another file on submission. I managed to echo out the result in the original file with the AJAX-function, but I have not managed to transfer a variable from the php file to the original one.
I need this variable in order to add an event listener which will look for changes in that particular variable (not sure how to do that either).
Here's are what you are looking for it's working:-
Put this in your forsok.php
<div id="input">
<input type="text" id="number" name="value">
<b id="show_result"></b>
</div>`
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script>
$('#number').on('keyup',function(e){
if(e.which == 13){
var get_var_name = $(this).val();
$.get('result.php',{number:get_var_name},function(data,status){
if(status == 'success'){
alert(data['show']);
$('#show_result').text(data['show']);
}else{
alert('Nothing');
}
});
}
});
</script>
For hej.php:-
<?php
$one=$_GET['number'];
if(empty($one)) {
echo "Can't be blank";
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$show=$one*2;
$arr = array(
'show'=>$show
);
header('Content-Type:application/json');
echo json_encode($arr);
exit();
// echo $show;
} else {
echo "NaN";
$a['result']='null';
$a['error']='nan';
}
}
?>
First create an array of what should be the output. JSON encode that array and then you can parse the output in your ajax success handler. Like in your php file output like:
echo json_encode(array(
'result' => 'null',
'error' => 'nan'
));
Then in you ajax success turn the json into an object and parse data as you want:
success: function (data, textStatus, jqXHR) {
var obj = $.parseJSON(data);
$('#utmatning').html(obj.result); // result value from your json return
$('#utmatning').append(obj.error); // error value from your json return
}
At last of your php file, add,
json_encode($a);
In ajax success,
success: function(html) {
$.each(html, function(index, element) {
alert(element.result);
alert(element.error);
//append to which ever div you want.
});
}
Now with this, you can get n number of array indexes from php
Instead of echoing strings here and there in in hej.php it might better to return JSON data to your ajax call. so you can evaluate if an error occured, which error it is or which valid result has been returned.
hej.php:
<?php
$one=$_GET['value'];
if(empty($one)) {
$a['result']='null';
$a['error'] = 'No value!!';
} else {
if(is_numeric($one)) {
$a['result']=$one*2;
$a['error']='ok';
} else {
$a['result']='null';
$a['error']='nan';
}
}
die(json_encode ($a));
?>
if $value was 1 that would return
{"result":"2","error":"ok"}
In forsok.php you could check the reults and act accordingly
...
$.ajax({
type: "GET",
dataType: "json",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(response)
{
if (response.error=='ok'){
$('#utmatning').html(response.result); // show response from the php script.
}
else{
console.log(response.result); // handle the error
}
}
});
...
Regards,
Stefan
i get the json data from the php to ajax how can i separate the value of the console data just like that
i have to set in my id only the agent name not the hole "name" : "Testing"
This is my console value
[{"agent_module_id":"1","agent_module_number":"101","name":"Testing","description":";;;","agent_mobile":"0123456789","email":"d#gmial.com","category":"","unit_price":null,"cost_price":null,"deleted":"0"}]
This is My PHP Code
$this->load->model("member");
$agent_value = $_POST['agent_value'];
$data["results"] = $this->member->get_agent_data($agent_value);
echo json_encode($data["results"]);
This is my JavaScript Code
function agentForm()
{
var agent_id = document.getElementById("agent_code").value;
if(agent_id !='')
{
document.getElementById("agent_operation_form").style.display ="block";
$.ajax({
url: '<?php echo site_url("members/get_agent_data");?>',
data: { 'agent_value': agent_id},
type: "post",
/* success: function(data){
// document.write(data); //just do not use document.write
var fd_values = data.split(/,/);
document.getElementById("agent_name").value=fd_values[2]; // unique _id
document.getElementById("agent_mobile_number").value=fd_values[1];
console.log(data);*/
success: function(data){
// document.write(data); //just do not use document.write
var fd_values = $.parseJSON(data);
document.getElementById("agent_name").value = fd_values[0].name; // unique _id
document.getElementById("agent_mobile_number").value = fd_values[0].agent_module_number;
console.log(fd_values);
}
}
});
}else
{
document.getElementById("agent_operation_form").style.display ="none";
}
}
Thanx in advance
Try as (Not Tested). You can parse your JSON data using $.parseJSON
success: function(data){
// document.write(data); //just do not use document.write
var fd_values = $.parseJSON(data);
document.getElementById("agent_name").value = fd_values[0].name; // unique _id
document.getElementById("agent_mobile_number").value = fd_values[0].agent_module_number;
console.log(fd_values);
}
I have this php script:
<?php
add_action('wp_ajax_nopriv_getuser', 'getuser');
add_action('wp_ajax_getuser', 'getuser');
function getuser($str)
{
global $wpdb;
if(!wp_verify_nonce($_REQUEST['_nonce'], 'ajax-nonce'))
{
die('Not authorised!');
}
$myoption = get_option( 'fixformdata_options' );
$myoptionValue = maybe_unserialize( $myoption );
$result2 = $wpdb->get_row
(
$wpdb->prepare
(
"SELECT * FROM {$myoptionValue[tablename]} WHERE personeelsNummer = %s", 1
)
);
if($result2)
{
echo json_encode( $result2 );
}
}
And this javascript file:
jQuery(document).ready(function($){
jQuery('#input_1_2').change(function()
{
jQuery.ajax({
type : 'post',
dataType : 'json',
_nonce : myAjax.ajaxurl,
url : myAjax.ajaxurl,
data : {action: 'getuser', value: this.value},
succes: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
});
});
});
Purpose of the scripts:
When a text inputs change, use the value of this text input to display some database data in another text input.
Now I have 2 problems:
I can't get the value of the text input to the function getuser()
When I hardcode a value in the sql statement, I get the results, but they display in the console instead of using:
.
success: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
How can I resolve this, I'm new in Wordpress and Ajax.
By the looks of your php _nonce should be inside data. You cant use this.value as this is the jQuery ajax function itself so Try:
jQuery('#input_1_2').change(function()
$value = $(this).val();
jQuery.ajax({
type : 'post',
dataType : 'json',
url : myAjax.ajaxurl,
data : {
action: 'getuser',
value: $value,
_nonce : myAjax.ajaxurl
},
succes: function(response){
var parsed = JSON.parse(response);
var arr = [];
for(var x in parsed){ arr.push(parsed[x]);}
jQuery('#input_1_3').val(arr[1]);
jQuery('#input_1_4').val(arr[2]);
}
});
});
In the php you will find value in
$_POST['value'];
Edit
inside the php add
header('content-type:application/json');
before
echo json_encode( $result2 );
on the js you shoud then not need
JSON.parse(response)
you shoud have the results in the array, ie:
response[0]
etc