Make a if loop according to what returns the ajax html(data) - ajax

I want to make a if loop according to what returns html(data), so how can I get in my ajax script a var returned by "form_treatment.php" ? I want to close the colorbox (a lightbox) containing myForm only if "form_treatment.php" returns a var PHP with a "true" value.
$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
$('#message').html(data);
// Make a if loop according to what returns html(data)
}
});
return false;
});
form.php :
<form method="post" action="form_treatment.php" >
<input type="text" name="user_name" value="Your name..." />
<button type="submit" >OK</button>
</form>
form_treatment.php :
if ( empty($_POST['user_name']) ){
$a = false;
$b = "Name already used.";
} else {
$already_existing = verify_existence( $_POST['user_name'] );
// verification in the DB, return true or false
if( $already_existing ){
$a = false;
$b = "Name already used.";
} else {
$a = true;
$b = "Verification is OK";
}
}

Try adding dataType : 'json' inside your $.ajax() call, and then, in your php file, respond with nothing but a json object such as:
{ "success" : true, "msg" : 'Verification is OK' }
Then, inside your $.json() success function, you can access anything from the server's response like so:
if (data.success) {
alert(data.msg);
}
I know you said you want to loop, but that's just an example. Note that PHP has a great little function called json_encode() that can turn an array into a json object that your JavaScript will pick up just fine.

$('#myForm').submit(function() {
var myForm = $(this);
$.ajax({
type: 'POST',
url: 'form_treatment.php',
data: myForm.serialize(),
success: function (data) {
// if data is a variable like '$a="Verification is OK"':
eval(data);
if ($a == 'Verification is OK')
$("#colorBox").close() // or whatever the close method is for your plugin
else
$('#message').html($a);
}
});
return false;
});

The var "data" is the response being passed back from your PHP file. Therefore, you can do something like:
...success: function (data) {
if (data == 'Verification is OK') {
// Make a if loop according to what returns html(data)
}
}

You just have to make a simple comparison in your success function in the ajax request, like this:
success: function (data) {
$('#message').html(data);
if(data == 'Verification is OK')
{
// make the lightbox show
}
}

Related

Ajax Request In Order

I'm making litte app to get pages by URL and check their title.
I need check URLs line by line which is user pasted in textarea.
Process sequence :
Check URL > append response to page > then check next url......
Here is my code :
HTML :
<textarea id="textarea" name="urlLine"></textarea>
<button type="button" name="action" id="check">Check IT!</button>
Js :
function getResp(req) {
var uri = req.shift();
$.ajax({
type: 'POST',
url: 'r.php',
async: true,
data: {'uriLine': uri},
success: function (msg) {
$('.collection').append(msg);
$('body').animate({
scrollTop: height,
}, 500)
},
fail: function (msg) {
console.log(msg);
}
});
if (typeof uri !== 'undefined' && uri.length > 0) {
setTimeout(getResp, 5, req);
} else {
alert('Finish');
}
}
$(document).ready(function () {
$('#check').click(function () {
var uris= $('textarea').val().split('\n');
getResp(uris);
});
PHP :
sleep(5); // I don't know why i'm adding. Just wait for performance.
$title = 'title_i_searching';
$adress = $_POST['uriLine'];
if($check->chekURL('https://'.$adress) == $title){
echo ' OK';
}else{
echo 'NOT OK';
}
PHP CLASS :
class checkES
{
public $url;
public function chekURL($url){
$arrContextOptions=array(
"ssl"=>array(
"verify_peer"=>false,
"verify_peer_name"=>false,
),
"http"=>array(
"timeout"=> 5
)
);
$str=
file_get_contents($url,false,stream_context_create($arrContextOptions));
if(strlen($str)>0){
$str = trim(preg_replace('/\s+/', ' ', $str));
preg_match("/\<title\>(.*)\<\/title\>/i",$str,$title);
return $title[1];
}
}
public function parseByLine($content){
$lines = preg_split('/\r\n|[\r\n]/', $content);
return $lines;
}
}
But when i run this code for example; in 20 URL searching on 5th url page alert 'finish'. But append function still continue.
Sometimes, page crash down.
I could not find the healthy method.
I wish i was explain. Sorry for bad language.
Try moving the code to process next uri in success function like this:
function getResp(req) {
var uri = req.shift();
$.ajax({
type: 'POST',
url: 'r.php',
async: true,
data: {'uriLine': uri},
success: function (msg) {
$('.collection').append(msg);
$('body').animate({
scrollTop: height,
}, 500);
if (typeof uri !== 'undefined' && uri.length > 0) {
setTimeout(getResp, 5, req);
} else {
alert('Finish');
}
},
fail: function (msg) {
console.log(msg);
}
});
}

how to pass a variable with the help of ajax jquery into a function directly, which is on another page

how to pass a variable with the help of ajax jquery into a function directly, which is on another page
function show_data2(str1) {
xml2http = new XMLHttpRequest();
xml2http.onreadystatechange = function () {
if (xml2http.readyState === 4 && xml2http.status === 200) {
document.getElementById("show_data_sal").innerHTML = xml2http.responseText;
}
};
xml2http.open("POST", "functions.php?r=" + str1, true);
xml2http.send(str1);
};
functions.php
class querydb
{
function useHere()
{
...I want to use that variable 'r' here.
}
}
If you are using jQuery, this will be the easiest way to send post data via ajax:
var jqxhr = $.ajax( {
method: "POST",
url: "functions.php",
data: { r: "some value", s: "another value" }
})
.done(function() {
alert( "success" );
})
.fail(function() {
alert( "error" );
})
.always(function() {
alert( "complete" );
});
function.php
class querydb
{
function useHere()
{
// We're sending our post data as json so we'll need php to decode it for us to use.
$foo = json_decode($_POST[], true);
// you can now access your variables like an array
$bar = $foo['r'];
}
}
Just be sure to clean anything from post before you do anything with it to prevent any malicious parameters coming through

checking if the success data is empty in ajax method of jquery

I have two select boxes in my form.when a user select an option of first select box the options of second select box will be shown by jquery ajax.My problem is that some options of first select box has no record in database and when they selected the second select box should not be shown.I need to check if the data is empty .I treid this code but nothing happens
view:
<script type='text/javascript'>
$(document).ready(function(){
$('#subsec').hide();
$('section').change(){
var sec_id=$(this).val();
var url='article_controler/get_options/'+sec_id;
$.ajax({
url:url,
type:'post',
success:function(resp){
if(!resp)
$('#subsec').hide();
else
$('#subsec').show();
$('$subsec').html(resp)
})
}
});
</script>
you can try this
$.ajax({
url:url,
type:'post',
success:function(resp){
if(resp == "" || resp == null){
$('#subsec').hide();
}
else {
$('#subsec').show();
$('#subsec').html(resp);
}
})
}
});
I have added inline comments to help you out
class Article_Controller extends CI_Controller
{
public function get_options()
{
$option = $this->input->post('option'); // validate this
//Get a list of Sub options from your model
$model = ''; //your own implementation here
//If no model data returned, send a 404 status header
//and bail
if(!$model){
return $this->output->set_status_header(404);
}
$responce = array(
'suboptions' => $model // array of suboptions the model returned
);
// Ideally Abstract all the Ajax stuff to
// its own controller to keep things Dry
return $this->output
->set_status_header(200)
->set_content_type('application/json')
->set_output(json_encode($responce));
}
}
-
//Global URL variable or put it in <base href>
var URL = "<?php echo site_url();?>";
(function($){
var myForm = {
init : function(){
//initialize myForm object properties here
this.Form = $("form#myFormID");
this.selectChange = this.Form.find("select#mySelectBoxI");
this.newSelect = this.Form.find("select#secondaryselectboxId");
//hide second select with CSS by default
//Bind the Change event to our object(myForm) method
this.selectChange.on('change', $.proxy(this.ChangedEvent, this));
},
ChangedEvent : function(event){ // gets the change event
//Grab the currentTarget(option[i]) value from the event received
//You may also need to pass the CSRF Token
this.buildAjaxRequest({'option' : event.currentTarget.value});
},
buildAjaxRequest : function( data ){
var config = {
cache : false,
url : URL + 'article_controller/get_options',
method : 'POST',
data : data, //'option' : event.currentTarget.value
dataType : 'json'
};
this.makeAjaxRequest(config).then(
$.proxy(this.ResponceHandler, this),
$.proxy(this.ErrorHandler, this)
);
},
makeAjaxRequest : function( config ){
return $.ajax( config ).promise();
},
ResponceHandler : function( data ){
$.each(data.suboptions, function(i, v){
this.newSelect.append('<option value="'.data[i].'">'.data[v].'</option>');');
});
this.newSelect.show();
},
ErrorHandler : function(xhr, statusText, exception){
switch(xhr.status)
{
case 404: //remember the 404 from the controller
alert(xhr.statusText); //handle your own way here
break;
}
},
}
myForm.init();
}(jQuery));
Hi pls try this,
<script type='text/javascript'>
$(document).ready(function(){
$('#subsec').hide();
$('#firstSelectBoxId').change("selectboxMethod");
});
function selectboxMethod(){
var sec_id=$("#firstSelectBoxId").val();
alert("Selected from first select"+sec_id);
if(sec_id != null){
var url='article_controler/get_options/'+sec_id;
$.ajax({
url:url,
type:'post',
success:function(resp){
$('#subsec').show();
$('#subsec').html(resp);
}
});
}else{
$("#subsec").hide();
}
}
</script>

AJAX Form Validation to see if course already exist always return true

I want to validate my course name field if the course name inputted already exist using AJAX, but my ajax function always return the alert('Already exist') even if i inputted data that not yet in the database. Please help. Here is my code. Thanks.
View:
<script type="text/javascript">
var typingTimer;
var doneTypingInterval = 3000;
$('#course_name').keyup(function(){
typingTimer = setTimeout(check_course_name_exist, doneTypingInterval);
});
$('#course_name').keydown(function(){
clearTimeout(typingTimer);
});
function check_course_name_exist()
{
var course_name=$("#course_name").val();
var postData= {
'course_name':course_name
};
$.ajax({
type: "POST",
url: "<?php echo base_url();?>/courses/check_course_name_existence",
data: postData,
success: function(msg)
{
if(msg == 0)
{
alert('Already Exist!');
return false;
}
else
{
alert('Available');
return false;
}
return false;
}
});
$("html, body").animate({ scrollTop: 0 }, 600);
return false;
}
</script>
Controller:
function check_course_name_existence()
{
$course_name = $this->input->post('course_name');
$result = $this->course_booking_model->check_course_name_exist($course_name);
if ($result)
{
return true;
}
else
{
return false;
}
}
Model:
function check_course_name_exist($course_name)
{
$this->db->where("course_name",$course_name);
$query=$this->db->get("courses");
if($query->num_rows()>0)
{
return true;
}
else
{
return false;
}
}
You could use console.log() function from firebug. This way you will know exactly what the ajax returns. Example:
success: function(msg) {
console.log(msg);
}
This way you also know the type of the result variable.
jQuery, and Javascript generally, does not have access to the Boolean values that the PHP functions are returning. So either they return TRUE or FALSE does not make any difference for the JS part of your code.
You should try to echo something in your controller and then make your Javascript comparison based on that value.

Return array from php to ajax success

I want to return an array from a php function to my ajax call. After that I want to use the array values from the page the ajax call is made.
So this is my ajax call:
$(function() {
$("#find").click(function() {
var url = $("#form_url").val();
var dataString = 'url=' + url;
$.ajax({
type: "POST",
url: "/ajax/add_url.php",
data: dataString,
}).done(function( result ) {
myresult(result);
});
return false;
});
});
function myresult(result) {
var result_lines = result.split("<splitter>");
if (result_lines[0] == '1') {
$('#content_error').html(result_lines[1]).fadeIn(250);
$('#content_error').delay(1500).fadeOut(500);
} else if (result_lines[0] == '2') {
$('#content_success').html('Succesfully get images').fadeIn(250);
$('#url_result').delay(500).fadeIn(500);
$('#content_success').delay(1500).fadeOut(500);
alert(eval(data));
}
return true;
}
and this is my php script:
if($_POST['url']) {
$url = $Db->escape($_POST['url']);
$html = file_get_html($url);
$count = 0;
$goodfiles = array();
foreach($html->find('img') as $element) {
$pic = url_to_absolute($url, $element->src);
if(!empty($pic)){
$pics = parse_url($pic);
list($width, $height, $type, $attr) = getimagesize($pic);
if($pics["scheme"]=="http" && $width >= 300 && $height >= 250) {
array_push($goodfiles,$pic);
$_SESSION['pictures'] = $goodfiles;
$count++;
}
}
}
if($count == 0){
$_SESSION['count'] = 'empty';
echo "1<splitter>";
echo "No items found with the correct size";
}else{
$_SESSION['count'] = $count;
echo "2<splitter>";
echo json_encode($_SESSION['pictures']);
}
$_SESSION['url'] = $url;
$html->clear();
$empty = 1;
}
}
when the ajax call is successful I use json_encode on the array to use it on my php page. But I don't know how I get this array to a javascript on the page the ajax call was made of.
right now I'm receiving the following content:
["image.jpeg","image.jpg"]
And I want to put this in a javascript array...
The error is this with this line:
var result_lines = result.split("<splitter>");
result (the AJAX response) is an object or array (depending on the nature of your JSON) but you are trying to call a string method (split()) on it.
This would cause an error in your JS console - always check the console.
Finally, eval() is evil and almost never required except in exceptional circumstances. Try to avoid it.
I don't know how to work with $.ajax but here is an alternative.
Replace this
$.ajax({
type: "POST",
url: "/ajax/add_url.php",
data: dataString,
}).done(function( result ) {
myresult(result);
});
with
$.post("/ajax/add_url.php",{dataString:dataString},function(data){
alert(data['you array index']);
},'json')
I repeat ,this is my alternative so don't take it hard!

Resources