I have
$userPostsInt = array("22", "45", "56");
I am receiving via ajax an id:
$post_id = $_POST['id'];
Then on front end I click and send an ID and I need to check if:
1. the clicked ID is in the array
2. if the array count is <= 2 if not do something
So I try:
$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);
if($count<2) {
foreach($userPostsInt as $key=>$post){
if( $post == $post_id ) {
foreach($userPostsInt as $idInt){
array_push($totSaved, $idInt);
}
echo json_encode($count);
}
}
} else {
echo json_encode($count);
}
Then on ajax success I do:
success: function(data) {
var received = true;
if(received) {
if(data < 2) {
do_something
} else {
do_something
}
} else {
do_something else
}
}
How can I send 2 variable on echo json_encode($count); in order to do a double check for "is ID in the array? Is the array less than 2?" or is it there another way I'm missing?
the simple way to do is use in_array() along with array output:
$totSaved = array();
$userPostsInt = array("22", "45", "56");
$count = count($userPostsInt);
if(in_array($post_id,$userPostsInt)){
echo json_encode(array('found'=>'yes','count'=>$count));
}else{
$totSaved[] = $post_id;//add new value for next time checks
echo json_encode(array('found'=>'no','count'=>$count));
}
Related
I have a drop down box with multiple select . The dropdown looks like this:
<select multiple class="form-control" name="batch_no[]" id="batch_no" required onchange="getBatchCourseDetail();">
<option value="">-----------Select Your Batch----------</option>
<?php
foreach ($result as $res)
{
?>
<option value="<?php echo $res['batch_code']; ?>"><?php echo $res['batch_code']; ?></option>
<?php
} ?>
</select>
In onchange function call i have the script like this:
function getBatchCourseDetail()
{
var other = String($('#batch_no').val());
var opts = [],
opt;
var split1 = other.split(',');
for (var i = 0; i < split1.length; i++)
{
opt = split1[i];
opts.push(opt);
}
$.ajax({
url: 'course_apply_batch_course_detail_ajax.php',
type: 'POST',
data:
{
batch_code: opts
},
success: function (data)
{
//console.log(data);
$('#batch_information_autofill').html(data);
}
});
}
In the ajax file that is in course_apply_course_detail_ajax.php page I retrieve all the values of the drop down .
course_apply_course_detail_ajax.php :
<?php
require('classes/autoloader.php');
$course_apply = new \Model\CourseApplyModel();
$batch_code111=array();
$batch_code111 = $_POST['batch_code'];
$batch_code1 ="'" .implode("','",$batch_code111) ."'";
$parameter = array(
"batchcode" => $batch_code1,
"status" => 0);
$result11 =$course_apply->getBatchCourseDetail11($parameter);
echo"<pre>";
print_r($result11);
echo"</pre>";
exit;
?>
I will be getting the $batch_code1 values as : 'LATS-CHMB-1000','LATS-SA-1000','LATS-ABSE-1003' which is stored in the array variable 'batchcode'.
In Model My query looks like this:
public function getBatchCourseDetail11($parameter)
{
/* $QUERY1="SELECT start_date,end_date,course_code FROM batch WHERE
batch_code IN('LATS-CHMB-1000','LATS-SA-1000','LATS-ABSE-1003') AND status =0"; */
$query1="SELECT start_date,end_date,course_code FROM batch WHERE status =:status AND batch_code IN(:batchcode)";
try{
$result1=$this->dbh->prepare($query1);
$result1->execute($parameter);
$data11=$result1->fetchAll(\PDO::FETCH_ASSOC);
return $data11;
}
catch(\PDOException $e)
{
print_r($e);
return false;
}
}
When i try to print the return data i'm getting array() but the query is executing correctly in the phpmyadmin.
Thanks in advance please help me to get solved from this issue.
The query is your issue
$query1="SELECT start_date,end_date,course_code
FROM batch
WHERE status =:status
AND batch_code IN(:batchcode)";
it is not possible to substitute an arbitrary query part with a placeholder. So for a comma-separated placeholders, like IN(), you must create a set of ?'s manually and put them into the query:
In short we must create a syntax like IN(?,?,?) if you have 3 values you want in your IN() list and then pass the 3 paremeters to the prepare.
public function getBatchCourseDetail11($parameter)
{
// generate the number of ? we need
$ins = str_repeat('?,', count($parameter['batchcode']) - 1) . '?';
$query1="SELECT start_date,end_date,course_code
FROM batch
WHERE status = ?
AND batch_code IN($ins)";
try{
$result1=$this->dbh->prepare($query1);
$params[] = $parameter['status'];
foreach ( $parameter['batchcode'] as $p ) {
$params[] = $p;
}
$result1->execute($params);
$data11=$result1->fetchAll(\PDO::FETCH_ASSOC);
return $data11;
}
catch(\PDOException $e) {
print_r($e);
return false;
}
}
I have a JQuery script that submits user input to a PHP script in the same file, and then displays the result of what the PHP script does with the input. That part works fine. The issue that I’m having is that, upon submission, the JQuery script (at least, I think it's the script) also generates a new submission box below the original.
I’m not sure why. I thought at first that it was an issue with the input type, with the asynchronous part, or even with where I had the form in the overall code, but none of those seem to be playing any role. I'm still a beginner and I'm just not seeing the issue.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<form id = "my_form">
verb <input type = "text" id ="word1"/>
<input type = "submit"/></form>
<div id="name"></div>
<script>
$(document).ready(function(){
$("#my_form").on('submit', function(e)
{
e.preventDefault();
var verb = $ ("#word1").val();
var tag = "#Latin ";
var url = "http://en.wiktionary.org/wiki/"+verb+tag;
$.ajax({
url: "Parser.php",
data: {"verb": verb},
type: "POST",
async: true,
success: function(result){
$("#name").html(result);
$("#name").append(url);
}
});
});
});</script>
RESULT:
PHP
<?php
$bank = array();
function endsWith($haystack, $needle) {
return $needle === "" || (($temp = strlen($haystack) - strlen($needle)) >= 0 && strpos($haystack, $needle, $temp) !== false);
}
function check_end_array($str, $ends)
{
foreach ($ends as $try) {
if (substr($str, -1*strlen($try))===$try) return $try;
}
return false;
}
function db_connect() {
static $connection;
if(!isset($connection)) {
$connection = mysqli_connect('127.0.0.1','username','password','Verb_Bank');
}
if($connection === false) {
return mysqli_connect_error();
}
return $connection;
}
function db_query($query) {
$connection = db_connect();
$result = mysqli_query($connection,$query);
return $result;
}
function db_quote($value) {
$connection = db_connect();
return "'" . mysqli_real_escape_string($connection,$value) . "'";
}
$y = false;
if (isset($_POST['verb'])){
$y=db_quote($_POST['verb']);
echo $y;
echo "\n";
$m = db_query("SELECT `conjugation` FROM normal_verbs WHERE (" . $y . ") LIKE CONCAT('%',root,'%')");
if($m !== false) {
$rows = array();
while ($row = mysqli_fetch_assoc($m)) {
$rows[] = $row;
}
}
foreach ($rows as $key => $value){
if (in_array("first",$value)==true){
echo "first conjugation verb\n";}
$y = $_POST["verb"];
$x = $y;
foreach ($bank as $key => $value)
(series of IF-statements)
}}?>
As Roamer-1888 says's the problem lies in server side, you are returning a html which has a input too. You need to change your code to return only the result string which you append to the div. Else if this is not possible doing at server side as it might require you to change lot of code, then you can strip off the input element from the result and then append it to the div. Like below.
success: function(result){
var div = document.createElement('div');
div.innerHTML = result;
$(div).find('input').remove();
$("#name").html(div.innerHTML);
$("#name").append(url);
}
Hi I am developing an app in phonegap, where I am getting a particular value from server by connecting php file the value I need to pass is a string value 'pmnno'suppose whose value is '2' I need to get the value of '2' in column name 'personalnumber'.. So I am giving my code below
var jsonData;
$.ajax({
type: 'GET',
url: 'http://xxxx.com/app/get_pday1_number.php',
data: { pmnno: '2' },
dataType: 'html',
success: function (response) {
jsonData = response;
alert(jsonData);
}
});
php code
<?php
// array for JSON response
$response = array();
// include db connect class
require_once __DIR__ . '/db_connect.php';
// connecting to db
$db = new DB_CONNECT();
// check for post data
if (isset($_GET["pone"]))
{
$pone = $_GET['pone'];
// get a product from products table
$result = mysql_query("SELECT *FROM pdaynew WHERE pone = $pone");
if (!empty($result)) {
// check for empty result
if (mysql_num_rows($result) > 0) {
$result = mysql_fetch_array($result);
$product = array();
$product["pid"] = $result["pid"];
$product["pone"] = $result["pone"];
$product["personaldayone"] = $result["personaldayone"];
$product["created_at"] = $result["created_at"];
$product["updated_at"] = $result["updated_at"];
// success
$response["success"] = 1;
// user node
$response["product"] = array();
array_push($response["product"], $product);
// echoing JSON response
echo json_encode($response);
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// no product found
$response["success"] = 0;
$response["message"] = "No product found";
// echo no users JSON
echo json_encode($response);
}
} else {
// required field is missing
$response["success"] = 0;
$response["message"] = "Required field(s) is missing";
// echoing JSON response
echo json_encode($response);
}
?>
I am getting a success mesage that means connection is succesful but ineed the value of '2' in column 'personalnumber' for that where I need to add that code..If anyone knows pls help me...
Instead of using * use personaldayone:
$result = mysql_query("SELECT personaldayone FROM pdaynew WHERE pone = $pone");
I try to get the cities according to the country which is passed as parameter and sent via ajax. But for some countries I can get cities and update my form with these cities, for against for other I have this error
{"readyState":0,"responseText":"","status":0,"statusText":"OK"}
When I look in logs for those countries that returns me an error I have the names of the cities retrieved from the database.
I do not understand why this error.
how can I fix it?
Please find below my code
Model
function get_ville_depart($country = null){
$this->db->select('NUMVILLEDEPART, NOMVILLEDEPART')->from('villedepart');
$this->db->join('pays','pays.NUMPAYS=villedepart.numpays');
$this->db->where('pays.NUMPAYS', $country);
$this->db->order_by("NOMVILLEDEPART","asc");
$query = $this->db->get();
$cities = array();
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
}
return $cities;
}else{
return FALSE;
}
}
Controller
function get_ville_depart($country){
foreach($this->ville_model->get_ville_depart($country) as $ville){
log_message('debug',json_encode($ville));
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->ville_model->get_ville_depart($country));
}
View
$('#paysdepart').on("change",function(){
$("#villedepart > option").remove();
var country_id = $('#paysdepart').val();
var base_url="<?= site_url('annonce');?>";
$.ajax({
type: "GET",
url: base_url+"/get_ville_depart/"+country_id,
dataType:'json',
success: function(cities)
{
if(!jQuery.isEmptyObject(cities))
{
$("#ifnotvilledepartindatabase").hide();
$("#dynamicvilledepart").show();
$.each(cities,function(NUMVILLEDEPART,NOMVILLEDEPART)
{
var opt = $('<option />');
opt.val(NUMVILLEDEPART);
opt.text(NOMVILLEDEPART);
$('#villedepart').append(opt);
});
}else
{
$("#dynamicvilledepart").hide();
$("#ifnotvilledepartindatabase").show()
}
},
error:function(error)
{
alert("Error "+JSON.stringify(error));
$("#dynamicvilledepart").hide();
$("#ifnotvilledepartindatabase").show()
}
});
});
Error in those country which does not have any City.
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
}
return $cities;
}else{
return new stdClass; /* Only this line have to change */
}
Use direct URL to see the error for the particuler Country ID.
I have tested in local everything if fine .
Everything seems fine to me, but here my guess about your code :
==> MAKE SURE THE COUNTRY ID IS NEVER EQUAL TO NULL
1 - in your Model, change this,
if($query->result()){
foreach ($query->result() as $city) {
$cities[$city->NUMVILLEDEPART] = $city->NOMVILLEDEPART;
return $cities;
}
else{
return FALSE;
}
to this :
if($result = $query->result_array())
$cities = array_column($result, 'NOMVILLEDEPART', 'NUMVILLEDEPART');
return $cities;
2 - in your Controller, change this :
function get_ville_depart($country){
foreach($this->ville_model->get_ville_depart($country) as $ville){
log_message('debug',json_encode($ville));
}
header('Content-Type: application/json; charset=utf-8');
echo json_encode($this->ville_model->get_ville_depart($country));
}
to this :
function get_ville_depart($country){
$countries = $this->ville_model->get_ville_depart($country);
return $this->output->set_content_type('application/json')
->set_output(json_encode($countries));
}
3 - In your View, Change this :
var country_id = $('#paysdepart').val();
to this :
var country_id = $(this).val();
Note : you can access directly to this page "http://{mywebsite}/get_ville_depart/{country_id}"
with {country_id} equal to the country ID you have a problem with, and check if everything's OK before using the Ajax Query.
My aim is to update a WordPress post using AJAX. My code so far:
Script:
$.ajax({
type: 'POST',
url: ajax_url,
data: {
'action': 'wp_post',
'ID': post_id,
'post_title': post_title
},
success: function( data ) {
$( '.message' )
.addClass( 'success' )
.html( data );
},
error: function() {
$( '.message' )
.addClass( 'error' )
.html( data );
}
});
PHP:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
if ( $id == 0 ) {
$error = 'true';
$response = 'This failed';
echo $response;
} else {
$error = 'false';
$response = 'This was successful';
echo $response;
}
}
As you can see the $response variable in my PHP function is being passed to the success function in my script and the value of $response is displayed on the page.
I want to modify my success function to do something like this:
success: function( data ) {
if( $error == 'true' ) {
// do something
} else {
// do something else
}
},
The problem is, I am having trouble passing both the $response and $error variables in my PHP function to the success function in my scipt.
Can anyone let me know how to pass $response and $error to my script's success function?
Is there a better approach I should be taking?
I'm newish to AJAX so forgive me if the question is very basic.
You shoud encode the response of the php script as json, as follows:
function wp_post() {
$post['ID'] = $_POST['ID'];
$post['post_title'] = $_POST['post_title'];
$post['post_status'] = 'publish';
$id = wp_update_post( $post, true );
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
if( data.status == 'error' ) {
// error handling, show data.message or what you want.
} else {
// same as above but with success
}
},
You can create a JSON array like this one, in the backend:
$arr = array('error' => true, 'something' => 'foo');
echo json_encode($arr);
And then parse the json array to fetch the returned values, like this:
success: function( data ) {
var error = '';
var something = '';
for(var i = 0; i < data.length ; i++)
{
error = data[i].error;
something = data[i].something;
}
if( error ) {
// do something
} else {
// do something else
}
},
Wherea you echoed the array from the backend to the frontend, you can't simply access PHP variables within the JavaScript.
Note that there might be a syntax error, since I'm not testing it.
What you are looking for is json_encode()
This converts a PHP array to JSON.
For example:
$dataArray = array( 'message' => 'Error', 'data' => data);
echo json_encode($dataArray);
You cannot directly use PHP variables within JavaScript. The best you can do is manipulate PHP output in your JavaScript code.
For example, you could print $response as either 'error' or 'no_error' - and in your AJAX callback, check that var data does not equal 'error' (For example).
if you use:
echo json_encode($response);
on your .php function, remember to use:
var data = $.parseJSON(data);
on your ajax success.
Example:
function php_ajax_function() {
// whatever you want to do...
$response = array();
if ( $id == 0 ) {
$response['status'] = 'error';
$response['message'] = 'This failed';
} else {
$response['status'] = 'success';
$response['message'] = 'This was successful';
}
echo json_encode($response);
}
And then, in your javascript code:
success: function( data ) {
console.log(data);
var data = $.parseJSON(data);
if( data.status == 'error' ) {
// do something
} else {
// do other thing
}
}
the javascript variable data contains your echoed $response variable. So using your example, it would be something like this. Be sure you are also asking for html as your return data in the ajax function. here is the docs on that: http://api.jquery.com/jquery.ajax/
success: function( data ) {
if( data == 'This failed' ) {
// do something
} else {
// do something else
}
},